码迷,mamicode.com
首页 > 其他好文 > 详细

随机验证码生成

时间:2015-09-22 16:23:38      阅读:217      评论:0      收藏:0      [点我收藏+]

标签:

技术分享
 1 public static void CreateValidateGraphic(string validateCode, HttpContext httpContext)
 2     {
 3         Bitmap img = new Bitmap((int)Math.Ceiling(validateCode.Length * 12.0), 20);
 4         Graphics g = Graphics.FromImage(img);
 5         try
 6         {
 7             Random random = new Random();
 8             g.Clear(Color.White);
 9 
10             //图片的干扰线
11             for (int i = 0; i < 25; i++)
12             {
13                 int x1 = random.Next(img.Width);
14                 int x2 = random.Next(img.Width);
15                 int y1 = random.Next(img.Height);
16                 int y2 = random.Next(img.Height);
17                 g.DrawLine(new Pen(Color.Silver), x1, y1, x2, y2);
18             }
19             Font font = new Font("Arial", 12, (FontStyle.Bold | FontStyle.Italic));
20             System.Drawing.Drawing2D.LinearGradientBrush brush = new LinearGradientBrush(
21                 new Rectangle(0, 0, img.Width, img.Height), Color.Blue, Color.DarkRed, 1.2f, true);
22             g.DrawString(validateCode, font, brush, 3, 2);
23             //图片前景干扰点
24             for (int i = 0; i < 100; i++)
25             {
26                 int x = random.Next(img.Width);
27                 int y = random.Next(img.Height);
28                 img.SetPixel(x,y,Color.FromArgb(random.Next()));
29                 
30             }
31             //图片边框线
32             g.DrawRectangle(new Pen(Color.Silver),0,0,img.Width-1,img.Height-1 );
33             MemoryStream memoryStream=new MemoryStream();
34             img.Save(memoryStream,ImageFormat.Jpeg);
35             httpContext.Response.Clear();
36             httpContext.Response.ContentType = "image/jpeg";
37             httpContext.Response.BinaryWrite(memoryStream.ToArray());
38         }
39         catch (Exception)
40         {
41 
42             throw;
43         }
44     }
View Code

 

随机验证码生成

标签:

原文地址:http://www.cnblogs.com/zyblogs/p/4829164.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!