直接上code:
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.Imaging;
namespace AnalyzerExtAuth.Common
{
public partial class ValidateCodeImg : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//验证码中可能会出现的字符集合
String checkCodeString = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
//验证码字符集合的长度
int length = checkCodeString.Length;
//设置绘制验证码的字体,并设置为粗体并倾斜
Font font = new Font("宋体", 24, (FontStyle.Bold | FontStyle.Italic));
//绘制验证码的笔刷
Brush brush = null;
//绘制验证码文字的颜色
Color brushColor = new Color();
//验证码的字符串
String checkCode = String.Empty;
//当前要绘制的验证字符
String code = String.Empty;
//要生成的验证码图片对象
Bitmap image = new Bitmap(80, 40);
//绘图画板
Graphics graphics = Graphics.FromImage(image);
//填充背景为白色
graphics.Clear(Color.White);
//创建随机数对象
Random random = new Random();
int x1, x2, y1, y2;
Pen pen = new Pen(Color.Silver);
//画背景噪音线
for (int i = 1; i <= 25; i++)
{
x1 = random.Next(image.Width);
y1 = random.Next(image.Height);
x2 = random.Next(image.Width);
y2 = random.Next(image.Height);
graphics.DrawLine(pen, x1, y1, x2, y2);
}
for (int i = 0; i < 4; i++)
{
//为了保证取的字符索引不超过0-35之间
//取任何数的余数都肯定小于自身
//采用当前时间的毫秒 % 验证码字符的总长度=当前验证字符
int current = random.Next(DateTime.Now.Millisecond) % length;
//截取验证字符
code = checkCodeString.Substring(current, 1);
//拼接到验证码的字符串
checkCode += code;
//随机生成验证码字符的颜色
brushColor = Color.FromArgb(random.Next(256), random.Next(256), random.Next(256));
//笔刷的颜色
brush = new SolidBrush(brushColor);
//绘制刚刚得到的字符串
graphics.DrawString(code, font, brush, i * 15 + 2, 2);
}
Response.Clear();
Response.ContentType = "image/pjpeg";
//在Session中保存验证码字符串,以便与用户输入进行比较
Session["CheckCode"] = checkCode;
image.Save(Response.OutputStream, ImageFormat.Jpeg);
image.Dispose();
Response.End();
}
}
}
//验证控件
< img src = "ValidateCode.aspx" width = "60" height = "25" style = "cursor: pointer;" onclick = "this.src='ValidateCode.aspx?id'+Math.random()*10000" / >
P.S.其中id加上一个随机数只是为了网页能够刷新重新计算验证码。当然我们还可以在后面添加生成验证码的长度,以便更好的管理验证码复杂性