效果图:

窗体设计器生成的代码:

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(, );
this.groupBox1.Name = "groupBox1";
this.groupBox1.Size = new System.Drawing.Size(, );
this.groupBox1.TabIndex = ;
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(, );
this.lvSourceFolderList.MultiSelect = false;
this.lvSourceFolderList.Name = "lvSourceFolderList";
this.lvSourceFolderList.Size = new System.Drawing.Size(, );
this.lvSourceFolderList.TabIndex = ;
this.lvSourceFolderList.UseCompatibleStateImageBehavior = false;
this.lvSourceFolderList.View = System.Windows.Forms.View.Details;
//
// columnHeader1
//
this.columnHeader1.Text = "图片文件";
this.columnHeader1.Width = ;
//
// btnSelectSourceFolder
//
this.btnSelectSourceFolder.Location = new System.Drawing.Point(, );
this.btnSelectSourceFolder.Name = "btnSelectSourceFolder";
this.btnSelectSourceFolder.Size = new System.Drawing.Size(, );
this.btnSelectSourceFolder.TabIndex = ;
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(, );
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(, );
this.label1.TabIndex = ;
this.label1.Text = "选择文件夹";
//
// tbSourceFolderPath
//
this.tbSourceFolderPath.Location = new System.Drawing.Point(, );
this.tbSourceFolderPath.Name = "tbSourceFolderPath";
this.tbSourceFolderPath.Size = new System.Drawing.Size(, );
this.tbSourceFolderPath.TabIndex = ;
//
// 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(, );
this.groupBox2.Name = "groupBox2";
this.groupBox2.Size = new System.Drawing.Size(, );
this.groupBox2.TabIndex = ;
this.groupBox2.TabStop = false;
this.groupBox2.Text = "保存到";
//
// label6
//
this.label6.AutoSize = true;
this.label6.Location = new System.Drawing.Point(, );
this.label6.Name = "label6";
this.label6.Size = new System.Drawing.Size(, );
this.label6.TabIndex = ;
this.label6.Text = "%";
//
// label5
//
this.label5.AutoSize = true;
this.label5.Location = new System.Drawing.Point(, );
this.label5.Name = "label5";
this.label5.Size = new System.Drawing.Size(, );
this.label5.TabIndex = ;
this.label5.Text = "%";
//
// cbQualityRate
//
this.cbQualityRate.FormattingEnabled = true;
this.cbQualityRate.Items.AddRange(new object[] {
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
""});
this.cbQualityRate.Location = new System.Drawing.Point(, );
this.cbQualityRate.Name = "cbQualityRate";
this.cbQualityRate.Size = new System.Drawing.Size(, );
this.cbQualityRate.TabIndex = ;
//
// cbSizeRate
//
this.cbSizeRate.FormattingEnabled = true;
this.cbSizeRate.Items.AddRange(new object[] {
"",
"",
"",
"",
"",
"",
"",
"",
"",
""});
this.cbSizeRate.Location = new System.Drawing.Point(, );
this.cbSizeRate.Name = "cbSizeRate";
this.cbSizeRate.Size = new System.Drawing.Size(, );
this.cbSizeRate.TabIndex = ;
//
// label4
//
this.label4.AutoSize = true;
this.label4.Location = new System.Drawing.Point(, );
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(, );
this.label4.TabIndex = ;
this.label4.Text = "压缩质量:";
//
// label3
//
this.label3.AutoSize = true;
this.label3.Location = new System.Drawing.Point(, );
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(, );
this.label3.TabIndex = ;
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(, );
this.lvResultList.MultiSelect = false;
this.lvResultList.Name = "lvResultList";
this.lvResultList.Size = new System.Drawing.Size(, );
this.lvResultList.TabIndex = ;
this.lvResultList.UseCompatibleStateImageBehavior = false;
this.lvResultList.View = System.Windows.Forms.View.Details;
//
// 压缩文件
//
this.压缩文件.Text = "压缩文件";
this.压缩文件.Width = ;
//
// 压缩结果
//
this.压缩结果.Text = "压缩结果";
this.压缩结果.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
this.压缩结果.Width = ;
//
// btnSelectTargetFolder
//
this.btnSelectTargetFolder.Location = new System.Drawing.Point(, );
this.btnSelectTargetFolder.Name = "btnSelectTargetFolder";
this.btnSelectTargetFolder.Size = new System.Drawing.Size(, );
this.btnSelectTargetFolder.TabIndex = ;
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(, );
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(, );
this.label2.TabIndex = ;
this.label2.Text = "选择文件夹";
//
// tbTargetFolderPath
//
this.tbTargetFolderPath.Location = new System.Drawing.Point(, );
this.tbTargetFolderPath.Name = "tbTargetFolderPath";
this.tbTargetFolderPath.Size = new System.Drawing.Size(, );
this.tbTargetFolderPath.TabIndex = ;
//
// lbInfomation
//
this.lbInfomation.AutoSize = true;
this.lbInfomation.Location = new System.Drawing.Point(, );
this.lbInfomation.Name = "lbInfomation";
this.lbInfomation.Size = new System.Drawing.Size(, );
this.lbInfomation.TabIndex = ;
this.lbInfomation.Text = "已经停止";
//
// btnClose
//
this.btnClose.Location = new System.Drawing.Point(, );
this.btnClose.Name = "btnClose";
this.btnClose.Size = new System.Drawing.Size(, );
this.btnClose.TabIndex = ;
this.btnClose.Text = "关闭";
this.btnClose.UseVisualStyleBackColor = true;
this.btnClose.Click += new System.EventHandler(this.btnClose_Click);
//
// btnStart
//
this.btnStart.Location = new System.Drawing.Point(, );
this.btnStart.Name = "btnStart";
this.btnStart.Size = new System.Drawing.Size(, );
this.btnStart.TabIndex = ;
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(, );
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 = ;
//压缩质量默认显示选项
cbQualityRate.SelectedIndex = ; 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(, ) + @"\";
while (s.IndexOf(@"\") != -)
{
root = root.OpenSubKey(s.Substring(, s.IndexOf(@"\")));
s = s.Remove(, s.IndexOf(@"\") + );
}
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 = ; i < files.Length; i++)
{
FileInfo file = files[i] as FileInfo;
if (file != null && file.Name.Trim().LastIndexOf(".") > -)
{
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 > )
{
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 != -)
{
string fileName = item.Substring(index + ); 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[].Text = fileName;
thisListItem.SubItems.Add("成功");
lvResultList.Items.Add(thisListItem);
}
else
{
ListViewItem thisListItem = new ListViewItem();
thisListItem.ForeColor = Color.White;
thisListItem.BackColor = Color.Red;
thisListItem.SubItems[].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) / ;// 大小比率
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(); p = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, Qty);
ps.Param[] = 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;
}
}
}

最新文章

  1. 【USACO 1.4】Arithmetic Progressions
  2. ucenter的单点登录
  3. xampp 访问出现New XAMPP security concept 解决办法
  4. STM32F0xx_TIM输入捕获(计算频率)配置详细过程
  5. BZOJ 2768: [JLOI2010]冠军调查 最小割
  6. 版本控制Subversion TortoiseSVN apache VisualSVN笔记(转载)
  7. 数据结构(莫队算法):国家集训队2010 小Z的袜子
  8. 【linux】开发环境说明
  9. 记录OC学习的一点一滴(一)
  10. tools_list
  11. elk安装配置
  12. 10分钟明白对偶建模法 / +Leampms的“主模型建模”和“对偶模型建模” 之 —— 三类最短路径问题
  13. Docker发布程序那些事
  14. nvidia驱动自动更新版本后问题解决 -- failed to initialize nvml: driver/library version mismatch
  15. Vue入门基础
  16. [WC2011]最大XOR和路径(贪心+线性基)
  17. go channel tips
  18. C 转义字符说明
  19. R语言列表list函数
  20. MD5、SHA校验命令

热门文章

  1. 算法笔记_176:历届试题 最大子阵(Java)
  2. 虚拟机Linux下一直获取不到ip怎么办
  3. Codeforces Round #228 (Div. 1) C 贪心
  4. WebApi 数据保护操作未成功。这可能是由于未为当前线程的用户上下文加载用户配置文件导致的。当线程执行模拟时,可能会出现此情况。&quot;,&quot;ExceptionType&quot;:&quot;System.Security.Cryptography.CryptographicException&quot;,&quot;StackTrace
  5. TestNG方法測试及注意要点 代码及配置具体解释(解决testng方法不运行问题)
  6. eclipse c++ 经常使用快捷键
  7. spring mvc中@requesMapping的可配置参数和标注的处理方法的可选参数
  8. Redis学习(4)-数据类型,string,hash
  9. 微信小程序Tab选项卡切换大集合
  10. Android网络开发之WIFI