public class TxtWaterMark{public enum WaterPositionMode{LeftTop,//左上LeftBottom,//左下RightTop,//右上RightBottom,//右下Center,//中间Other//其他,若选此项AddWaterText方法内自己把xValue和yValue穿进去 }/// <summary>/// 给图片加文字水印/// </summary>/// <param name="oldpath">图片地址</param>/// <param name="savepath">加上文字水印以后图片保存地址</param>/// <param name="watertext">水印文字</param>/// <param name="position">水印位置</param>/// <param name="fontName">水印文字字体</param>/// <param name="fontSize">水印文字大小</param>/// <param name="color">水印文字颜色</param>/// <param name="alpha">水印文字透明度</param>/// <param name="isBold">水印文字是否加粗</param>/// <param name="xValue">水印位置position Other选项下设置</param>/// <param name="yValue">水印位置position Other选项下设置</param>public static void AddWaterText(string oldpath, string savepath, string watertext, WaterPositionMode position, string fontName, int fontSize, string fontColor, int alpha, bool isBold, float xValue = 0, float yValue = 0){Image image = Image.FromFile(oldpath);Bitmap bitmap = new Bitmap(image.Width, image.Height);Graphics graphics = Graphics.FromImage(bitmap);graphics.Clear(Color.White);graphics.DrawImage(image, new Rectangle(0, 0, image.Width, image.Height), 0, 0, image.Width, image.Height, GraphicsUnit.Pixel);Font font = new Font(fontName, fontSize, FontStyle.Bold);if (!isBold){font = new Font(fontName, fontSize);}SizeF ziSizeF = new SizeF();ziSizeF = graphics.MeasureString(watertext, font);float x = 0f;float y = 0f;switch (position){case WaterPositionMode.LeftTop:x = ziSizeF.Width / 2f;y = 0f;break;case WaterPositionMode.LeftBottom:x = ziSizeF.Width / 2f;y = image.Height - ziSizeF.Height;break;case WaterPositionMode.RightTop:x = image.Width * 1f - ziSizeF.Width / 2f;y = 0f;break;case WaterPositionMode.RightBottom:x = image.Width - ziSizeF.Width;y = image.Height - ziSizeF.Height;break;case WaterPositionMode.Center:x = image.Width / 2;y = image.Height / 2 - ziSizeF.Height / 2;break;case WaterPositionMode.Other:x = xValue + ziSizeF.Width / 2f;y = yValue;break;}try{StringFormat stringFormat = new StringFormat { Alignment = StringAlignment.Center };SolidBrush solidBrush = new SolidBrush(Color.FromArgb(alpha < 0 ? 0 : alpha, 0, 0, 0));graphics.DrawString(watertext, font, solidBrush, x + 1f, y + 1f, stringFormat);SolidBrush brush = new SolidBrush(Color.FromArgb(alpha < 0 ? 0 : alpha, ColorTranslator.FromHtml(fontColor)));graphics.DrawString(watertext, font, brush, x, y, stringFormat);solidBrush.Dispose();brush.Dispose();bitmap.Save(savepath, ImageFormat.Png);}catch (Exception e){}finally{bitmap.Dispose();image.Dispose();}}}