BinaryWrite方法输出验证码

在创建网站中验证码是不可或缺的。可以利用BinaryWrite输出二进制图像的方法输出验证码。

在开发图形验证码时,首先生成验证码,然后绘制成图像,最后通过该方法输出到页面中。所以熟练地掌握该方法可以为以后开发图形验证码奠定基础。首先定义个字符串数组,随机去除一个用来做验证码。根据字符串长度创建一个画布Bitmap,接着在Bitmap对象上绘制边框,背景颜色,背景噪音线和前景噪音线,并且将绘制后的二进制图像保存到内存流中,最后通过Response对象的BinaryWrite方法输出到浏览器中。代码如下

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Web;
 5 using System.Web.UI;
 6 using System.Web.UI.WebControls;
 7 using System.Drawing;
 8 using System.Drawing.Drawing2D;
 9 using System.Drawing.Imaging;
10 
11 public partial class _Default : System.Web.UI.Page
12 {
13     protected void Page_Load(object sender, EventArgs e)
14     {
15         //生成随机生成器
16         Random random = new Random();
17         //成语字符串数组,随机去除创建验证码
18         string[] str = { "海阔天高", "望子成龙", "守株待兔", "国足无敌", "点石成金", "天涯明月", "尧尧无敌", "一望无际" };
19         //string checkCode = "海阔天高";
20         int count = random.Next(str.Length);
21         string checkCode = str[count];
22         //根据字符串长度创建一个Bitmap画布
23         Bitmap image = new Bitmap((int)Math.Ceiling((checkCode.Length * 20.5)), 22);
24         Graphics g = Graphics.FromImage(image);
25         try
26         {
27             g.Clear(Color.White);//清空图片背景色
28             for (int i = 0; i < 2; i++)//生成两条随机的噪音线
29             {
30                 int x1 = random.Next(image.Width);
31                 int x2 = random.Next(image.Width);
32                 int y1 = random.Next(image.Height);
33                 int y2 = random.Next(image.Height);
34                 g.DrawLine(new Pen(Color.Black), x1, y1, x2, y2);
35             }
36             Font font = new Font("Arial", 12, (FontStyle.Bold));//定义字体
37             LinearGradientBrush brush = new LinearGradientBrush(
38                 new Rectangle(0, 0, image.Width, image.Height), Color.Blue, Color.DarkRed, 1.2f, true);
39             g.DrawString(checkCode, font, brush, 2, 2);
40             //画图片前景噪音点
41             for (int i = 0; i < 100; i++)
42             {
43                 int x = random.Next(image.Width);
44                 int y = random.Next(image.Height);
45                 image.SetPixel(x, y, Color.FromArgb(random.Next()));
46             }
47             //画图片边框线
48             g.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1);
49             System.IO.MemoryStream ms = new System.IO.MemoryStream();
50             image.Save(ms, ImageFormat.Gif);
51             Response.ClearContent();
52             Response.ContentType = "image/Gif";
53             Response.BinaryWrite(ms.ToArray());
54         }
55         finally
56         {
57             g.Dispose();
58             image.Dispose();
59         }
60     }
61 }

 

posted @ 2013-06-20 15:06  尧设计  阅读(1356)  评论(5编辑  收藏  举报