先定义一个制作验证码的类:
using System;
using System.Web;
using System.Drawing;
using System.Drawing.Imaging;
namespace Identifying_Code
{
public class CheckCode
{
//不在页面代码文件中,没有继承page类,所以Responce对象要自己定义
private HttpResponse Response;
public CheckCode(HttpResponse response)
{
this.Response = response;
}
//创建有随机数和随机字符组成的字符串
public string stringCode(int length)
{
Random random = new Random();
string checkCode = "0123456789ABCDEFGHJKLMNOPQUVWXYZ";
string selectCode = null;// " "等价于string.Empty,它表示的是空字符而不是字符串为空
for (int i = 1; i <= length; i++)
{
int count = random.Next(checkCode.Length);//返回小于checkCode.Length的随机非负数,返回的是一个int整数
selectCode += checkCode[count];
}
return selectCode;
}
//创建一个由随机字符和数字生成的图像
public void createImage(string checkCode)
{
if (string.IsNullOrEmpty(checkCode))
return;
Bitmap bm = new Bitmap((int)Math.Ceiling((checkCode.Length * 12.5)), 22);//设置宽度和高度创建位图对象
Graphics g = Graphics.FromImage(bm);//根据位图对象创建Graphics对象
g.Clear(Color.White);//将背景色填充为白色
//g.DrawEllipse(new Pen(new SolidBrush(Color.Silver)),10,10,180,40);//画椭圆
//g.DrawString("hello world!",new Font("宋体",18),new SolidBrush(Color.Red),20,20);//画字符
//画图片背景噪音线
Random random = new Random();
for (int i = 0; i < 44; i++)
{
int x1 = random.Next(bm.Width - i);
int x2 = random.Next(bm.Width);
int y1 = random.Next(bm.Height);
int y2 = random.Next(bm.Height);
g.DrawLine(new Pen(Color.Silver), x1, x2, y1, y2);
}
//定义字体
Font font = new Font("Arial", 12, (FontStyle.Bold | FontStyle.Italic));
//定义画刷
System.Drawing.Drawing2D.LinearGradientBrush brush = new
System.Drawing.Drawing2D.LinearGradientBrush(
new Rectangle(0, 0, bm.Width, bm.Height), Color.Blue, Color.DarkRed, 1.2f, true);
g.DrawString(checkCode, font, brush, 2, 2);
//g.DrawString(checkCode,new Font("宋体",18),new SolidBrush(Color.Red),20,20);
//画图片的前景噪音点
for (int i = 0; i < 88; i++)
{
int x = random.Next(bm.Width);
int y = random.Next(bm.Height);
bm.SetPixel(x, y, Color.FromArgb(random.Next()));//指点所描点的颜色
}
//画图片的边框线
g.DrawRectangle(new Pen(Color.Silver), 0, 0, bm.Width - 1, bm.Height - 1);
//将图片以Gif的形式放入内存流中,也可以用png,jpg试试效果
System.IO.MemoryStream ms = new System.IO.MemoryStream();
Response.Cache.SetNoStore();//不缓存,用户码在用户提交后立即改变.
bm.Save(ms, ImageFormat.Gif);
//写图片1
//Response.ClearContent();
//Response.ContentType = "image/Gif";
//Response.BinaryWrite(ms.ToArray());
//写图片2
bm.Save(Response.OutputStream, ImageFormat.Gif);//用位图的方法输出
}
}
}
在页面中显示:
using System;
namespace Identifying_Code
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
CheckCode image = new CheckCode(this.Response);
string stringcode = image.stringCode(4);//自动生成数字和字母
image.createImage(image.stringCode(4));//用生成的数字和字母创建验证码
}
}
}