C# realizes adding watermark to pictures

Sometimes we need to add watermark on image . For example, adding a copyright or name to an image. We may also need to create a watermark in the document. Next, implement  how C#  adds watermarks to images. The pictures to be watermarked are as follows:

 1. VS2019 adds a console program, of course other types of programs are also available, the code is the same

 

 

 Copy the picture to the specified directory of the project

 2. The project references System.Drawing.dll

 3. Create a directory images under the bin directory of the project, and copy the picture 6p.jpg to this directory. Of course, you can put this directory in another location.

 4. Write code:

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. Operating effect,

 

 The effect is quite handsome, and chicken legs are added.

Guess you like

Origin blog.csdn.net/hqwest/article/details/130789582