c# 如何添加图片水印?

有时我们需要在图像上添加水印。例如,在图像上添加版权或名称。我们可能还需要在文档中创建水印。
在这篇博客和代码示例中,我解释了如何使用 C# 在图像上编写文本。此代码可用于 Windows 或 Web 应用程序。
首先,将需要添加水印的图片放在程序运行目录,水印示例图片具体如下
图片添加水印
其次,在项目中添加“System.Drawing.dll”引用
c#引用gdi
然后,引用“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.cisharp.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);
                }
            }
        }
    }
}

最后,附上效果图
c#图片添加水印效果

转载自C#如何添加图片水印?

posted @ 2022-09-23 15:31  零壹贰叁肆  阅读(1539)  评论(0编辑  收藏  举报