using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Drawing; using System.Drawing.Drawing2D; using System.IO; /// <summary> ///Img 的摘要说明 /// </summary> public class Img { public Img() { // //TODO: 在此处添加构造函数逻辑 // } public string getstr(int len) { string str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; Random rd = new Random(); string code = ""; for (int i = 0; i < len; i++) { code += str.Substring(rd.Next(0, str.Length), 1);//从第一个开始截取一个 } return code; } public void getimg(int len, out string checkString) { checkString = getstr(len); if (checkString.Trim() == "" || checkString == null) { return; } Bitmap bmp = new Bitmap((int)(checkString.Length * 18), 23); Graphics g = Graphics.FromImage(bmp); g.Clear(Color.White); try { Random rd = new Random(); for (int i = 0; i < 20; i++) { int x1 = rd.Next(bmp.Width); int x2 = rd.Next(bmp.Width); int y1 = rd.Next(bmp.Height); int y2 = rd.Next(bmp.Height); g.DrawLine(new Pen(Color.Silver), x1, y1, x2, y2); } Font font = new Font("Arial", 16, System.Drawing.FontStyle.Italic); LinearGradientBrush brush = new LinearGradientBrush(new Rectangle(0, 0, bmp.Width, bmp.Height), Color.Blue, Color.Red, 1.2f); g.DrawString(checkString, font, brush, 5, 0); g.DrawRectangle(new Pen(Color.Silver), 0, 0, bmp.Width - 1, bmp.Height - 1); System.IO.MemoryStream ms = new System.IO.MemoryStream(); //string imgPath = System.Web.HttpContext.Current.Server.MapPath("~/image/"); //bmp.Save(imgPath + "chk.gif", System.Drawing.Imaging.ImageFormat.Gif); //存储到文件 bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Gif); HttpContext.Current.Response.ClearContent(); HttpContext.Current.Response.ContentType = "image/Gif"; HttpContext.Current.Response.BinaryWrite(ms.ToArray()); //输出流 } finally { bmp.Dispose(); g.Dispose(); } } }