using System; using System.Drawing; using System.Drawing.Drawing2D; using System.Drawing.Imaging; using System.IO; using System.Web; namespace Common { public class Identify { public static void DrawIdentifyCode(string strIdentifyCode, int intFgNoise, int intBgNoise) { if (strIdentifyCode == null || strIdentifyCode.Trim() == string.Empty) return; Bitmap bitmap = new Bitmap((int) Math.Ceiling((double) strIdentifyCode.Length * 12.5), 20); Graphics graphics = Graphics.FromImage((Image) bitmap); try { Random random = new Random(); graphics.Clear(Color.White); for (int index = 0; index < intBgNoise; ++index) { int x1 = random.Next(bitmap.Width); int x2 = random.Next(bitmap.Width); int y1 = random.Next(bitmap.Height); int y2 = random.Next(bitmap.Height); graphics.DrawLine(new Pen(Color.Silver), x1, y1, x2, y2); } Font font = new Font("Arial", 12f, FontStyle.Bold | FontStyle.Italic); LinearGradientBrush linearGradientBrush = new LinearGradientBrush(new Rectangle(0, 0, bitmap.Width, bitmap.Height), Color.Blue, Color.DarkRed, 1.2f, true); graphics.DrawString(strIdentifyCode, font, (Brush) linearGradientBrush, 2f, 2f); for (int index = 0; index < intFgNoise; ++index) { int x = random.Next(bitmap.Width); int y = random.Next(bitmap.Height); bitmap.SetPixel(x, y, Color.FromArgb(random.Next())); } graphics.DrawRectangle(new Pen(Color.Silver), 0, 0, bitmap.Width - 1, bitmap.Height - 1); MemoryStream memoryStream = new MemoryStream(); bitmap.Save((Stream) memoryStream, ImageFormat.Gif); HttpContext.Current.Response.ClearContent(); HttpContext.Current.Response.ContentType = "image/Gif"; HttpContext.Current.Response.BinaryWrite(memoryStream.ToArray()); } finally { graphics.Dispose(); bitmap.Dispose(); } } public static string IdentifyCode(int intLength) { string str = string.Empty; Random random = new Random(); for (int index = 0; index < intLength; ++index) { int num = random.Next(); char ch = num % 2 != 0 ? (char) (65U + (uint) (ushort) (num % 26)) : (char) (48U + (uint) (ushort) (num % 10)); str += ch.ToString(); } return str; } } }