随机验证码生成

本文介绍了一种使用C#生成带有验证码的图片的方法。该方法通过绘制随机线条和设置字体样式来增加图片的复杂度,并通过随机像素点提高抗噪能力。
 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

 

转载于:https://www.cnblogs.com/zyblogs/p/4829164.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值