生成验证码语法(旧版)

一.通过“一般处理程序”返回一张图片:

1.一般处理程序需要先设置ContentType =“image/jpeg

2.一般处理程序需要把图片保存到Response.OutputStream中。

 


代码:

  • 自己创建一张图片

注:File.OpenWrite(@"d:2.jpg")  表示将创建的图片保存的位置!

  • 将本地图片复制到浏览器上
1 context.Response.ContentType = "image/jpeg";
2             string path = context.Server.MapPath("~/lanse22.jpg");
3             using (Stream allfile = File.OpenRead(path))
4             {
5                 allfile.CopyTo(context.Response.OutputStream);
6             }
  • 对图片内容进行添加或修饰
1 context.Response.ContentType = "image/jpeg";
2             string path = context.Server.MapPath("~/lanse22.jpg");
3             using (Image img = Bitmap.FromFile(path))
4             using (Graphics g = Graphics.FromImage(img))
5                 {
6                     g.DrawString("水印", new Font(FontFamily.GenericSansSerif, 50), Brushes.Red, 10, 10);
7                     img.Save(context.Response.OutputStream, ImageFormat.Jpeg);
8                 }
  •  生成简单的数字验证码
 1 context.Response.ContentType = "image/jpeg";
 2             Random rand = new Random();
 3            int number= rand.Next(1000, 10000);
 4            using (Bitmap bm = new Bitmap(55, 25))
 5            using (Graphics g =Graphics.FromImage(bm))
 6            using(Font font =new Font (FontFamily.GenericSansSerif,15))
 7            {
 8                g.DrawString(number.ToString(), font, Brushes.Red, 0, 0);
 9                using (Stream stream = File.OpenWrite("d:\sy.jpg"))
10                {
11                    bm.Save(context.Response.OutputStream, ImageFormat.Jpeg);
12                }
13            }

关于生成的验证码,通过系统产生的随机数存入Session中。在到Sesson中取数据和用户输入的数据进行比对!

具体的操作步骤在后面写Cookie和session中详细介绍!

原文地址:https://www.cnblogs.com/fengxuehuanlin/p/4885111.html