ASP.NET给图片加文字水印
ASP.NET给图片加文字水印ASP.NET给图片加文字水印代码如下:
using System.IO; using System.Drawing; using System.Drawing.Imaging; using System.Drawing.Drawing2D; /// <summary> /// 文字水印处理方法 /// </summary> /// <param name="path">图片路径(绝对路径)</param> /// <param name="size">字体大小</param> /// <param name="letter">水印文字</param> /// <param name="color">颜色</param> /// <param name="location">水印位置</param> public static string LetterWatermark(string path, int size, string letter, Color color, string location) { string kz_name = Path.GetExtension(path); if (kz_name == ".jpg" || kz_name == ".bmp" || kz_name == ".jpeg") { DateTime time = DateTime.Now; string filename = "" + time.Year.ToString() + time.Month.ToString() + time.Day.ToString() + time.Hour.ToString() + time.Minute.ToString() + time.Second.ToString() + time.Millisecond.ToString(); Image img = Bitmap.FromFile(path); Graphics gs = Graphics.FromImage(img); ArrayList loca = GetLocation(location, img, size, letter.Length); Font font = new Font("宋体", size); Brush br = new SolidBrush(color); gs.DrawString(letter, font, br, float.Parse(loca[0].ToString()), float.Parse(loca[1].ToString())); gs.Dispose(); string newpath = Path.GetDirectoryName(path) + filename + kz_name; img.Save(newpath); img.Dispose(); File.Copy(newpath, path, true); if (File.Exists(newpath)) { File.Delete(newpath); } } return path; } /// <summary> /// 文字水印位置的方法 /// </summary> /// <param name="location">位置代码</param> /// <param name="img">图片对象</param> /// <param name="width">宽(当水印类型为文字时,传过来的就是字体的大小)</param> /// <param name="height">高(当水印类型为文字时,传过来的就是字符的长度)</param> private static ArrayList GetLocation(string location, Image img, int width, int height) { ArrayList loca = new ArrayList(); //定义数组存储位置 float x = 10; float y = 10; if (location == "LT") { loca.Add(x); loca.Add(y); } else if (location == "T") { x = img.Width / 2 - (width * height) / 2; loca.Add(x); loca.Add(y); } else if (location == "RT") { x = img.Width - width * height; } else if (location == "LC") { y = img.Height / 2; } else if (location == "C") { x = img.Width / 2 - (width * height) / 2; y = img.Height / 2; } else if (location == "RC") { x = img.Width - height; y = img.Height / 2; } else if (location == "LB") { y = img.Height - width - 5; } else if (location == "B") { x = img.Width / 2 - (width * height) / 2; y = img.Height - width - 5; } else { x = img.Width - width * height; y = img.Height - width - 5; } loca.Add(x); loca.Add(y); return loca; }