在好例子网,分享、交流、成长!
您当前所在位置:首页C# 开发实例C#语言基础 → C# 批量给图片加水印工具源码(亲测)

C# 批量给图片加水印工具源码(亲测)

C#语言基础

下载此实例
  • 开发语言:C#
  • 实例大小:0.11M
  • 下载次数:30
  • 浏览次数:440
  • 发布时间:2019-03-08
  • 实例类别:C#语言基础
  • 发 布 人:crazycode
  • 文件格式:.zip
  • 所需积分:2
 相关标签: 水印 图片 C#

实例介绍

【实例简介】

【实例截图】

from clipboard


加水印后的效果(右下角的喜字即为水印图片)

from clipboard

【核心代码】

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.IO;
using 图片加水印工具.BLL;

namespace 图片加水印工具
{
    public partial class Form1 : Form
    {
        List<string> listExtention = new List<string>();
        public Form1()
        {
            InitializeComponent();
            Form.CheckForIllegalCrossThreadCalls = false;
            listExtention.AddRange(new string[] { ".jpg", ".gif", ".png" });
            ConfigFile.Instanse.fileName = AppDomain.CurrentDomain.BaseDirectory   "图片加水印工具.ini";
        }
       
        private void Form1_FormClosed(object sender, FormClosedEventArgs e)
        {
            Application.Exit();
            Application.ExitThread();
        }
        #region 在新线程中运行函数
        /// <summary>
        /// 在新线程中运行函数
        /// </summary>
        /// <param name="func">传入 函数名(无参、无返回值)</param>
        /// <param name="IsBackground">是否为后台线程(后台线程,窗口关闭后就终止线程)</param>
        public static void ThreadNew(VoidFunction func, bool IsBackground)
        {
            Thread th1 = new Thread(new ThreadStart(func));
            th1.IsBackground = IsBackground;//后台线程,窗口关闭后就终止线程
            th1.Start();
        }
        /// <summary>
        /// 在新线程中运行函数
        /// </summary>
        /// <param name="func">传入 函数名(有一个参数、无返回值)</param>
        /// <param name="para">object参数</param>
        /// <param name="IsBackground">是否为后台线程(后台线程,窗口关闭后就终止线程)</param>
        public static Thread ThreadNew(ParamFunction func, object para, bool IsBackground)
        {
            Thread th1 = new Thread(new ParameterizedThreadStart(func));
            //判断状态
            //((int)th1.ThreadState &((int)ThreadState.Running | (int)ThreadState.Suspended) ) == 0 
            th1.IsBackground = IsBackground;
            th1.Start(para);
            return th1;
        }
        /// <summary>
        /// 允许线程之间进行操作
        /// </summary>
        public static void OprateBetweenThread()
        {
            System.Windows.Forms.Control.CheckForIllegalCrossThreadCalls = false;
        }

        /// <summary>
        /// 无参的、返回值为void的委托,可以用来做参数名
        /// </summary>
        public delegate void VoidFunction();

        /// <summary>
        /// 有一个参数的、返回值为void的委托,可以用来做参数名
        /// </summary>
        public delegate void ParamFunction(object para);


        #endregion

        private void lb_selectDir_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog fbd = new FolderBrowserDialog();
            if (fbd.ShowDialog() == DialogResult.OK)
            {
                txtDir.Text = fbd.SelectedPath;
                ConfigFile.Instanse["txtDir"] = txtDir.Text;                
            }
        }

        private void lb_selectMark_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();

            //设置文件类型
            ofd.Filter = "png(*.png)|*.png|jpg(*.jpg)|*.jpg|gif(*.gif)|*.gif";

            //设置默认文件类型显示顺序
            ofd.FilterIndex = 1;

            //保存对话框是否记忆上次打开的目录
            ofd.RestoreDirectory = true;

            //点了保存按钮进入
            if (ofd.ShowDialog() == DialogResult.OK)
            {

                txtMark.Text = ofd.FileName.ToString();
                ConfigFile.Instanse["txtMark"]=txtMark.Text;
            }
        }
        int success = 0; //成功
        int falure = 0; //失败
        int total = 0;
        private void MakeWaterMark()
        {
            success = 0;
            falure = 0;
            total = 0;
            string errmsg = "";
            string markPicPath = txtMark.Text.Trim();
            string strtxtDir = txtDir.Text.Trim();
            if (strtxtDir == "" || markPicPath == "")
            {
                MessageBox.Show("请选择目录和水印文件!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Stop);
            }
            else if (Directory.Exists(strtxtDir) == false)
            {
                MessageBox.Show("文件夹不存在!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Stop);
            }
            else
            {
                btnExec.Enabled = false;
                List<string> PictureList = new List<string>();
                lb_statusInfo.Text = "状态:正在检索图片…";
                SearchFile(txtDir.Text.Trim(), ref PictureList);
                foreach (string s in PictureList)
                {
                    try
                    {

                        MakeWaterPic(s, "", markPicPath, "");
                        success  ;
                    }
                    catch (Exception er)
                    {
                        falure  ;
                        errmsg  = er.Message;
                    }
                    total  ;
                    lb_statusInfo.Text = "状态:正在为第"   (total   1)   "张图片加水印…";
                }
                lb_statusInfo.Text = "状态:完成!共"   total   ",成功"   success   ",失败"   falure;
                btnExec.Enabled = true;
                if (errmsg != "") MessageBox.Show(errmsg, "执行完成,部分文件出错信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }
        public void SearchFile(string parentDir, ref List<string> PictureList)
        {
            try
            {
                string[] subFiles = Directory.GetFiles(parentDir);
                string[] subDirs = Directory.GetDirectories(parentDir, "*.*", SearchOption.TopDirectoryOnly);
                PictureList.AddRange(subFiles);
                foreach (string dir in subDirs)
                {
                    SearchFile(dir, ref PictureList);
                }
            }
            catch (Exception ex) { }
        }


        private string MakeWaterPic(string SourcePicPath, string WaterText, string WaterPath, string SaveName)
        {
            if (File.Exists(SourcePicPath) == false)
            {
                return "-1";//文件不存在
            }

            string extension = Path.GetExtension(SourcePicPath).ToLower();//后缀
            if (listExtention.Contains(extension) == false) throw new Exception("不允许的后缀:"   SourcePicPath   "\n");
            string fileName = "";
            if (SaveName.Trim() != "") fileName = SaveName;
            else fileName = DateTime.Now.ToString("yyyy-MM-dd_hhmmssfff");

            //加文字水印
            System.Drawing.Image image = System.Drawing.Image.FromFile(SourcePicPath, true);
            int imgwidth = image.Width;
            int imgheight = image.Height;
            using (System.Drawing.Bitmap bitmap = new Bitmap(image.Width, image.Height))
            {

                using (System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap))//
                {
                    g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
                    g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                    g.Clear(System.Drawing.Color.Transparent);
                    g.DrawImage(image, 0, 0, imgwidth, imgheight);//画上原图片

                    image.Dispose();
                    //g.DrawImage(image, 0, 0, image.Width, image.Height);
                    if (WaterText != "")
                    {
                        Font f = new Font("Verdana", 32);
                        Brush b = new SolidBrush(Color.Yellow);
                        g.DrawString(WaterText, f, b, 10, 10);
                    }
                    //g.Dispose();

                    //加图片水印
                    System.Drawing.Image copyImage = System.Drawing.Image.FromFile(WaterPath);
                    g.DrawImage(copyImage, new Rectangle(imgwidth - copyImage.Width, imgheight - copyImage.Height, copyImage.Width, copyImage.Height), 0, 0, copyImage.Width, copyImage.Height, GraphicsUnit.Pixel);
                    if (File.Exists(SourcePicPath))
                    {
                        File.Delete(SourcePicPath);
                    }
                    //保存加水印过后的图片,删除原始图片
                    // string newPath = fileName   extension;
                    switch (extension)
                    {
                        case ".jpg":
                            bitmap.Save(SourcePicPath, System.Drawing.Imaging.ImageFormat.Jpeg);
                            break;
                        case ".gif":
                            bitmap.Save(SourcePicPath, System.Drawing.Imaging.ImageFormat.Gif);
                            break;
                        case ".png":
                            bitmap.Save(SourcePicPath, System.Drawing.Imaging.ImageFormat.Png);
                            break;
                        default:
                            throw new Exception("不允许的后缀:"   SourcePicPath);
                    }

                }
            }

            return "1";
            // Response.Redirect(newPath);
            //}
        }

        private void btnExec_Click(object sender, EventArgs e)
        {
            ThreadNew(MakeWaterMark, true);
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            txtDir.Text = ConfigFile.Instanse["txtDir"];
            txtMark.Text = ConfigFile.Instanse["txtMark"];
        }

    }
}


标签: 水印 图片 C#

实例下载地址

C# 批量给图片加水印工具源码(亲测)

不能下载?内容有错? 点击这里报错 + 投诉 + 提问

好例子网口号:伸出你的我的手 — 分享

网友评论

发表评论

(您的评论需要经过审核才能显示)

查看所有0条评论>>

小贴士

感谢您为本站写下的评论,您的评论对其它用户来说具有重要的参考价值,所以请认真填写。

  • 类似“顶”、“沙发”之类没有营养的文字,对勤劳贡献的楼主来说是令人沮丧的反馈信息。
  • 相信您也不想看到一排文字/表情墙,所以请不要反馈意义不大的重复字符,也请尽量不要纯表情的回复。
  • 提问之前请再仔细看一遍楼主的说明,或许是您遗漏了。
  • 请勿到处挖坑绊人、招贴广告。既占空间让人厌烦,又没人会搭理,于人于己都无利。

关于好例子网

本站旨在为广大IT学习爱好者提供一个非营利性互相学习交流分享平台。本站所有资源都可以被免费获取学习研究。本站资源来自网友分享,对搜索内容的合法性不具有预见性、识别性、控制性,仅供学习研究,请务必在下载后24小时内给予删除,不得用于其他任何用途,否则后果自负。基于互联网的特殊性,平台无法对用户传输的作品、信息、内容的权属或合法性、安全性、合规性、真实性、科学性、完整权、有效性等进行实质审查;无论平台是否已进行审查,用户均应自行承担因其传输的作品、信息、内容而可能或已经产生的侵权或权属纠纷等法律责任。本站所有资源不代表本站的观点或立场,基于网友分享,根据中国法律《信息网络传播权保护条例》第二十二与二十三条之规定,若资源存在侵权或相关问题请联系本站客服人员,点此联系我们。关于更多版权及免责申明参见 版权及免责申明

;
报警