关于生成验证码的代码 网上很多
这里就只弄个生成验证码图片的代码
生成效果
/// <summary> /// 生成图片验证码 /// </summary> /// <param name="iCount">验证码的字符数(注意: 一个汉字为两个字符)</param> /// <param name="sValidate">验证码</param> /// <returns>图片字节流</returns> public static byte[] CreateImage(int iCount, string sValidate) { int iBmpWidth = 13 * iCount + 5; int iBmpHeight = 25; Bitmap bmp = new Bitmap(iBmpWidth, iBmpHeight);
//生成随机背景颜色 int iRed, iGreen, iBlue; // 背景的三元色 Random rd = new Random((int)System.DateTime.Now.Ticks); iRed = rd.Next(255) % 128 + 128; iGreen = rd.Next(255) % 128 + 128; iBlue = rd.Next(255) % 128 + 128;
//填充位图背景 Graphics graph = Graphics.FromImage(bmp); graph.FillRectangle(new SolidBrush(Color.FromArgb(iRed, iGreen, iBlue)), 0, 0, iBmpWidth, iBmpHeight);
//绘制干扰线条,采用比背景略深一些的颜色 Pen pen = new Pen(Color.FromArgb(iRed - 17, iGreen - 17, iBlue - 17), 2); for (int a = 0; a < 3; a++) { int x1 = rd.Next() % iBmpWidth; int y1 = rd.Next() % iBmpHeight; int x2 = rd.Next() % iBmpWidth; int y2 = rd.Next() % iBmpHeight; graph.DrawLine(pen, x1, y1, x2, y2); }
//生成字体 Font font = new Font("Courier New", 12 + rd.Next() % 4, FontStyle.Bold);
//绘图 graph.DrawString(sValidate, font, new SolidBrush(Color.FromArgb(iRed - 60, iGreen - 60, iBlue - 40)), 2, 3);
System.IO.MemoryStream bstream = new System.IO.MemoryStream(); bmp.Save(bstream, System.Drawing.Imaging.ImageFormat.Jpeg);
bmp.Dispose(); graph.Dispose();
byte[] byteReturn = bstream.ToArray(); bstream.Close();
return byteReturn; } |
需要注意的是,如果是用Session保存验证码,在验证成功后,记得把保存验证码的 Session清空掉.否则就可以跳过验证码,就失去验证码的意义了。