BinaryWrite方法输出验证码

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

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

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging; public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//生成随机生成器
Random random = new Random();
//成语字符串数组,随机去除创建验证码
string[] str = { "海阔天高", "望子成龙", "守株待兔", "国足无敌", "点石成金", "天涯明月", "尧尧无敌", "一望无际" };
//string checkCode = "海阔天高";
int count = random.Next(str.Length);
string checkCode = str[count];
//根据字符串长度创建一个Bitmap画布
Bitmap image = new Bitmap((int)Math.Ceiling((checkCode.Length * 20.5)), );
Graphics g = Graphics.FromImage(image);
try
{
g.Clear(Color.White);//清空图片背景色
for (int i = ; i < ; i++)//生成两条随机的噪音线
{
int x1 = random.Next(image.Width);
int x2 = random.Next(image.Width);
int y1 = random.Next(image.Height);
int y2 = random.Next(image.Height);
g.DrawLine(new Pen(Color.Black), x1, y1, x2, y2);
}
Font font = new Font("Arial", , (FontStyle.Bold));//定义字体
LinearGradientBrush brush = new LinearGradientBrush(
new Rectangle(, , image.Width, image.Height), Color.Blue, Color.DarkRed, 1.2f, true);
g.DrawString(checkCode, font, brush, , );
//画图片前景噪音点
for (int i = ; i < ; i++)
{
int x = random.Next(image.Width);
int y = random.Next(image.Height);
image.SetPixel(x, y, Color.FromArgb(random.Next()));
}
//画图片边框线
g.DrawRectangle(new Pen(Color.Silver), , , image.Width - , image.Height - );
System.IO.MemoryStream ms = new System.IO.MemoryStream();
image.Save(ms, ImageFormat.Gif);
Response.ClearContent();
Response.ContentType = "image/Gif";
Response.BinaryWrite(ms.ToArray());
}
finally
{
g.Dispose();
image.Dispose();
}
}
}
上一篇:Java API —— Random类


下一篇:Hibernate中的一对一关联