Winform水印工具(文字和图片皆可)

这是一个介绍如何在Winform应用中创建水印工具的文章,支持文字和图片作为水印内容。用户可以选择水印的位置,如左上、右上、居中、左下和右下。尽管当前版本生成缩略图时会先保存为物理文件,未来可优化为直接使用图片对象。此外,计划增加文字大小和字体样式的调整,以及支持批量处理文件夹中的图片。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Winform水印工具(文字和图片皆可)

简介:如题Winform水印工具,原图和水印图都将以缩略图的形式展示在工具上

              水印类型/水印内容:文字、图片

              水印位置:左上角、右上角、居中、左下角、右下角

              待优化:工具上的原图和水印图的缩略图都生成了物理文件再加载的,可改为图片对象

                              文字大小和字体样式可增加等

                              目前是单一图片的水印,可增加部分代码改成文件夹的批量水印

              如下图:

代码展示:

WaterMarkBll.cs

/*----------------------------------------
 * Corporation:**
 * Author:彭振
 * Time:2015-10-23 16:08:54
 * Remark:图片处理相关业务处理(水印、缩略图)
----------------------------------------*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing.Imaging;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.IO;
using System.Collections;

namespace Watermark
{
    /// <summary>
    /// 水印的类型
    /// </summary>
    public enum WaterMarkType
    {
        /// <summary>
        /// 文字水印
        /// </summary>
        TextMark,
        /// <summary>
        /// 图片水印
        /// </summary>
        ImageMark // 暂时只能添加文字水印
    };

    /// <summary>
    /// 水印的位置
    /// </summary>
    public enum WaterMarkPosition
    {
        /// <summary>
        /// 左上角
        /// </summary>
        WMP_Left_Top,
        /// <summary>
        /// 左下角
        /// </summary>
        WMP_Left_Bottom,
        /// <summary>
        /// 居中
        /// </summary>
        WMP_Center,
        /// <summary>
        /// 右上角
        /// </summary>
        WMP_Right_Top,
        /// <summary>
        /// 右下角
        /// </summary>
        WMP_Right_Bottom
    };

    /// <summary>
    /// 图片处理相关业务处理(水印、缩略图)
    /// </summary>
    public class WaterMarkBll
    {
        public WaterMarkBll() { }

        #region 给图片加水印
        /// <summary>
        /// 添加水印(分图片水印与文字水印两种)
        /// </summary>
        /// <param name="oldpath">原图片绝对地址</param>
        /// <param name="newpath">新图片放置的绝对地址</param>
        /// <param name="wmpPosition">要添加的水印的位置</param>
        /// <param name="wmtType">要添加的水印的类型</param>
        /// <param name="sWaterMarkContent">水印内容,若添加文字水印,此即为要添加的文字;
        /// 若要添加图片水印,此为图片的路径</param>
        public void addWaterMark(string oldpath, string newpath, WaterMarkPosition wmpPosition,
         WaterMarkType wmtType, string sWaterMarkContent)
        {
            try
            {
                Image image = Image.FromFile(oldpath);

                Bitmap b = new Bitmap(image.Width, image.Height,
                 PixelFormat.Format24bppRgb);

                Graphics g = Graphics.FromImage(b);
                g.Clear(Color.White);
                g.SmoothingMode = SmoothingMode.HighQuality;
                g.InterpolationMode = InterpolationMode.High;

                g.DrawImage(image, 0, 0, image.Width, image.Height);

                switch (wmtType)
                {
                    case WaterMarkType.TextMark:
                        //文字水印
                        this.addWatermarkText(g, sWaterMarkContent, wmpPosition.ToString(),
                         image.Width, image.Height);
                        break;
                    case WaterMarkType.ImageMark:
                        //图片水印
                        Image imageWatermark = Image.FromFile(sWaterMarkContent);
                        this.addWatermarkImage(g, imageWatermark, wmpPosition.ToString(), image.Width, image.Height);
                        break;
                }

                b.Save(newpath);
                b.Dispose();
                image.Dispose();
            }
            catch
            {
                if (File.Exists(oldpath))
                {
                    //File.Delete(oldpath);
                }
            }
            finally
            {
                if (File.Exists(oldpath))
                {
                    //File.Delete(oldpath);
                }
            }
        }

        /// <summary>
        ///   加水印文字
        /// </summary>
        /// <param name="picture">imge 对象</param>
        /// <param name="_watermarkText">水印文字内容</param>
        /// <param name="_watermarkPosition">水印位置</param>
        /// <param name="_width">被加水印图片的宽</param>
        /// <param name="_height">被加水印图片的高</param>
        private void addWatermarkText(Graphics picture, string _watermarkText,
         string _watermarkPosition, int _width, int _height)
        {
            // 确定水印文字的字体大小
            int[] sizes = new int[] { 32, 30, 28, 26, 24, 22, 20, 18, 16, 14, 12, 10, 8, 6, 4 };
            Font crFont = null;
            SizeF crSize = new SizeF();
            for (int i = 0; i < sizes.Length; i++)
            {
                crFont = new Font("Arial Black", sizes[i], FontStyle.Bold);
                crSize = picture.MeasureString(_watermarkText, crFont);

                if ((ushort)crSize.Width < (ushort)_width)
                {
                    break;
                }
            }

            // 生成水印图片(将文字写到图片中)
            Bitmap floatBmp = new Bitmap((int)crSize.Width + 3,
                  (int)crSize.Height + 3, PixelFormat.Format32bppArgb);
            Graphics fg = Graphics.FromImage(floatBmp);
            PointF pt = new PointF(0, 0);

            // 画阴影文字
            Brush TransparentBrush0 = new SolidBrush(Color.FromArgb(255, Color.Black));
            Brush TransparentBrush1 = new SolidBrush(Color.FromArgb(255, Color.Black));
            fg.DrawString(_watermarkText, crFont, TransparentBrush0, pt.X, pt.Y + 1);
            fg.DrawString(_watermarkText, crFont, TransparentBrush0, pt.X + 1, pt.Y);

            fg.DrawString(_watermarkText, crFont, TransparentBrush1, pt.X + 1, pt.Y + 1);
            fg.DrawString(_watermarkText, crFont, TransparentBrush1, pt.X, pt.Y + 2);
            fg.DrawString(_watermarkText, crFont, TransparentBrush1, pt.X + 2, pt.Y);

            TransparentBrush0.Dispose();
            TransparentBrush1.Dispose();

            // 画文字
            fg.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
            fg.DrawString(_watermarkText,
             crFont, new SolidBrush(Color.White),
             pt.X, pt.Y, StringFormat.GenericDefault);

            // 保存刚才的操作
            fg.Save();
            fg.Dispose();
            // floatBmp.Save("d:\\WebSite\\DIGITALKM\\ttt.jpg");

            // 将水印图片加到原图中
            this.addWatermarkImage(
             picture,
             new Bitmap(floatBmp),
             _watermarkPosition,
             _width,
             _height);
        }

        /// <summary>
        ///   加水印图片
        /// </summary>
        /// <param name="picture">imge 对象</param>
        /// <param name="iTheImage">Image对象(以此图片为水印)</param>
        /// <param name="_watermarkPosition">水印位置</param>
        /// <param name="_width">被加水印图片的宽</param>
        /// <param name="_height">被加水印图片的高</param>
        private void addWatermarkImage(Graphics picture, Image iTheImage,
         string _watermarkPosition, int _width, int _height)
        {
            Image watermark = new Bitmap(iTheImage);

            ImageAttributes imageAttributes = new ImageAttributes();
            ColorMap colorMap = new ColorMap();

            colorMap.OldColor = Color.FromArgb(255, 0, 255, 0);
            colorMap.NewColor = Color.FromArgb(0, 0, 0, 0);
            ColorMap[] remapTable = { colorMap };

            imageAttributes.SetRemapTable(remapTable, ColorAdjustType.Bitmap);

            float[][] colorMatrixElements = {
             new float[] {1.0f, 0.0f, 0.0f, 0.0f, 0.0f},
             new float[] {0.0f, 1.0f, 0.0f, 0.0f, 0.0f},
             new float[] {0.0f, 0.0f, 1.0f, 0.0f, 0.0f},
             new float[] {0.0f, 0.0f, 0.0f, 0.3f, 0.0f},
             new float[] {0.0f, 0.0f, 0.0f, 0.0f, 1.0f}
            };

            ColorMatrix colorMatrix = new ColorMatrix(colorMatrixElements);

            imageAttributes.SetColorMatrix(colorMatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);

            int xpos = 0;
            int ypos = 0;
            int WatermarkWidth = 0;
            int WatermarkHeight = 0;
            double bl = 1d;

            //计算水印图片的比率
            //取背景的1/4宽度来比较
            if ((_width > watermark.Width * 4) && (_height > watermark.Height * 4))
            {
                bl = 1;
            }
            else if ((_width > watermark.Width * 4) && (_height < watermark.Height * 4))
            {
                bl = Convert.ToDouble(_height / 4) / Convert.ToDouble(watermark.Height);

            }
            else if ((_width < watermark.Width * 4) && (_height > watermark.Height * 4))
            {
                bl = Convert.ToDouble(_width / 4) / Convert.ToDouble(watermark.Width);
            }
            else
            {
                if ((_width * watermark.Height) > (_height * watermark.Width))
                {
                    bl = Convert.ToDouble(_height / 4) / Convert.ToDouble(watermark.Height);

                }
                else
                {
                    bl = Convert.ToDouble(_width / 4) / Convert.ToDouble(watermark.Width);

                }

            }

            WatermarkWidth = Convert.ToInt32(watermark.Width * bl);
            WatermarkHeight = Convert.ToInt32(watermark.Height * bl);

            switch (_watermarkPosition)
            {
                case "WMP_Left_Top":
                    xpos = 10;
                    ypos = 10;
                    break;
                case "WMP_Right_Top":
                    xpos = _width - WatermarkWidth - 10;
                    ypos = 10;
                    break;
                case "WMP_Center":
                    xpos = (_width / 2) - (WatermarkWidth / 2);
                    ypos = (_height / 2) - (WatermarkHeight / 2);
                    break;
                case "WMP_Right_Bottom":
                    xpos = _width - WatermarkWidth - 10;
                    ypos = _height - WatermarkHeight - 10;
                    break;
                case "WMP_Left_Bottom":
                    xpos = 10;
                    ypos = _height - WatermarkHeight - 10;
                    break;
            }

            picture.DrawImage(
             watermark,
             new Rectangle(xpos, ypos, WatermarkWidth, WatermarkHeight),
             0,
             0,
             watermark.Width,
             watermark.Height,
             GraphicsUnit.Pixel,
             imageAttributes);

            watermark.Dispose();
            imageAttributes.Dispose();
        }

        /// <summary>
        ///   加水印图片
        /// </summary>
        /// <param name="picture">imge 对象</param>
        /// <param name="WaterMarkPicPath">水印图片的地址</param>
        /// <param name="_watermarkPosition">水印位置</param>
        /// <param name="_width">被加水印图片的宽</param>
        /// <param name="_height">被加水印图片的高</param>
        private void addWatermarkImage(Graphics picture, string WaterMarkPicPath,
         string _watermarkPosition, int _width, int _height)
        {
            Image watermark = new Bitmap(WaterMarkPicPath);

            this.addWatermarkImage(picture, watermark, _watermarkPosition, _width,
             _height);
        }
        #endregion

        #region 生成缩略图
        /// <summary>
        /// 保存图片
        /// </summary>
        /// <param name="image">Image 对象</param>
        /// <param name="savePath">保存路径</param>
        /// <param name="ici">指定格式的编解码参数</param>
        private void SaveImage(Image image, string savePath, ImageCodecInfo ici)
        {
            //设置 原图片 对象的 EncoderParameters 对象
            EncoderParameters parameters = new EncoderParameters(1);
            parameters.Param[0] = new EncoderParameter(
             System.Drawing.Imaging.Encoder.Quality, ((long)90));
            image.Save(savePath, ici, parameters);
            parameters.Dispose();
        }

        /// <summary>
        /// 获取图像编码解码器的所有相关信息
        /// </summary>
        /// <param name="mimeType">包含编码解码器的多用途网际邮件扩充协议 (MIME) 类型的字符串</param>
        /// <returns>返回图像编码解码器的所有相关信息</returns>
        private ImageCodecInfo GetCodecInfo(string mimeType)
        {
            ImageCodecInfo[] CodecInfo = ImageCodecInfo.GetImageEncoders();
            foreach (ImageCodecInfo ici in CodecInfo)
            {
                if (ici.MimeType == mimeType)
                    return ici;
            }
            return null;
        }

        /// <summary>
        /// 生成缩略图
        /// </summary>
        /// <param name="sourceImagePath">原图片路径(相对路径)</param>
        /// <param name="thumbnailImagePath">生成的缩略图路径,如果为空则保存为原图片路径(相对路径)</param>
        /// <param name="thumbnailImageWidth">缩略图的宽度(高度与按源图片比例自动生成)</param>
        public void ToThumbnailImages(
         string SourceImagePath,
         string ThumbnailImagePath,
         int ThumbnailImageWidth)
        {
            Hashtable htmimes = new Hashtable();
            htmimes[".jpeg"] = "image/jpeg";
            htmimes[".jpg"] = "image/jpeg";
            htmimes[".png"] = "image/png";
            htmimes[".tif"] = "image/tiff";
            htmimes[".tiff"] = "image/tiff";
            htmimes[".bmp"] = "image/bmp";
            htmimes[".gif"] = "image/gif";

            // 取得原图片的后缀
            string sExt = SourceImagePath.Substring(
             SourceImagePath.LastIndexOf(".")).ToLower();

            //从 原图片创建 Image 对象
            Image image = Image.FromFile(SourceImagePath);
            int num = ((ThumbnailImageWidth / 4) * 3);
            int width = image.Width;
            int height = image.Height;

            //计算图片的比例
            if ((((double)width) / ((double)height)) >= 1.3333333333333333f)
            {
                num = ((height * ThumbnailImageWidth) / width);
            }
            else
            {
                ThumbnailImageWidth = ((width * num) / height);
            }
            if ((ThumbnailImageWidth < 1) || (num < 1))
            {
                return;
            }

            //用指定的大小和格式初始化 Bitmap 类的新实例
            Bitmap bitmap = new Bitmap(ThumbnailImageWidth, num,
             PixelFormat.Format32bppArgb);

            //从指定的 Image 对象创建新 Graphics 对象
            Graphics graphics = Graphics.FromImage(bitmap);

            //清除整个绘图面并以透明背景色填充
            graphics.Clear(Color.Transparent);

            graphics.SmoothingMode = SmoothingMode.HighQuality;
            graphics.InterpolationMode = InterpolationMode.High;

            //在指定位置并且按指定大小绘制 原图片 对象
            graphics.DrawImage(image, new Rectangle(0, 0, ThumbnailImageWidth, num));
            image.Dispose();

            try
            {
                //将此 原图片 以指定格式并用指定的编解码参数保存到指定文件
                SaveImage(bitmap, ThumbnailImagePath,
                 GetCodecInfo((string)htmimes[sExt]));
            }
            catch (System.Exception e)
            {
                throw e;
            }
        }
        #endregion


    }
}

WaterMarkTool.cs

/*----------------------------------------
 * Corporation:**
 * Author:彭振
 * Time:2015-10-23 16:09:13
 * Remark:生成水印工具
----------------------------------------*/
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Collections;
using System.Drawing.Imaging;
using System.IO;

namespace Watermark
{
    public partial class WaterMarkTool : Form
    {
        public WaterMarkTool()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 选择要生成水印的图片  
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void chooseFile_Click(object sender, EventArgs e)
        {
            if (this.openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                this.tbFilePath.Text = this.openFileDialog1.FileName;
            }

            if (tbFilePath.Text.Trim() == "")
            {
                MessageBox.Show("源图片不存在!");
                return;
            }
            else
            {
                string SourceImagePath = tbFilePath.Text.Trim();

                string strPath = Path.GetFullPath(SourceImagePath).Replace(Path.GetFileName(SourceImagePath), "");

                string sExt = SourceImagePath.Substring(
          SourceImagePath.LastIndexOf(".")).ToLower();

                string ThumbnailImage = strPath + DateTime.Now.Ticks.ToString() + sExt;

                WaterMarkBll objWMB = new WaterMarkBll();
                objWMB.ToThumbnailImages(SourceImagePath, ThumbnailImage, pbSourceImg.Width);

                pbSourceImg.Image = Image.FromFile(ThumbnailImage);
            }
        }

        /// <summary>
        /// 生成水印
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btCreateWater_Click(object sender, EventArgs e)
        {
            if (tbFilePath.Text.Trim() == "")
            {
                MessageBox.Show("源图片不存在!");
                return;
            }
            if (tbWaterContent.Text.Trim() == "")
            {
                MessageBox.Show("水印内容不存在!");
                return;
            }
            if (!rbTypeFont.Checked && !rbTypeImg.Checked)
            {
                MessageBox.Show("水印类型未选择!");
                return;
            }
            if (cbWaterPosition.Text.Trim() == "")
            {
                MessageBox.Show("水印位置未选择!");
                return;
            }

            string SourceImagePath = tbFilePath.Text.Trim();

            string strPath = Path.GetFullPath(SourceImagePath).Replace(Path.GetFileName(SourceImagePath), "");

            string sExt = SourceImagePath.Substring(
      SourceImagePath.LastIndexOf(".")).ToLower();


            string SaveImagePath = strPath + DateTime.Now.Ticks.ToString() + sExt;
            WaterMarkBll objWMB = new WaterMarkBll();

            WaterMarkPosition wmpPosition = new WaterMarkPosition();
            switch (cbWaterPosition.Text)
            {
                case "左上角":
                    wmpPosition = WaterMarkPosition.WMP_Left_Top;
                    break;
                case "右上角":
                    wmpPosition = WaterMarkPosition.WMP_Right_Top;
                    break;
                case "居中":
                    wmpPosition = WaterMarkPosition.WMP_Center;
                    break;
                case "左下角":
                    wmpPosition = WaterMarkPosition.WMP_Left_Bottom;
                    break;
                case "右下角":
                    wmpPosition = WaterMarkPosition.WMP_Right_Bottom;
                    break;
            } 

            if (rbTypeFont.Checked)
            {
                objWMB.addWaterMark(SourceImagePath, SaveImagePath, wmpPosition, WaterMarkType.TextMark, tbWaterContent.Text);
            }
            else
            {
                objWMB.addWaterMark(SourceImagePath, SaveImagePath, wmpPosition, WaterMarkType.ImageMark, tbWaterContent.Text);
            }

            string ThumbnailImage = strPath + DateTime.Now.Ticks.ToString() + sExt;
            objWMB.ToThumbnailImages(SaveImagePath, ThumbnailImage, pbWarterImg.Width);

            pbWarterImg.Image = Image.FromFile(ThumbnailImage);
        }

        /// <summary>
        /// 选择水印图片
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void chooseFolderPath_Click(object sender, EventArgs e)
        {
            if (this.openFileDialog2.ShowDialog() == DialogResult.OK)
            {
                this.tbWaterContent.Text = this.openFileDialog2.FileName;
            }
        }
    }
}

项目代码及工具下载地址
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值