using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Drawing; using System.Drawing.Drawing2D; using System.Drawing.Imaging; using System.IO; public class WaterMark { /// <summary> /// 生成4位字母和数字的验证码图片 /// </summary> /// <returns>验证码的字符串</returns> //public static string GenerateImage(string username) //{ // return CreateImage(username); //} /// <summary> /// 创建验证码图片,并将其写入内存流中 /// </summary> /// <param name="waterText"></param> public static string CreateImage(string waterText) { // 已经存在直接返回 if (File.Exists(System.AppDomain.CurrentDomain.BaseDirectory + "\\watermarks\\" + waterText + ".png")) { return "/watermarks/" + waterText + ".png"; } //验证码未设置时,不生成图片 if (waterText == null || waterText.Trim() == String.Empty) { return null; } Bitmap img = new Bitmap(640, 640); Graphics g = Graphics.FromImage(img); try { //生成随机生成器 Random random = new Random(); //清空图片背景色 g.Clear(Color.Transparent); g.InterpolationMode = InterpolationMode.High; //設定高品質插值法 g.SmoothingMode = SmoothingMode.HighQuality; //設定高品質,低速度呈現平滑程度 g.CompositingQuality = CompositingQuality.HighQuality; g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias; //画图片的背景噪音线 //for (int iCount = 0; iCount < 25; iCount++) //{ // int x1 = random.Next(img.Width); // int x2 = random.Next(img.Width); // int y1 = random.Next(img.Height); // int y2 = random.Next(img.Height); // g.DrawLine(new Pen(Color.Silver), x1, y1, x2, y2); //} Font font = new Font("Arial", 24, (System.Drawing.FontStyle.Bold)); System.Drawing.Drawing2D.LinearGradientBrush brush = new System.Drawing.Drawing2D.LinearGradientBrush(new Rectangle(0, 0, img.Width, img.Height), Color.Black, Color.DarkRed, 1.2f, true); g.RotateTransform(-30); float xpos = 0; float ypos = 0; // 获取图片的宽和高 int width = img.Width; int height = img.Height; // 循环打印文字水印 for (int i = -width / 2; i < width * 1.5; i += 180) { xpos = i; for (int j = -height / 2; j < height * 1.5; j += 80) { ypos = j; g.DrawString(waterText, font, new SolidBrush(Color.FromArgb(50, 210, 210, 210)), xpos, ypos); //g.DrawString(CheckCode, font, brush, 2, 2); } } //画图片的前景噪音点 //for (int i = 0; i < 100; i++) //{ // int x = random.Next(img.Width); // int y = random.Next(img.Height); // img.SetPixel(x, y, Color.FromArgb(random.Next())); //} //画图片的边框线 //g.DrawRectangle(new Pen(Color.Silver), 0, 0, img.Width - 1, img.Height - 1); System.IO.MemoryStream ms = new System.IO.MemoryStream(); img.Save(System.AppDomain.CurrentDomain.BaseDirectory + "\\watermarks\\" + waterText + ".png", System.Drawing.Imaging.ImageFormat.Png); return "/watermarks/" + waterText + ".png"; //Response.ClearContent(); //Response.ContentType = "image/Gif"; //Response.BinaryWrite(ms.ToArray()); //return img; } catch (Exception exp) { throw exp; } finally { g.Dispose(); img.Dispose(); } } }
时间: 2024-10-21 11:25:25