效果
後臺代碼
protected override void OnPreInit(EventArgs e)
{
//字符 去掉了 o0 i1l
string str = "A,B,C,D,E,F,G,H,G,K,M,N,P,Q,R,S,T,U,V,W,X,Y,Z,2,3,4,5,6,7,8,9";
//顏色
Color[] cs = new Color[] { Color.Red, Color.Green, Color.Black, Color.Blue, Color.Purple };
//字體
string[] fs = { "Verdana", "Microsoft Sans Serif", "Comic Sans MS", "Arial", "宋體" };
//字體大小
int[] size = new int[] { 16, 18, 20 };
//字體樣式
FontStyle[] _fs = new FontStyle[] { FontStyle.Bold, FontStyle.Italic, FontStyle.Regular };
Random ram = new Random();
Bitmap img = new Bitmap(80, 25);
Graphics g = Graphics.FromImage(img);
//清空圖片
g.Clear(Color.White);
//畫干擾線
for (int i = 1; i <= 5; i++)
{
int x1 = ram.Next(img.Width);
int y1 = ram.Next(img.Height);
int x2 = ram.Next(img.Width);
int y2 = ram.Next(img.Height);
Pen p = new Pen(cs[ram.Next(cs.Length)]);
g.DrawLine(p, x1, y1, x2, y2);
}
//畫字符
string[] array = str.Split(',');
string vcode = string.Empty;
for (int i = 1; i <= 4; i++)
{
Font f = new Font(fs[ram.Next(fs.Length)], size[ram.Next(size.Length)], _fs[ram.Next(_fs.Length)]);
Brush b = new SolidBrush(cs[ram.Next(cs.Length)]);
string temp = array[ram.Next(array.Length)];
vcode += temp.ToLower();
if (ram.Next(9) % 2 == 0)
{
g.DrawString(temp, f, b, new Point(20 * (i - 1) + 0, 0));
}
else
{
g.DrawString(temp.ToLower(), f, b, new Point(20 * (i - 1) + 0, 0));
}
}
//畫噪點
for (int i = 1; i <= 30; i++)
{
int x = ram.Next(img.Width);
int y = ram.Next(img.Height);
Color clr = cs[ram.Next(cs.Length)];
img.SetPixel(x, y, clr);
}
//將驗證碼的值保存
Response.Cookies.Add(new HttpCookie("9FDFFFADBEF1A3D9612D39754765D442", StringHelper.EncryptAES(vcode)));
//設置頁面無緩存
Response.Buffer = true;
Response.ExpiresAbsolute = System.DateTime.Now.AddSeconds(-1);
Response.Expires = 0;
Response.CacheControl = "no-cache";
Response.AppendHeader("Pragma", "No-Cache");
//寫入文件流
System.IO.MemoryStream ms = new System.IO.MemoryStream();
img.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
Response.Cache.SetNoStore();
Response.ClearContent();
Response.ContentType = "image/Jpeg";
Response.BinaryWrite(ms.ToArray());
//釋放
g.Dispose();
img.Dispose();
Response.End();
}
前臺調用
<img src="VCode.aspx" alt="看不清,換一個" title="看不清,換一個" style="cursor:pointer;" οnclick="javascript:this.src='VCode.aspx?vc='+Math.random();" />