//文件下载,里面有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 }
//窗体
评论列表: