/// <summary> /// 生成验证码图片 /// </summary> public void CreateCheckCodeImage() { string checkCode = VerficationCodeSrc(5); if (checkCode == null || checkCode.Trim() == String.Empty) return; //string checkCode = "asfd2"; Bitmap image = new Bitmap(90, 28); Graphics g = Graphics.FromImage(image); try { //生成随机生成器 Random random = new Random(); //清空图片背景色 g.Clear(Color.White); //画图片的背景噪音线 for (int i = 0; i < 2; i++) { int x1 = random.Next(image.Width); int x2 = random.Next(image.Width); int y1 = random.Next(image.Height); int y2 = random.Next(image.Height); g.DrawLine(new Pen(Color.Black), x1, y1, x2, y2); } Font font = new Font("Arial", 16, (FontStyle.Bold)); System.Drawing.Drawing2D.LinearGradientBrush brush = new System.Drawing.Drawing2D.LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height), Color.Blue, Color.DarkRed, 1.2f, true); g.DrawString(checkCode, font, brush, 2, 2); //画图片的前景噪音点 for (int i = 0; i < 100; i++) { int x = random.Next(image.Width); int y = random.Next(image.Height); image.SetPixel(x, y, Color.FromArgb(random.Next())); } //画图片的边框线 g.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1); System.IO.MemoryStream ms = new System.IO.MemoryStream(); image.Save(ms, System.Drawing.Imaging.ImageFormat.Gif); Response.ClearContent(); Response.ContentType = "image/Gif"; Response.BinaryWrite(ms.ToArray()); } finally { g.Dispose(); image.Dispose(); } } /// <summary> /// 生成验证码字符串 /// </summary> /// <param name="numberOfChars"></param> /// <returns></returns> private string VerficationCodeSrc(int numberOfChars) { if (numberOfChars > 36) { throw new InvalidOperationException("Random Word Charecters can not be greater than 36."); } char[] columns = new char[36]; //字母 for (int charPos = 97; charPos < 97 + 26; charPos++) columns[charPos - 97] = (char)charPos; //数字 for (int intPos = 48; intPos <= 57; intPos++) columns[intPos - 22] = (char)intPos; StringBuilder randomBuilder = new StringBuilder(); Random randomSeed = new Random(); for (int incr = 0; incr < numberOfChars; incr++) { randomBuilder.Append(columns[randomSeed.Next(36)].ToString()); } return randomBuilder.ToString(); }