C#添加图片水印就这么简单C#添加图片水印就这么简单
|
admin
2023年8月16日 9:21
本文热度 1866
|
有时我们需要在图像上添加水印。例如,在图像上添加版权或名称。我们可能还需要在文档中创建水印。接下来就来讲一下 C# 如何在图像上添加水印。首先,将需要添加水印的图片放在程序运行目录,水印示例图片具体如下:

其次,在项目中添加Nuget包“System.Drawing.Common”引用。

或者代码安装
Install-Package System.Drawing.Common
为图片添加水印代码如下,说明在代码中:
static void Main(string[] args) { #region 图片加水印 //设置目标图片路径 string src_path = "D:\\test001.jpg"; //设置保存位置 string dst_path = "D:\\cptest001.jpg"; //读取目标图片 System.Drawing.Image src_img = (System.Drawing.Image)Bitmap.fromFile(src_path); //设置水印字体、字号 Font font = new Font("Arial", 35, FontStyle.Italic, GraphicsUnit.Pixel); //设置水印颜色 Color color = Color.fromArgb(255, 233, 0, 0); //运算水印位置 Point atpoint = new Point(src_img.Width / 2, src_img.Height / 2); //初始化画刷 SolidBrush brush = new SolidBrush(color); //初始化gdi绘图 using (Graphics graphics = Graphics.fromImage(src_img)) { StringFormat sf = new StringFormat(); sf.Alignment = StringAlignment.Center; sf.LineAlignment = StringAlignment.Center; graphics.DrawString("DOTNET开发跳槽", font, brush, atpoint, sf);
using (MemoryStream m = new MemoryStream()) { //以jpg格式写入到内存流,完成绘制 src_img.Save(m, System.Drawing.Imaging.ImageFormat.Jpeg); //保存到磁盘 src_img.Save(dst_path); } } #endregion }
最后,附上效果图

该文章在 2023/8/16 9:21:43 编辑过