1 protected void Page_Load(object sender, EventArgs e) 2 { 3 string checkCode = "陌上花开,可缓缓归矣"; 4 //创建画板 5 System.Drawing.Bitmap image = new System.Drawing.Bitmap((int)Math.Ceiling((checkCode.Length * 20.5)), 22); 6 Graphics g = Graphics.FromImage(image);//创建Graphics对象 7 try 8 { 9 Random random = new Random();//生成随机生成器 10 g.Clear(Color.White);//清空图片背景色 11 for (int i = 0; i < 2; i++)//画图片的背景噪音线 12 { 13 int x1 = random.Next(image.Width); 14 int x2 = random.Next(image.Width); 15 int y1 = random.Next(image.Height); 16 int y2 = random.Next(image.Height); 17 g.DrawLine(new Pen(Color.Black), x1, y1, x2, y2); 18 } 19 Font font = new System.Drawing.Font("Arial", 12, (System.Drawing.FontStyle.Bold)); 20 System.Drawing.Drawing2D.LinearGradientBrush brush = new System.Drawing.Drawing2D.LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height), Color.Gray, Color.DarkBlue, 1.2f, true); 21 g.DrawString(checkCode, font, brush, 2, 2); 22 for (int i = 0; i < 100; i++)//画图片的前景噪音点 23 { 24 int x = random.Next(image.Width); 25 int y = random.Next(image.Height); 26 image.SetPixel(x, y, Color.FromArgb(random.Next())); 27 } 28 g.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1); 29 System.IO.MemoryStream ms = new System.IO.MemoryStream();//画图片的边框线 30 image.Save(ms, System.Drawing.Imaging.ImageFormat.Gif); 31 Response.ClearContent(); 32 Response.ContentType = "image/Gif"; 33 Response.BinaryWrite(ms.ToArray()); 34 } 35 finally 36 { 37 g.Dispose(); 38 image.Dispose(); 39 } 40 }
运行效果: