C# 验证码生成
后台:
//生成验证码 public void CreateImage() { //获取4位验证码,并转成小写。 string code = getRandomNumber(4).ToLower(); //验证码赋值Cookie HttpCookie myCookie = new HttpCookie(Constant.LOGIN_VALIDATE_CODE); myCookie.Value = MD5Utils.getMD5(code); myCookie.Expires = DateTime.Now.AddMinutes(15); Response.Cookies.Add(myCookie);//字体名 string strFontName = "宋体"; //字体大小 int intFontSize = 12; //图像宽 int intWidth = 45; //图像长 int intHeight = 20; //背景颜色 Color bgColor = ColorTranslator.FromHtml("#EFB3FF"); //前景颜色 Color foreColor = ColorTranslator.FromHtml("#FF0000"); //产生字体 Font forFont = new Font(strFontName, intFontSize, FontStyle.Bold); //生成图片 Bitmap newBitmap = new Bitmap(intWidth, intHeight, PixelFormat.Format32bppArgb); Graphics g = Graphics.FromImage(newBitmap); //定义一个四方形框与字片一样大小 Rectangle newRect = new Rectangle(0, 0, intWidth, intHeight); //涂上背景色 g.FillRectangle(new SolidBrush(bgColor), newRect); //写字 g.DrawString(code, forFont, new SolidBrush(foreColor), 2, 2); MemoryStream mStream = new MemoryStream(); //存入MemoryStream newBitmap.Save(mStream, ImageFormat.Gif); g.Dispose(); newBitmap.Dispose(); //发送 Response.ClearContent(); Response.ContentType = "image/GIF"; Response.BinaryWrite(mStream.ToArray()); HttpContext.ApplicationInstance.CompleteRequest(); } //生成4位验证码 public static string getRandomNumber(int Length) { System.Text.StringBuilder newRandom = new System.Text.StringBuilder(10); Random rd = new Random(); for (int i = 0; i < Length; i++) { //得到数字(根据情况二选一) newRandom.Append(constant[rd.Next(10)]); //得到字符和数字 newRandom.Append(constant[rd.Next(62)]); } return newRandom.ToString(); }
//验证码库 private static char[] constant = { '0','1','2','3','4','5','6','7','8','9', 'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z', 'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z' };
前台(点击图片触发更改验证码的方法):
<img border="0" class="text4" align="absmiddle" style="cursor: pointer;" onclick="changeImages();" src="" name="createImage" title="点击换一张图片" id="Img3" />
JavaScript:
function changeImages() { var d = new Date(); var obj = document.getElementById('Img'); obj.src = "/Common/CreateImage?tmep_seq=" + d.getTime(); }
changeImages();