C# 如何添加图片水印?
原文链接:https://www.cisharp.com/archives/254.html
有时我们需要在图像上添加水印。例如,在图像上添加版权或名称。我们可能还需要在文档中创建水印。接下来就来讲一下 C# 如何在图像上添加水印。首先,将需要添加水印的图片放在程序运行目录,水印示例图片具体如下
其次,在项目中添加“System.Drawing.dll”引用
然后,引用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);
<span class="hljs-keyword">using</span> (MemoryStream m = <span class="hljs-keyword">new</span> MemoryStream())
{
<span class="hljs-comment">//以jpg格式写入到内存流,完成绘制</span>
src_img.Save(m, System.Drawing.Imaging.ImageFormat.Jpeg);
<span class="hljs-comment">//保存到磁盘</span>
src_img.Save(dst_path);
}
}
}
}
}