Winform文件夹图片批量压缩整理修改
效果图:
窗体设计器生成的代码:
namespace ImageCompact { partial class MainForm { /// <summary> /// 必需的设计器变量。 /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// 清理所有正在使用的资源。 /// </summary> /// <param name="disposing">如果应释放托管资源,为 true;否则为 false。</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows 窗体设计器生成的代码 /// <summary> /// 设计器支持所需的方法 - 不要 /// 使用代码编辑器修改此方法的内容。 /// </summary> private void InitializeComponent() { this.groupBox1 = new System.Windows.Forms.GroupBox(); this.lvSourceFolderList = new System.Windows.Forms.ListView(); this.columnHeader1 = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); this.btnSelectSourceFolder = new System.Windows.Forms.Button(); this.label1 = new System.Windows.Forms.Label(); this.tbSourceFolderPath = new System.Windows.Forms.TextBox(); this.groupBox2 = new System.Windows.Forms.GroupBox(); this.label6 = new System.Windows.Forms.Label(); this.label5 = new System.Windows.Forms.Label(); this.cbQualityRate = new System.Windows.Forms.ComboBox(); this.cbSizeRate = new System.Windows.Forms.ComboBox(); this.label4 = new System.Windows.Forms.Label(); this.label3 = new System.Windows.Forms.Label(); this.lvResultList = new System.Windows.Forms.ListView(); this.压缩文件 = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); this.压缩结果 = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); this.btnSelectTargetFolder = new System.Windows.Forms.Button(); this.label2 = new System.Windows.Forms.Label(); this.tbTargetFolderPath = new System.Windows.Forms.TextBox(); this.lbInfomation = new System.Windows.Forms.Label(); this.btnClose = new System.Windows.Forms.Button(); this.btnStart = new System.Windows.Forms.Button(); this.folderBrowserDialog = new System.Windows.Forms.FolderBrowserDialog(); this.groupBox1.SuspendLayout(); this.groupBox2.SuspendLayout(); this.SuspendLayout(); // // groupBox1 // this.groupBox1.Controls.Add(this.lvSourceFolderList); this.groupBox1.Controls.Add(this.btnSelectSourceFolder); this.groupBox1.Controls.Add(this.label1); this.groupBox1.Controls.Add(this.tbSourceFolderPath); this.groupBox1.Location = new System.Drawing.Point(12, 12); this.groupBox1.Name = "groupBox1"; this.groupBox1.Size = new System.Drawing.Size(819, 268); this.groupBox1.TabIndex = 0; this.groupBox1.TabStop = false; this.groupBox1.Text = "文件来源"; // // lvSourceFolderList // this.lvSourceFolderList.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] { this.columnHeader1}); this.lvSourceFolderList.FullRowSelect = true; this.lvSourceFolderList.GridLines = true; this.lvSourceFolderList.HeaderStyle = System.Windows.Forms.ColumnHeaderStyle.Nonclickable; this.lvSourceFolderList.Location = new System.Drawing.Point(10, 58); this.lvSourceFolderList.MultiSelect = false; this.lvSourceFolderList.Name = "lvSourceFolderList"; this.lvSourceFolderList.Size = new System.Drawing.Size(796, 204); this.lvSourceFolderList.TabIndex = 3; this.lvSourceFolderList.UseCompatibleStateImageBehavior = false; this.lvSourceFolderList.View = System.Windows.Forms.View.Details; // // columnHeader1 // this.columnHeader1.Text = "图片文件"; this.columnHeader1.Width = 499; // // btnSelectSourceFolder // this.btnSelectSourceFolder.Location = new System.Drawing.Point(731, 18); this.btnSelectSourceFolder.Name = "btnSelectSourceFolder"; this.btnSelectSourceFolder.Size = new System.Drawing.Size(75, 23); this.btnSelectSourceFolder.TabIndex = 2; this.btnSelectSourceFolder.Text = "浏览"; this.btnSelectSourceFolder.UseVisualStyleBackColor = true; this.btnSelectSourceFolder.Click += new System.EventHandler(this.btnSelectSourceFolder_Click); // // label1 // this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point(8, 23); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(65, 12); this.label1.TabIndex = 1; this.label1.Text = "选择文件夹"; // // tbSourceFolderPath // this.tbSourceFolderPath.Location = new System.Drawing.Point(74, 20); this.tbSourceFolderPath.Name = "tbSourceFolderPath"; this.tbSourceFolderPath.Size = new System.Drawing.Size(655, 21); this.tbSourceFolderPath.TabIndex = 0; // // groupBox2 // this.groupBox2.Controls.Add(this.label6); this.groupBox2.Controls.Add(this.label5); this.groupBox2.Controls.Add(this.cbQualityRate); this.groupBox2.Controls.Add(this.cbSizeRate); this.groupBox2.Controls.Add(this.label4); this.groupBox2.Controls.Add(this.label3); this.groupBox2.Controls.Add(this.lvResultList); this.groupBox2.Controls.Add(this.btnSelectTargetFolder); this.groupBox2.Controls.Add(this.label2); this.groupBox2.Controls.Add(this.tbTargetFolderPath); this.groupBox2.Location = new System.Drawing.Point(12, 286); this.groupBox2.Name = "groupBox2"; this.groupBox2.Size = new System.Drawing.Size(819, 274); this.groupBox2.TabIndex = 1; this.groupBox2.TabStop = false; this.groupBox2.Text = "保存到"; // // label6 // this.label6.AutoSize = true; this.label6.Location = new System.Drawing.Point(288, 251); this.label6.Name = "label6"; this.label6.Size = new System.Drawing.Size(11, 12); this.label6.TabIndex = 12; this.label6.Text = "%"; // // label5 // this.label5.AutoSize = true; this.label5.Location = new System.Drawing.Point(133, 252); this.label5.Name = "label5"; this.label5.Size = new System.Drawing.Size(11, 12); this.label5.TabIndex = 11; this.label5.Text = "%"; // // cbQualityRate // this.cbQualityRate.FormattingEnabled = true; this.cbQualityRate.Items.AddRange(new object[] { "10", "20", "22", "25", "27", "30", "40", "50", "60", "70", "80", "90", "100"}); this.cbQualityRate.Location = new System.Drawing.Point(226, 246); this.cbQualityRate.Name = "cbQualityRate"; this.cbQualityRate.Size = new System.Drawing.Size(56, 20); this.cbQualityRate.TabIndex = 10; // // cbSizeRate // this.cbSizeRate.FormattingEnabled = true; this.cbSizeRate.Items.AddRange(new object[] { "10", "20", "30", "40", "50", "60", "70", "80", "90", "100"}); this.cbSizeRate.Location = new System.Drawing.Point(74, 247); this.cbSizeRate.Name = "cbSizeRate"; this.cbSizeRate.Size = new System.Drawing.Size(56, 20); this.cbSizeRate.TabIndex = 9; // // label4 // this.label4.AutoSize = true; this.label4.Location = new System.Drawing.Point(160, 252); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(59, 12); this.label4.TabIndex = 8; this.label4.Text = "压缩质量:"; // // label3 // this.label3.AutoSize = true; this.label3.Location = new System.Drawing.Point(8, 251); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(59, 12); this.label3.TabIndex = 7; this.label3.Text = "压缩大小:"; // // lvResultList // this.lvResultList.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] { this.压缩文件, this.压缩结果}); this.lvResultList.FullRowSelect = true; this.lvResultList.GridLines = true; this.lvResultList.HeaderStyle = System.Windows.Forms.ColumnHeaderStyle.Nonclickable; this.lvResultList.Location = new System.Drawing.Point(6, 54); this.lvResultList.MultiSelect = false; this.lvResultList.Name = "lvResultList"; this.lvResultList.Size = new System.Drawing.Size(796, 187); this.lvResultList.TabIndex = 6; this.lvResultList.UseCompatibleStateImageBehavior = false; this.lvResultList.View = System.Windows.Forms.View.Details; // // 压缩文件 // this.压缩文件.Text = "压缩文件"; this.压缩文件.Width = 596; // // 压缩结果 // this.压缩结果.Text = "压缩结果"; this.压缩结果.TextAlign = System.Windows.Forms.HorizontalAlignment.Center; this.压缩结果.Width = 108; // // btnSelectTargetFolder // this.btnSelectTargetFolder.Location = new System.Drawing.Point(731, 12); this.btnSelectTargetFolder.Name = "btnSelectTargetFolder"; this.btnSelectTargetFolder.Size = new System.Drawing.Size(75, 23); this.btnSelectTargetFolder.TabIndex = 5; this.btnSelectTargetFolder.Text = "浏览"; this.btnSelectTargetFolder.UseVisualStyleBackColor = true; this.btnSelectTargetFolder.Click += new System.EventHandler(this.btnSelectTargetFolder_Click); // // label2 // this.label2.AutoSize = true; this.label2.Location = new System.Drawing.Point(8, 17); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(65, 12); this.label2.TabIndex = 4; this.label2.Text = "选择文件夹"; // // tbTargetFolderPath // this.tbTargetFolderPath.Location = new System.Drawing.Point(74, 14); this.tbTargetFolderPath.Name = "tbTargetFolderPath"; this.tbTargetFolderPath.Size = new System.Drawing.Size(655, 21); this.tbTargetFolderPath.TabIndex = 3; // // lbInfomation // this.lbInfomation.AutoSize = true; this.lbInfomation.Location = new System.Drawing.Point(18, 574); this.lbInfomation.Name = "lbInfomation"; this.lbInfomation.Size = new System.Drawing.Size(53, 12); this.lbInfomation.TabIndex = 2; this.lbInfomation.Text = "已经停止"; // // btnClose // this.btnClose.Location = new System.Drawing.Point(614, 567); this.btnClose.Name = "btnClose"; this.btnClose.Size = new System.Drawing.Size(75, 23); this.btnClose.TabIndex = 3; this.btnClose.Text = "关闭"; this.btnClose.UseVisualStyleBackColor = true; this.btnClose.Click += new System.EventHandler(this.btnClose_Click); // // btnStart // this.btnStart.Location = new System.Drawing.Point(717, 566); this.btnStart.Name = "btnStart"; this.btnStart.Size = new System.Drawing.Size(75, 23); this.btnStart.TabIndex = 4; this.btnStart.Text = "开始压缩"; this.btnStart.UseVisualStyleBackColor = true; this.btnStart.Click += new System.EventHandler(this.btnStart_Click); // // MainForm // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(838, 604); this.Controls.Add(this.btnStart); this.Controls.Add(this.btnClose); this.Controls.Add(this.lbInfomation); this.Controls.Add(this.groupBox2); this.Controls.Add(this.groupBox1); this.Name = "MainForm"; this.Text = "图片批量压缩"; this.groupBox1.ResumeLayout(false); this.groupBox1.PerformLayout(); this.groupBox2.ResumeLayout(false); this.groupBox2.PerformLayout(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.GroupBox groupBox1; private System.Windows.Forms.GroupBox groupBox2; private System.Windows.Forms.Label label1; private System.Windows.Forms.TextBox tbSourceFolderPath; private System.Windows.Forms.Button btnSelectSourceFolder; private System.Windows.Forms.Button btnSelectTargetFolder; private System.Windows.Forms.Label label2; private System.Windows.Forms.TextBox tbTargetFolderPath; private System.Windows.Forms.ListView lvSourceFolderList; private System.Windows.Forms.ListView lvResultList; private System.Windows.Forms.Label label4; private System.Windows.Forms.Label label3; private System.Windows.Forms.Label label6; private System.Windows.Forms.Label label5; private System.Windows.Forms.ComboBox cbQualityRate; private System.Windows.Forms.ComboBox cbSizeRate; private System.Windows.Forms.Label lbInfomation; private System.Windows.Forms.Button btnClose; private System.Windows.Forms.Button btnStart; private System.Windows.Forms.ColumnHeader columnHeader1; private System.Windows.Forms.ColumnHeader 压缩文件; private System.Windows.Forms.ColumnHeader 压缩结果; private System.Windows.Forms.FolderBrowserDialog folderBrowserDialog; } }
后台代码:
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 Microsoft.Win32; using System.IO; using System.Threading; using System.Drawing.Imaging; namespace ImageCompact { public partial class MainForm : Form { /// <summary> /// 定义文件列表 /// </summary> private IList<string> imageList = new List<string>(); /// <summary> /// 压缩结果信息 /// </summary> /// <param name="file"></param> /// <param name="result"></param> private delegate void DelegateWriteResult(string file, bool result); /// <summary> /// 压缩状态信息 /// </summary> /// <param name="message"></param> private delegate void DelegateWriteMessage(string message); public MainForm() { InitializeComponent(); //压缩大小默认显示选项 cbSizeRate.SelectedIndex = 8; //压缩质量默认显示选项 cbQualityRate.SelectedIndex = 8; RegistryKey folders; folders = OpenRegistryPath(Registry.CurrentUser, @"\software\microsoft\windows\currentversion\explorer\shell folders"); //保存的选择文件夹默认路径 tbTargetFolderPath.Text = folders.GetValue("Desktop").ToString(); } /// <summary> /// 获得注册表键对象 /// </summary> /// <returns></returns> private RegistryKey OpenRegistryPath(RegistryKey root, string s) { s = s.Remove(0, 1) + @"\"; while (s.IndexOf(@"\") != -1) { root = root.OpenSubKey(s.Substring(0, s.IndexOf(@"\"))); s = s.Remove(0, s.IndexOf(@"\") + 1); } return root; } /// <summary> /// 浏览选择文件夹 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnSelectSourceFolder_Click(object sender, EventArgs e) { if (DialogResult.OK == folderBrowserDialog.ShowDialog()) { this.lvSourceFolderList.Items.Clear(); tbSourceFolderPath.Text = folderBrowserDialog.SelectedPath; ListFiles(new DirectoryInfo(tbSourceFolderPath.Text)); } } /// <summary> /// 遍历文件 /// </summary> /// <param name="info"></param> public void ListFiles(FileSystemInfo info) { if (!info.Exists) return; DirectoryInfo dir = info as DirectoryInfo; if (dir == null) return; FileSystemInfo[] files = dir.GetFileSystemInfos(); for (int i = 0; i < files.Length; i++) { FileInfo file = files[i] as FileInfo; if (file != null && file.Name.Trim().LastIndexOf(".") > -1) { if (file.Name.Substring(file.Name.LastIndexOf(".")).ToUpper() == ".JPG") { this.lvSourceFolderList.Items.Add(file.FullName); imageList.Add(file.FullName); } } else { ListFiles(files[i]); //对于子目录,进行递归调用 } } } /// <summary> /// 将文件列表加载到list中 /// </summary> /// <param name="path"></param> //private void ScanFolder(string path) //{ // imageList = new List<string>(); // string[] images = Directory.GetFiles(path, "*.bmp"); // for (int i = 0; i < images.Length; i++) // { // imageList.Add(images[i]); // } // images = Directory.GetFiles(path, "*.png"); // for (int i = 0; i < images.Length; i++) // { // imageList.Add(images[i]); // } // images = Directory.GetFiles(path, "*.jpg"); // for (int i = 0; i < images.Length; i++) // { // imageList.Add(images[i]); // } // if (imageList.Count > 0) // { // ListFiles(); // } //} /// <summary> /// 加载文件列表到listview /// </summary> private void ListFiles() { lvSourceFolderList.Items.Clear(); foreach (string item in imageList) { lvSourceFolderList.Items.Add(item); } } /// <summary> /// 保存到文件路径 的 选择文件夹 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnSelectTargetFolder_Click(object sender, EventArgs e) { if (DialogResult.OK == folderBrowserDialog.ShowDialog()) { tbTargetFolderPath.Text = folderBrowserDialog.SelectedPath; } } /// <summary> /// 退出 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnClose_Click(object sender, EventArgs e) { Application.Exit(); } /// <summary> /// 开始压缩 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnStart_Click(object sender, EventArgs e) { if (!Directory.Exists(tbTargetFolderPath.Text)) { MessageBox.Show("目标文件夹不存在,请先建立这个文件夹。", "存储错误", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } if (Directory.GetFiles(tbTargetFolderPath.Text).Length > 0) { if (DialogResult.OK != MessageBox.Show("目标文件夹不是空的,同名文件将被覆盖,确认?", "目标文件夹不是空的", MessageBoxButtons.OKCancel, MessageBoxIcon.Question)) { return; } } lvResultList.Items.Clear(); Thread workThread = new Thread(new ThreadStart(CompressAll)); workThread.IsBackground = true; workThread.Start(); } /// <summary> /// 压缩所有文件 /// </summary> private void CompressAll() { string message = ""; foreach (string item in imageList) { int index = item.LastIndexOf("\\"); if (index != -1) { string fileName = item.Substring(index + 1); string targetFilePath = tbTargetFolderPath.Text + "\\" + fileName; message = "正在处理" + fileName; if (this.InvokeRequired) { this.Invoke(new DelegateWriteMessage(WriteMessage), new object[] { message }); } else { this.WriteMessage(message); } if (CompressPicture(item, targetFilePath)) { if (this.InvokeRequired) { this.Invoke(new DelegateWriteResult(WriteResult), new object[] { item, true }); } else { this.WriteResult(item, true); } } else { if (this.InvokeRequired) { this.Invoke(new DelegateWriteResult(WriteResult), new object[] { item, false }); } else { this.WriteResult(item, false); } } } } message = "全部完成"; if (this.InvokeRequired) { this.Invoke(new DelegateWriteMessage(WriteMessage), new object[] { message }); } else { this.WriteMessage(message); } } /// <summary> /// 显示状态信息 /// </summary> /// <param name="message"></param> private void WriteMessage(string message) { lbInfomation.Text = message; } /// <summary> /// 显示压缩结果信息 /// </summary> /// <param name="fileName"></param> /// <param name="result"></param> private void WriteResult(string fileName, bool result) { if (result) { ListViewItem thisListItem = new ListViewItem(); thisListItem.ForeColor = Color.White; thisListItem.BackColor = Color.DarkGreen; thisListItem.SubItems[0].Text = fileName; thisListItem.SubItems.Add("成功"); lvResultList.Items.Add(thisListItem); } else { ListViewItem thisListItem = new ListViewItem(); thisListItem.ForeColor = Color.White; thisListItem.BackColor = Color.Red; thisListItem.SubItems[0].Text = fileName; thisListItem.SubItems.Add("失败"); lvResultList.Items.Add(thisListItem); } } /// <summary> /// 压缩图片方法 /// </summary> /// <param name="sourcePath">原目录</param> /// <param name="targetPath">目标目录</param> /// <returns>压缩是否成功</returns> private bool CompressPicture(string sourcePath, string targetPath) { try { double sizeRate = double.Parse(cbSizeRate.Text) / 100;// 大小比率 int qualityRate = int.Parse(cbQualityRate.Text);// 品质比率 Image sourceImage = Image.FromFile(sourcePath); //调整图片大小 Bitmap bmp = new Bitmap(sourceImage, new Size((int)(sourceImage.Width * sizeRate), (int)(sourceImage.Height * sizeRate))); //压缩图片 SaveAsJPEG(bmp, targetPath, qualityRate); GC.Collect(); return true; } catch { return false; } } /// <summary> /// 保存为JPEG格式,支持压缩质量选项 /// </summary> /// <param name="bmp">原始位图</param> /// <param name="FileName">新文件地址</param> /// <param name="Qty">压缩质量,越大越好,文件也越大(0-100)</param> /// <returns>成功标志</returns> public static bool SaveAsJPEG(Bitmap bmp, string FileName, int Qty) { try { EncoderParameter p; EncoderParameters ps; ps = new EncoderParameters(1); p = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, Qty); ps.Param[0] = p; bmp.Save(FileName, GetCodecInfo("image/jpeg"), ps); return true; } catch { return false; } } /// <summary> /// 保存JPG时用 /// </summary> /// <param name="mimeType"></param> /// <returns>得到指定mimeType的ImageCodecInfo</returns> private static ImageCodecInfo GetCodecInfo(string mimeType) { ImageCodecInfo[] CodecInfo = ImageCodecInfo.GetImageEncoders(); foreach (ImageCodecInfo ici in CodecInfo) { if (ici.MimeType == mimeType) return ici; } return null; } } }