有时我们需要在图像上添加水印。例如,在图像上添加版权或名称。我们可能还需要在文档中创建水印。接下来就实现 C# 如何在图像上添加水印。要添加水印的图片如下:
1、VS2019添加一个控制台程序,当然别的类型程序也可,代码是一样的
把图片复制到项目的指定目录下
2、项目引用System.Drawing.dll
3、在项目的bin目录下创建目录images,将图片6p.jpg复制到该目录下,当然这个目录你放在别的位置也行。
4、编写代码:
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleAppPicture
{
class Program
{
static void Main(string[] args)
{
//获取当前应用程序执行路径
string apppath = System.Environment.CurrentDirectory+ "\\images\\";
//设置目标图片路径
string src_path = apppath + "6p.jpg";
//设置保存位置
string dst_path = apppath + "6p-2.jpg";
//读取目标图片
System.Drawing.Image src_img = (System.Drawing.Image)Bitmap.FromFile(src_path);
//设置水印字体、字号
Font font = new Font("Arial", 115, FontStyle.Italic, GraphicsUnit.Pixel);
//设置水印颜色
Color color = Color.FromArgb(255, 255, 0, 0);
//运算水印位置
Point atpoint = new Point(src_img.Width / 2, src_img.Height / 3);
//初始化画刷
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.ywjwest.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);
}
}
}
}
}
5、运行效果、
效果相当的帅,要加鸡腿了。