關於生成驗證碼的代碼 網上很多
這裏就只弄個生成驗證碼圖片的代碼
生成效果
/// <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清空掉.否則就可以跳過驗證碼,就失去驗證碼的意義了。