C# 给图片添加文字水印
/// <summary> /// 文字水印 /// </summary> /// <param name="filename">保存文件名</param> /// <param name="watermarkText">水印文字</param> /// <param name="watermarkStatus">图片水印位置 0=不使用 1=左上 2=中上 3=右上 4=左中 9=右下</param> /// <param name="fontsize">字体大小</param> public static void AddImageSignText(string fileName, string watermarkText, int watermarkStatus, Font drawFont, SolidBrush brush) { System.Drawing.Image img = System.Drawing.Image.FromFile(fileName); Bitmap map = new Bitmap(img); Graphics g = Graphics.FromImage(map); SizeF crSize = g.MeasureString(watermarkText, drawFont); float xpos = 0; float ypos = 0; switch (watermarkStatus) { case 1: xpos = (float)img.Width * (float).01; ypos = (float)img.Height * (float).01; break; case 2: xpos = ((float)img.Width * (float).50) - (crSize.Width / 2); ypos = (float)img.Height * (float).01; break; case 3: xpos = ((float)img.Width * (float).99) - crSize.Width; ypos = (float)img.Height * (float).01; break; case 4: xpos = (float)img.Width * (float).01; ypos = ((float)img.Height * (float).50) - (crSize.Height / 2); break; case 5: xpos = ((float)img.Width * (float).50) - (crSize.Width / 2); ypos = ((float)img.Height * (float).50) - (crSize.Height / 2); break; case 6: xpos = ((float)img.Width * (float).99) - crSize.Width; ypos = ((float)img.Height * (float).50) - (crSize.Height / 2); break; case 7: xpos = (float)img.Width * (float).01; ypos = ((float)img.Height * (float).99) - crSize.Height; break; case 8: xpos = ((float)img.Width * (float).50) - (crSize.Width / 2); ypos = ((float)img.Height * (float).99) - crSize.Height; break; case 9: xpos = ((float)img.Width * (float).99) - crSize.Width; ypos = ((float)img.Height * (float).99) - crSize.Height; break; } img.Dispose(); g.DrawString(watermarkText, drawFont, brush, xpos + 1, ypos + 1); g.InterpolationMode = InterpolationMode.HighQualityBilinear; map.Save(fileName); drawFont.Dispose(); g.Dispose(); }
调用的代码:
string path = "D:\\images"; SolidBrush brush = new SolidBrush(Color.Yellow); Font font = new Font("宋体", 42, System.Drawing.FontStyle.Bold); string datastr = $"天气:晴朗\n紫外线:强\n时间:{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}"; //判断是否存在 if (Directory.Exists(path)) { System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(path); var files = di.GetFiles(); if (files != null) { foreach (var item in files.ToList()) { AddImageSignText(item.FullName, datastr, 3, font, brush); } } }