有时我们需要在图像上添加水印。例如,在图像上添加版权或名称。我们可能还需要在文档中创建水印。接下来就来讲一下 C# 如何在图像上添加水印。首先,将需要添加水印的图片放在程序运行目录,水印示例图片具体如下
测试添加水印图片.png

其次,在项目中添加“System.Drawing.dll”引用
添加图片引用.png

然后,引用using System.Drawing,为图片添加水印代码如下

using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace YlqfTest
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            //设置目标图片路径
            string src_path = "cstp.jpg";
            //设置保存位置
            string dst_path = "cisharp.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, 255, 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("www.sotoolbox.com", font, brush, atpoint, sf);

                using (MemoryStream m = new MemoryStream())
                {
                    //以jpg格式写入到内存流,完成绘制
                    src_img.Save(m, System.Drawing.Imaging.ImageFormat.Jpeg);
                    //保存到磁盘
                    src_img.Save(dst_path);
                }
            }
        }
    }
}

最后,附上效果图
测试添加水印图片.png

最后修改:2022 年 09 月 30 日
如果觉得我的文章对你有用,请随意赞赏