天天看點

C#winform批量給圖檔加水印代碼

//檔案下載下傳,裡面有exe可直接運作

<a target="_blank" href="http://download.csdn.net/detail/pukuimin1226/6001759">http://download.csdn.net/detail/pukuimin1226/6001759</a>

//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&lt;string&gt; listExtention = new List&lt;string&gt;();

        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 在新線程中運作函數

        /// &lt;summary&gt;

        /// 在新線程中運作函數

        /// &lt;/summary&gt;

        /// &lt;param name="func"&gt;傳入 函數名(無參、無傳回值)&lt;/param&gt;

        /// &lt;param name="IsBackground"&gt;是否為背景線程(背景線程,視窗關閉後就終止線程)&lt;/param&gt;

        public static void ThreadNew(VoidFunction func, bool IsBackground)

            Thread th1 = new Thread(new ThreadStart(func));

            th1.IsBackground = IsBackground;//背景線程,視窗關閉後就終止線程

            th1.Start();

        /// &lt;param name="func"&gt;傳入 函數名(有一個參數、無傳回值)&lt;/param&gt;

        /// &lt;param name="para"&gt;object參數&lt;/param&gt;

        public static Thread ThreadNew(ParamFunction func, object para, bool IsBackground)

            Thread th1 = new Thread(new ParameterizedThreadStart(func));

            //判斷狀态

            //((int)th1.ThreadState &amp;((int)ThreadState.Running | (int)ThreadState.Suspended) ) == 0

            th1.IsBackground = IsBackground;

            th1.Start(para);

            return th1;

        /// 允許線程之間進行操作

        public static void OprateBetweenThread()

            System.Windows.Forms.Control.CheckForIllegalCrossThreadCalls = false;

        /// 無參的、傳回值為void的委托,可以用來做參數名

        public delegate void VoidFunction();

        /// 有一個參數的、傳回值為void的委托,可以用來做參數名

        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&lt;string&gt; PictureList = new List&lt;string&gt;();

                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&lt;string&gt; 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);

                        case ".png":

                            bitmap.Save(SourcePicPath, System.Drawing.Imaging.ImageFormat.Png);

                        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.Security.Cryptography;

using System.Web.Security;

namespace 圖檔加水印工具.BLL

    /// &lt;summary&gt;

    /// 可逆加密解密類

    /// &lt;/summary&gt;

    public static class DesEncrypt

        /// 解密函數

        /// &lt;param name="Text"&gt;要解密的字元串(必須是經過加密後的字元串才能解密成功)&lt;/param&gt;

        /// &lt;param name="sKey"&gt;key&lt;/param&gt;

        /// &lt;returns&gt;&lt;/returns&gt;

        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 &lt; 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());

        /// 加密函數

        /// &lt;param name="Text"&gt;要加密的字元串&lt;/param&gt;

        public static string Encrypt(string Text, string sKey)

            byte[] bytes = Encoding.Default.GetBytes(Text);

            CryptoStream stream2 = new CryptoStream(stream, provider.CreateEncryptor(), CryptoStreamMode.Write);

            stream2.Write(bytes, 0, bytes.Length);

            StringBuilder builder = new StringBuilder();

            foreach (byte num in stream.ToArray())

                builder.AppendFormat("{0:X2}", num);

            return builder.ToString();

        /// 字元串解密

        /// &lt;param name="Text"&gt;要解密的字元串(必須是加密後的!不然格式不對!)&lt;/param&gt;

        public static string Decrypt(string Text)

            return Decrypt(Text, "4B2A9A696326C4C3770DED74D5AFCECA");

        /// 字元串加密

        public static string Encrypt(string Text)

            return Encrypt(Text, "4B2A9A696326C4C3770DED74D5AFCECA");

//檔案儲存資訊類

using System.Text.RegularExpressions;

    #region 配置檔案類 ConfigFile

    /// 配置檔案類 ConfigFile,内容存儲到檔案中,繼承自配置接口 (一定要給ConfigFile.Instanse.fileName 指派)

    public class ConfigFile : IConfig

        #region 檔案實體路徑 fileName

        private string _fileName = "";

        /// 檔案實體路徑

        public string fileName

            get { return _fileName; }

            set { _fileName = value; }

        private ConfigFile() { }

        #region 單例模式,傳回一個靜态執行個體 Instanse

        private static ConfigFile _Instance;

        /// 執行個體

        public static ConfigFile Instanse

            get { if (_Instance == null) { _Instance = new ConfigFile(); } return _Instance; }

        #region CreateFile()檔案不存在則建立檔案

        /// CreateFile()檔案不存在則建立檔案

        /// &lt;returns&gt;傳回檔案是否是建立的&lt;/returns&gt;

        public bool CreateFile()

            bool isCreate = false;

            if (!File.Exists(fileName))

                using (File.Create(fileName))//建立完成後立即釋放資源,否則會占用、報錯

                isCreate = true;

            return isCreate;

        #region 支援Get,set方法取值、加入值、修改值 this[Key]

        /// 索引函數

        /// &lt;param name="Key"&gt;鍵(key)&lt;/param&gt;

        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");//如果是建立的檔案 ,直接加入

                    for (int i = 0; i &lt; lines.Length; i++)

                        string line = lines[i];

                        var match = Regex.Match(line, @"(\w+)=(\w+)");

                        //逐行找,如果遇到名字等于name的就把這一行的值修改

                        //然後寫回檔案

                            lines[i] = linekey + "=" + value;

                            File.WriteAllLines(fileName, lines);

                            return;//如果找到值并修改了,不繼續向下執行

                    File.AppendAllText(fileName, Key + "=" + value + "\r\n");//如果上面沒找到,加入鍵值到檔案結尾

        #region 得到所有鍵名稱的集合 List&lt;string&gt;

        /// 得到所有鍵名稱的集合 List《string》

        public string[] Keys

                List&lt;string&gt; listKey = new List&lt;string&gt;();

                    return listKey.ToArray();

                        listKey.Add(linekey);

        #region 是否存在鍵 KeyExists(Key)

        /// 是否存在鍵 KeyExists(Key)

        /// &lt;param name="Key"&gt;鍵名稱&lt;/param&gt;

        public bool KeyExists(string Key)

            return (Keys as ICollection&lt;string&gt;).Contains(Key);

    #endregion

    #region 加密的配置檔案類 ConfigFileDES

    /// 加密的配置檔案類 ConfigFileDES,内容存儲到檔案中,使用時必須調用 ConfigFileDES.Instanse.SetIConfig(IConfig) 指派

    public class ConfigFileDES : IConfig

        private IConfig _iconfig = null;

        /// 接口變量

        public IConfig iconfig

            get { return _iconfig; }

            set { _iconfig = value; }

        private ConfigFileDES() { }

        private static ConfigFileDES _Instance;

        public static ConfigFileDES Instanse

            get { if (_Instance == null) { _Instance = new ConfigFileDES(); } return _Instance; }

        /// 傳入一個可操作的繼承自IConfig的類的對象

        /// &lt;param name="iconfig"&gt;繼承自IConfig的類的對象&lt;/param&gt;

        public void SetIConfig(IConfig iconfig)//本加密類是在其它實作IConfig的類基礎上進行,必須要傳入一個類的執行個體

            this.iconfig = iconfig;

        /// &lt;param name="key"&gt;名稱(key)&lt;/param&gt;

        public string this[string key]

                if (iconfig[key] == "") return "";

                return DesEncrypt.Decrypt(iconfig[key]);//解密後 取出

                iconfig[key] = DesEncrypt.Encrypt(value);//加密後 存入

        /// 所有鍵的集合

            get { return iconfig.Keys; }

        /// 是否存在

        /// &lt;param name="key"&gt;鍵(key)&lt;/param&gt;

        public bool KeyExists(string key)

            return iconfig.KeyExists(key);

    #region 配置接口  IConfig

    /// 配置接口  IConfig

    public interface IConfig

        /// 通過鍵得到對應的值

        /// &lt;param name="Key"&gt;鍵(key)&lt;/param&gt;

        string this[string Key] { get; set; }

        /// 傳回存在的鍵的集合

        string[] Keys { get; }

        /// 是否存在鍵

        /// &lt;param name="Key"&gt;鍵名&lt;/param&gt;

        bool KeyExists(string Key);

//窗體

C#winform批量給圖檔加水印代碼