using System;using System.Collections.Generic;using System.Text;using System.Drawing;using System.Drawing.Imaging;using System.IO;using System.Collections;
namespace ValidateCode{ public class VCode { public MemoryStream DrawVCode(string content) { System.Random random = new Random();
//创建图片对象 System.Drawing.Bitmap image = new Bitmap((int)content.Length * 17, 30); Graphics gh = Graphics.FromImage(image);
ArrayList bgcolor = new ArrayList(); bgcolor.Add(Color.Honeydew); bgcolor.Add(Color.AliceBlue); bgcolor.Add(Color.White); bgcolor.Add(Color.Azure); bgcolor.Add(Color.OldLace); bgcolor.Add(Color.Lavender); gh.Clear((Color)bgcolor[random.Next(0, 5)]);
//噪音线颜色数组 System.Collections.ArrayList c = new ArrayList(); c.Add(Color.Silver); c.Add(Color.SeaShell); c.Add(Color.SkyBlue);
for (int i = 0; i < 25; i++) { int x1 = random.Next(image.Width); int x2 = random.Next(image.Width); int y1 = random.Next(image.Height); int y2 = random.Next(image.Height);
gh.DrawLine(new Pen((Color)c[random.Next(0, 2)]), x1, y1, x2, y2); } //噪音点 for (int i = 0; i < 200; i++) { int x = random.Next(1, image.Width - 2); int y = random.Next(1, image.Height - 2);
image.SetPixel(x, y, Color.FromArgb(random.Next())); }
//设定字体颜色 System.Collections.ArrayList cb = new ArrayList(); cb.Add(Color.Black); cb.Add(Color.DarkBlue); cb.Add(Color.Purple); cb.Add(Color.Indigo); cb.Add(Color.DarkRed); cb.Add(Color.IndianRed); char[] CArray = content.ToCharArray(); for (int i = 0; i < CArray.Length; i++) { string cstr = CArray[i].ToString(); Font f = new Font("Times New Roman", 15); gh.DrawString(cstr, f, new SolidBrush((Color)cb[random.Next(0, 5)]), 2 + ((int)f.SizeInPoints) * i, 2); }
gh.DrawRectangle(new Pen((Color)cb[random.Next(0, 5)]), 0, 0, image.Width - 1, image.Height - 1); //汇出边框
System.IO.MemoryStream ms = new System.IO.MemoryStream(); image.Save(ms, System.Drawing.Imaging.ImageFormat.Gif); Response.ClearContent(); return ms.ToArray(); }
}}==========编译成组件