动态生成验证码

知识点:

1. 对图像的操作

 

问题:

动态生成验证码

 

解决方案

 1 <%@ WebHandler Language="C#" Class="ValidateCode" %>

 2 

 3 using System;

 4 using System.Web;

 5 using System.Drawing;

 6 using System.IO;

 7 

 8 public class ValidateCode : IHttpHandler {

 9     

10     public void ProcessRequest (HttpContext context) {

11         context.Response.ContentType = "text/plain";

12         //context.Response.Write("Hello World");

13         Random r = new Random();

14         int n = r.Next(10000,100000);

15         CreateValidateGraphic(n.ToString(),context);

16     }

17     /// <summary>

18     /// 创建验证码的图片

19     /// </summary>

20     /// <param name="containsPage">要输出到的page对象</param>

21     /// <param name="validateNum">验证码</param>

22     public void CreateValidateGraphic(string validateCode, HttpContext context)

23     {

24         Bitmap image = new Bitmap((int)Math.Ceiling(validateCode.Length * 12.0), 22);

25         Graphics g = Graphics.FromImage(image);

26         try

27         {

28             //生成随机生成器

29             Random random = new Random();

30             //清空图片背景色

31             g.Clear(Color.White);

32             //画图片的干扰线

33             for (int i = 0; i < 25; i++)

34             {

35                 int x1 = random.Next(image.Width);

36                 int x2 = random.Next(image.Width);

37                 int y1 = random.Next(image.Height);

38                 int y2 = random.Next(image.Height);

39                 g.DrawLine(new Pen(Color.Silver), x1, y1, x2, y2);

40             }

41             Font font = new Font("Arial", 12, (FontStyle.Bold | FontStyle.Italic));

42             System.Drawing.Drawing2D.LinearGradientBrush brush = new System.Drawing.Drawing2D.LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height),

43              Color.Blue, Color.DarkRed, 1.2f, true);

44             g.DrawString(validateCode, font, brush, 3, 2);

45             //画图片的前景干扰点

46             for (int i = 0; i < 100; i++)

47             {

48                 int x = random.Next(image.Width);

49                 int y = random.Next(image.Height);

50                 image.SetPixel(x, y, Color.FromArgb(random.Next()));

51             }

52             //画图片的边框线

53             g.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1);

54             //保存图片数据

55             MemoryStream stream = new MemoryStream();

56             image.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);

57             //输出图片流

58             context.Response.Clear();

59             context.Response.ContentType = "image/jpeg";

60             context.Response.BinaryWrite(stream.ToArray());

61         }

62         finally

63         {

64             g.Dispose();

65             image.Dispose();

66         }

67     }

68 

69     public bool IsReusable {

70         get {

71             return false;

72         }

73     }

74 

75 }
View Code

 

你可能感兴趣的:(验证码)