/// <summary>
/// 图片添加水印
/// </summary>
/// <param name="imgPath">需要添加水印的图片地址</param>
/// <param name="outPath">添加水印后图片输出地址</param>
/// <param name="watermarkText">水印文字</param>
/// <param name="pellucidity">水印文字透明度</param>
/// <param name="fontSize">水印文字大小</param>
public static void ImageAddWatermark(string imgPath, string outPath, string watermarkText, int pellucidity, int fontSize)
{
打开图片以流的形式读取
System.IO.FileStream fileStream = new System.IO.FileStream(imgPath, System.IO.FileMode.Open);
System.IO.BinaryReader br = new System.IO.BinaryReader(fileStream);
byte[] bytes = br.ReadBytes((int)fileStream.Length);
fileStream.Close();
br.Close();
System.IO.MemoryStream memoryStream = new System.IO.MemoryStream(bytes);//将图片字节赋值到新数据流
//创建新图片
System.Drawing.Image image = System.Drawing.Image.FromStream(memoryStream);
int width = image.Width, height = image.Height;
//新建一个位图宽高为图片宽高
System.Drawing.Bitmap map = new System.Drawing.Bitmap(width, height, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
map.SetResolution(72, 72);//分辨率
System.Drawing.Graphics graphics = System.Drawing.Graphics.FromImage(map);
graphics.Clear(System.Drawing.Color.FromName("white"));//背景色
graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;//呈现方式
graphics.DrawImage(image, new System.Drawing.Rectangle(0, 0, width, height), 0, 0, width, height, System.Drawing.GraphicsUnit.Pixel);
System.Drawing.Font font = new System.Drawing.Font("宋体", fontSize, System.Drawing.FontStyle.Bold);
System.Drawing.SizeF crSize = graphics.MeasureString(watermarkText, font);// 测量指定区域
float y = height - crSize.Height;
float x = width - crSize.Width;
System.Drawing.StringFormat StrFormat = new System.Drawing.StringFormat()
{
Alignment = System.Drawing.StringAlignment.Center,//水平对其方式
LineAlignment = System.Drawing.StringAlignment.Center,//垂直对齐方式
};
//重复绘制造成透明效果
System.Drawing.SolidBrush semiTransBrush2 = new System.Drawing.SolidBrush(System.Drawing.Color.FromArgb(pellucidity, 56, 56, 56));
graphics.DrawString(watermarkText, font, semiTransBrush2, x + 1, y + 1);
System.Drawing.SolidBrush semiTransBrush = new System.Drawing.SolidBrush(System.Drawing.Color.FromArgb(pellucidity, 176, 176, 176));
graphics.DrawString(watermarkText, font, semiTransBrush, x, y);
//保存
map.Save(outPath, System.Drawing.Imaging.ImageFormat.Jpeg);
graphics.Dispose();
image.Dispose();
map.Dispose();
System.Diagnostics.Process.Start(outPath);
}
效果图如下:
仅个人记录