C#winform批量给图片加水印代码

本文涉及的产品
密钥管理服务KMS,1000个密钥,100个凭据,1个月
简介: //文件下载,里面有exe可直接运行 http://download.csdn.net/detail/pukuimin1226/6001759 //form后台 //加密类注意要引用 System.

//文件下载,里面有exe可直接运行

http://download.csdn.net/detail/pukuimin1226/6001759

//form后台

//加密类注意要引用 System.Web

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"];
        }

    }
}

//加/解密类

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Security.Cryptography;
using System.Web.Security;

namespace 图片加水印工具.BLL
{
    /// <summary>
    /// 可逆加密解密类
    /// </summary>
    public static class DesEncrypt
    {
        /// <summary>
        /// 解密函数
        /// </summary>
        /// <param name="Text">要解密的字符串(必须是经过加密后的字符串才能解密成功)</param>
        /// <param name="sKey">key</param>
        /// <returns></returns>
        public static string Decrypt(string Text, string sKey)
        {
            DESCryptoServiceProvider provider = new DESCryptoServiceProvider();
            int num = Text.Length / 2;
            byte[] buffer = new byte[num];
            for (int i = 0; i < num; i++)
            {
                int num3 = Convert.ToInt32(Text.Substring(i * 2, 2), 0x10);
                buffer[i] = (byte)num3;
            }
            provider.Key = Encoding.ASCII.GetBytes(FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(0, 8));
            provider.IV = Encoding.ASCII.GetBytes(FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(0, 8));
            MemoryStream stream = new MemoryStream();
            CryptoStream stream2 = new CryptoStream(stream, provider.CreateDecryptor(), CryptoStreamMode.Write);
            stream2.Write(buffer, 0, buffer.Length);
            stream2.FlushFinalBlock();
            return Encoding.Default.GetString(stream.ToArray());
        }
        /// <summary>
        /// 加密函数
        /// </summary>
        /// <param name="Text">要加密的字符串</param>
        /// <param name="sKey">key</param>
        /// <returns></returns>
        public static string Encrypt(string Text, string sKey)
        {
            DESCryptoServiceProvider provider = new DESCryptoServiceProvider();
            byte[] bytes = Encoding.Default.GetBytes(Text);
            provider.Key = Encoding.ASCII.GetBytes(FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(0, 8));
            provider.IV = Encoding.ASCII.GetBytes(FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(0, 8));
            MemoryStream stream = new MemoryStream();
            CryptoStream stream2 = new CryptoStream(stream, provider.CreateEncryptor(), CryptoStreamMode.Write);
            stream2.Write(bytes, 0, bytes.Length);
            stream2.FlushFinalBlock();
            StringBuilder builder = new StringBuilder();
            foreach (byte num in stream.ToArray())
            {
                builder.AppendFormat("{0:X2}", num);
            }
            return builder.ToString();
        }
        /// <summary>
        /// 字符串解密
        /// </summary>
        /// <param name="Text">要解密的字符串(必须是加密后的!不然格式不对!)</param>
        /// <returns></returns>
        public static string Decrypt(string Text)
        {
            return Decrypt(Text, "4B2A9A696326C4C3770DED74D5AFCECA");
        }
        /// <summary>
        /// 字符串加密
        /// </summary>
        /// <param name="Text">要加密的字符串</param>
        /// <returns></returns>
        public static string Encrypt(string Text)
        {
            return Encrypt(Text, "4B2A9A696326C4C3770DED74D5AFCECA");
        }
    }
}
//文件保存信息类

using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using System.IO;

namespace 图片加水印工具.BLL
{
    #region 配置文件类 ConfigFile
    /// <summary>
    /// 配置文件类 ConfigFile,内容存储到文件中,继承自配置接口 (一定要给ConfigFile.Instanse.fileName 赋值)
    /// </summary>
    public class ConfigFile : IConfig
    {
        #region 文件物理路径 fileName
        private string _fileName = "";
        /// <summary>
        /// 文件物理路径
        /// </summary>
        public string fileName
        {
            get { return _fileName; }
            set { _fileName = value; }
        }
        #endregion

        private ConfigFile() { }

        #region 单例模式,返回一个静态实例 Instanse
        private static ConfigFile _Instance;
        /// <summary>
        /// 实例
        /// </summary>
        public static ConfigFile Instanse
        {
            get { if (_Instance == null) { _Instance = new ConfigFile(); } return _Instance; }
        }
        #endregion

        #region CreateFile()文件不存在则创建文件
        /// <summary>
        /// CreateFile()文件不存在则创建文件
        /// </summary>
        /// <returns>返回文件是否是新建的</returns>
        public bool CreateFile()
        {
            bool isCreate = false;
            if (!File.Exists(fileName))
            {
                using (File.Create(fileName))//创建完成后立即释放资源,否则会占用、报错
                {
                }
                isCreate = true;
            }
            return isCreate;
        }
        #endregion

        #region 支持Get,set方法取值、加入值、修改值 this[Key]
        /// <summary>
        /// 索引函数
        /// </summary>
        /// <param name="Key">键(key)</param>
        /// <returns></returns>
        public string this[string Key]
        {
            get
            {
                if (CreateFile())//如果是刚新建的空文件,返回空
                {
                    return "";
                }
                else
                {
                    string[] lines = File.ReadAllLines(fileName, Encoding.UTF8);
                    foreach (string line in lines)
                    {
                        var match = Regex.Match(line, @"(\w+)=([\w\W]+)");
                        string linekey = match.Groups[1].Value;
                        string lineValue = match.Groups[2].Value;
                        if (linekey == Key)
                        {
                            return lineValue; //如果匹配,返回找到的值
                        }
                    }
                    return "";//如果上面没找到,返回空
                }
            }
            set
            {
                if (CreateFile())
                {
                    File.AppendAllText(fileName, Key + "=" + value + "\r\n");//如果是新建的文件 ,直接加入
                }
                else
                {
                    string[] lines = File.ReadAllLines(fileName, Encoding.UTF8);
                    for (int i = 0; i < lines.Length; i++)
                    {
                        string line = lines[i];
                        var match = Regex.Match(line, @"(\w+)=(\w+)");
                        string linekey = match.Groups[1].Value;
                        string lineValue = match.Groups[2].Value;
                        //逐行找,如果遇到名字等于name的就把这一行的值修改
                        //然后写回文件
                        if (linekey == Key)
                        {
                            lines[i] = linekey + "=" + value;
                            File.WriteAllLines(fileName, lines);
                            return;//如果找到值并修改了,不继续向下执行
                        }
                    }
                    File.AppendAllText(fileName, Key + "=" + value + "\r\n");//如果上面没找到,加入键值到文件结尾
                }

            }
        }
        #endregion

        #region 得到所有键名称的集合 List<string>
        /// <summary>
        /// 得到所有键名称的集合 List《string》
        /// </summary>
        public string[] Keys
        {
            get
            {
                List<string> listKey = new List<string>();
                if (CreateFile())
                {
                    return listKey.ToArray();
                }
                else
                {

                    string[] lines = File.ReadAllLines(fileName, Encoding.UTF8);
                    foreach (string line in lines)
                    {
                        var match = Regex.Match(line, @"(\w+)=(\w+)");
                        string linekey = match.Groups[1].Value;
                        listKey.Add(linekey);
                    }
                    return listKey.ToArray();
                }
            }
        }
        #endregion

        #region 是否存在键 KeyExists(Key)
        /// <summary>
        /// 是否存在键 KeyExists(Key)
        /// </summary>
        /// <param name="Key">键名称</param>
        /// <returns></returns>
        public bool KeyExists(string Key)
        {
            return (Keys as ICollection<string>).Contains(Key);
        }
        #endregion

    }
    #endregion

    #region 加密的配置文件类 ConfigFileDES
    /// <summary>
    /// 加密的配置文件类 ConfigFileDES,内容存储到文件中,使用时必须调用 ConfigFileDES.Instanse.SetIConfig(IConfig) 赋值
    /// </summary>
    public class ConfigFileDES : IConfig
    {
        private IConfig _iconfig = null;
        /// <summary>
        /// 接口变量
        /// </summary>
        public IConfig iconfig
        {
            get { return _iconfig; }
            set { _iconfig = value; }
        }
        private ConfigFileDES() { }

        private static ConfigFileDES _Instance;
        /// <summary>
        /// 实例
        /// </summary>
        public static ConfigFileDES Instanse
        {
            get { if (_Instance == null) { _Instance = new ConfigFileDES(); } return _Instance; }
        }
        /// <summary>
        /// 传入一个可操作的继承自IConfig的类的对象
        /// </summary>
        /// <param name="iconfig">继承自IConfig的类的对象</param>
        public void SetIConfig(IConfig iconfig)//本加密类是在其它实现IConfig的类基础上进行,必须要传入一个类的实例
        {
            this.iconfig = iconfig;
        }
        /// <summary>
        /// 索引函数
        /// </summary>
        /// <param name="key">名称(key)</param>
        /// <returns></returns>
        public string this[string key]
        {
            get
            {
                if (iconfig[key] == "") return "";
                return DesEncrypt.Decrypt(iconfig[key]);//解密后 取出
            }
            set
            {
                iconfig[key] = DesEncrypt.Encrypt(value);//加密后 存入
            }
        }
        /// <summary>
        /// 所有键的集合
        /// </summary>
        public string[] Keys
        {
            get { return iconfig.Keys; }
        }
        /// <summary>
        /// 是否存在
        /// </summary>
        /// <param name="key">键(key)</param>
        /// <returns></returns>
        public bool KeyExists(string key)
        {
            return iconfig.KeyExists(key);
        }

    }
    #endregion

    #region 配置接口  IConfig
    /// <summary>
    /// 配置接口  IConfig
    /// </summary>
    public interface IConfig
    {
        /// <summary>
        /// 通过键得到对应的值
        /// </summary>
        /// <param name="Key">键(key)</param>
        /// <returns></returns>
        string this[string Key] { get; set; }
        /// <summary>
        /// 返回存在的键的集合
        /// </summary>
        string[] Keys { get; }
        /// <summary>
        /// 是否存在键
        /// </summary>
        /// <param name="Key">键名</param>
        /// <returns></returns>
        bool KeyExists(string Key);
    }
    #endregion
}

//窗体


相关文章
|
1月前
|
缓存 C# Windows
C#程序如何编译成Native代码
【10月更文挑战第15天】在C#中,可以通过.NET Native和第三方工具(如Ngen.exe)将程序编译成Native代码,以提升性能和启动速度。.NET Native适用于UWP应用,而Ngen.exe则通过预编译托管程序集为本地机器代码来加速启动。不过,这些方法也可能增加编译时间和部署复杂度。
|
2月前
|
数据采集 JavaScript C#
C#图像爬虫实战:从Walmart网站下载图片
C#图像爬虫实战:从Walmart网站下载图片
|
2月前
|
SQL API 定位技术
基于C#使用winform技术的游戏平台的实现【C#课程设计】
本文介绍了基于C#使用WinForms技术开发的游戏平台项目,包括项目结构、运行截图、实现功能、部分代码说明、数据库设计和完整代码资源。项目涵盖了登录注册、个人信息修改、游戏商城列表查看、游戏管理、用户信息管理、数据分析等功能。代码示例包括ListView和ImageList的使用、图片上传、图表插件使用和SQL工具类封装,以及高德地图天气API的调用。
基于C#使用winform技术的游戏平台的实现【C#课程设计】
|
1月前
|
C#
C# 图形验证码实现登录校验代码
C# 图形验证码实现登录校验代码
76 2
|
30天前
|
设计模式 程序员 C#
C# 使用 WinForm MDI 模式管理多个子窗体程序的详细步骤
WinForm MDI 模式就像是有超能力一般,让多个子窗体井然有序地排列在一个主窗体之下,既美观又实用。不过,也要小心管理好子窗体们的生命周期哦,否则一不小心就会出现一些意想不到的小bug
|
1月前
|
中间件 数据库连接 API
C#数据分表核心代码
C#数据分表核心代码
36 0
|
1月前
|
API C# Windows
【C#】在winform中如何实现嵌入第三方软件窗体
【C#】在winform中如何实现嵌入第三方软件窗体
75 0
|
1月前
|
API C#
C#实现Winform程序右下角弹窗消息提示
C#实现Winform程序右下角弹窗消息提示
84 0
|
3月前
|
物联网 C# Windows
看看如何使用 C# 代码让 MQTT 进行完美通信
看看如何使用 C# 代码让 MQTT 进行完美通信
578 0
|
3月前
|
数据安全/隐私保护 C# UED
利用 Xamarin 开展企业级移动应用开发:从用户登录到客户管理,全面演示C#与Xamarin.Forms构建跨平台CRM应用的实战技巧与代码示例
【8月更文挑战第31天】利用 Xamarin 进行企业级移动应用开发能显著提升效率并确保高质量和高性能。Xamarin 的跨平台特性使得开发者可以通过单一的 C# 代码库构建 iOS、Android 和 Windows 应用,帮助企业快速推出产品并保持一致的用户体验。本文通过一个简单的 CRM 示例应用演示 Xamarin 的使用方法,并提供了具体的代码示例。该应用包括用户登录、客户列表显示和添加新客户等功能。此外,还介绍了如何增强应用的安全性、数据持久化、性能优化及可扩展性,从而构建出功能全面且体验良好的移动应用。
52 0