C#图片添加文字水印

时间:2021-07-21 08:38:31
/// <summary>
/// 给图片添加文字水印
/// </summary>
/// <param name="img">图片</param>
/// <param name="text">文字</param>
/// <param name="p">文本位置中心点坐标</param>
/// <param name="font">字体</param>
/// <param name="fontColor">字体颜色</param>
/// <param name="angle">旋转角度(顺时针)</param>
/// <returns></returns>
public static Image AddText2Image(Image img, string text,Point p, Font font, Color fontColor, int angle)
{
  using (var g = Graphics.FromImage(img))
  using(var brush=new SolidBrush(fontColor))
  {
    g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
    g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
    var sizeF = g.MeasureString(text,font);
    g.ResetTransform();
    g.TranslateTransform(p.X,p.Y);
    g.RotateTransform(angle);
    g.DrawString(text,font,brush,new PointF(-sizeF.Width/2,-sizeF.Height/2));
  }
  return img;
}