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 }