C#實(shí)現(xiàn)無損壓縮圖片的示例詳解
更新時(shí)間:2022年12月12日 11:34:08 作者:芝麻粒兒
這篇文章主要為大家詳細(xì)介紹了如何利用C#實(shí)現(xiàn)無損壓縮圖片功能,文中的示例代碼講解詳細(xì),對我們學(xué)習(xí)C#有一定的幫助,感興趣的小伙伴可以了解一下
實(shí)踐過程
效果

代碼
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
FileSystemInfo[] fsi = null;
string ImgPath = "";
ArrayList al = new ArrayList();
string ImgSavePath = "";
string strSourcePath = "";
Thread td;
Image ig = null;
string strSavePath = "";
private void Form1_Load(object sender, EventArgs e)
{
CheckForIllegalCrossThreadCalls = false;
}
/// <summary>
/// 無損圖片縮放
/// </summary>
/// <param name="sFile">圖片的原始路徑</param>
/// <param name="dFile">縮放后圖片的保存路徑</param>
/// <param name="dHeight">縮放后圖片的高度</param>
/// <param name="dWidth">縮放后圖片的寬度</param>
/// <returns></returns>
public static bool GetPicThumbnail(string sFile, string dFile, int dHeight, int dWidth)
{
Image iSource = Image.FromFile(sFile);
ImageFormat tFormat = iSource.RawFormat;
int sW = 0, sH = 0;
// 按比例縮放
Size tem_size = new Size(iSource.Width, iSource.Height);
if (tem_size.Height > dHeight || tem_size.Width > dWidth)
{
if ((tem_size.Width * dHeight) > (tem_size.Height * dWidth))
{
sW = dWidth;
sH = (dWidth * tem_size.Height) / tem_size.Width;
}
else
{
sH = dHeight;
sW = (tem_size.Width * dHeight) / tem_size.Height;
}
}
else
{
sW = tem_size.Width;
sH = tem_size.Height;
}
Bitmap oB = new Bitmap(dWidth, dHeight);
Graphics g = Graphics.FromImage(oB);
g.Clear(Color.WhiteSmoke);
// 設(shè)置畫布的描繪質(zhì)量
g.CompositingQuality = CompositingQuality.HighQuality;
g.SmoothingMode = SmoothingMode.HighQuality;
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
g.DrawImage(iSource, new Rectangle((dWidth - sW) / 2, (dHeight - sH) / 2, sW, sH), 0, 0, iSource.Width, iSource.Height, GraphicsUnit.Pixel);
g.Dispose();
// 以下代碼為保存圖片時(shí),設(shè)置壓縮質(zhì)量
EncoderParameters eP = new EncoderParameters();
long[] qy = new long[1];
qy[0] = 100;
EncoderParameter eParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, qy);
eP.Param[0] = eParam;
try
{
//獲得包含有關(guān)內(nèi)置圖像編碼解碼器的信息的ImageCodecInfo對象。
ImageCodecInfo[] arrayICI = ImageCodecInfo.GetImageEncoders();
ImageCodecInfo jpegICIinfo = null;
for (int x = 0; x < arrayICI.Length; x++)
{
if (arrayICI[x].FormatDescription.Equals("JPEG"))
{
jpegICIinfo = arrayICI[x]; //設(shè)置JPEG編碼
break;
}
}
if (jpegICIinfo != null)
{
oB.Save(dFile, jpegICIinfo, eP);
}
else
{
oB.Save(dFile, tFormat);
}
return true;
}
catch
{
return false;
}
finally
{
iSource.Dispose();
oB.Dispose();
}
}
private void pictureBox1_Click(object sender, EventArgs e)
{
if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
{
fsi = null;
al.Clear();
txtPicPath.Text = folderBrowserDialog1.SelectedPath;
ImgPath = txtPicPath.Text.Trim();
DirectoryInfo di = new DirectoryInfo(txtPicPath.Text);
fsi = di.GetFileSystemInfos();
for (int i = 0; i < fsi.Length; i++)
{
string ofile = fsi[i].ToString();
string fileType = ofile.Substring(ofile.LastIndexOf(".") + 1, ofile.Length - ofile.LastIndexOf(".") - 1);
fileType = fileType.ToLower();
if (fileType == "jpeg" || fileType == "jpg" || fileType == "bmp" || fileType == "png")
{
al.Add(ofile);
}
}
lblPicNum.Text = al.Count.ToString();
}
}
private void pictureBox2_Click(object sender, EventArgs e)
{
if (folderBrowserDialog2.ShowDialog() == DialogResult.OK)
{
txtSavePath.Text = folderBrowserDialog2.SelectedPath;
ImgSavePath = txtSavePath.Text.Trim();
}
}
private void button2_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void rbPercent_Enter(object sender, EventArgs e)
{
groupBox1.Focus();
}
private void rbResolving_Enter(object sender, EventArgs e)
{
groupBox1.Focus();
}
private void CompleteIMG()
{
progressBar1.Maximum = al.Count;
progressBar1.Minimum = 1;
if (ImgPath.Length == 3)
strSourcePath = ImgPath;
else
strSourcePath = ImgPath + "\\";
if (ImgSavePath.Length == 3)
strSavePath = ImgSavePath;
else
strSavePath = ImgSavePath + "\\";
for (int i = 0; i < al.Count; i++)
{
ig = Image.FromFile(strSourcePath + al[i].ToString());
if (rbPercent.Checked)
{
GetPicThumbnail(strSourcePath + al[i].ToString(), strSavePath + al[i].ToString(), Convert.ToInt32(ig.Width * (numericUpDown1.Value / 100)),
Convert.ToInt32(ig.Height * (numericUpDown1.Value / 100)));
}
ig.Dispose();
progressBar1.Value = i + 1;
lblComplete.Text = Convert.ToString(i + 1);
}
if (lblComplete.Text == al.Count.ToString())
{
MessageBox.Show("壓縮成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
progressBar1.Value = 1;
pictureBox1.Enabled = true;
pictureBox2.Enabled = true;
rbPercent.Enabled = true;
lblPicNum.Text = "0";
lblComplete.Text = "0";
}
}
private void button1_Click(object sender, EventArgs e)
{
if (txtPicPath.Text.Trim() != "" && txtSavePath.Text.Trim() != "" && lblPicNum.Text != "0")
{
pictureBox1.Enabled = false;
pictureBox2.Enabled = false;
rbPercent.Enabled = false;
td = new Thread(new ThreadStart(this.CompleteIMG));
td.Start();
}
else
{
if (txtPicPath.Text.Trim() == "" && txtSavePath.Text.Trim() == "")
{
MessageBox.Show("警告:請選擇待處理的圖片目錄及保存位置", "警告", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else
{
if (txtPicPath.Text.Trim() == "")
MessageBox.Show("警告:請選擇待處理的圖片", "警告", MessageBoxButtons.OK, MessageBoxIcon.Error);
if (txtSavePath.Text.Trim() == "")
MessageBox.Show("警告:請選擇保存路徑", "警告", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
private void Form1_FormClosed(object sender, FormClosedEventArgs e)
{
if (td != null)
{
td.Abort();
}
}
}
partial class Form1
{
/// <summary>
/// 必需的設(shè)計(jì)器變量。
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// 清理所有正在使用的資源。
/// </summary>
/// <param name="disposing">如果應(yīng)釋放托管資源,為 true;否則為 false。</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows 窗體設(shè)計(jì)器生成的代碼
/// <summary>
/// 設(shè)計(jì)器支持所需的方法 - 不要
/// 使用代碼編輯器修改此方法的內(nèi)容。
/// </summary>
private void InitializeComponent()
{
this.groupBox1 = new System.Windows.Forms.GroupBox();
this.panel2 = new System.Windows.Forms.Panel();
this.pictureBox2 = new System.Windows.Forms.PictureBox();
this.txtSavePath = new System.Windows.Forms.TextBox();
this.panel1 = new System.Windows.Forms.Panel();
this.pictureBox1 = new System.Windows.Forms.PictureBox();
this.txtPicPath = new System.Windows.Forms.TextBox();
this.label2 = new System.Windows.Forms.Label();
this.label1 = new System.Windows.Forms.Label();
this.groupBox2 = new System.Windows.Forms.GroupBox();
this.numericUpDown1 = new System.Windows.Forms.NumericUpDown();
this.label4 = new System.Windows.Forms.Label();
this.label3 = new System.Windows.Forms.Label();
this.rbPercent = new System.Windows.Forms.RadioButton();
this.groupBox3 = new System.Windows.Forms.GroupBox();
this.progressBar1 = new System.Windows.Forms.ProgressBar();
this.label13 = new System.Windows.Forms.Label();
this.lblComplete = new System.Windows.Forms.Label();
this.lblPicNum = new System.Windows.Forms.Label();
this.label8 = new System.Windows.Forms.Label();
this.label7 = new System.Windows.Forms.Label();
this.button1 = new System.Windows.Forms.Button();
this.button2 = new System.Windows.Forms.Button();
this.folderBrowserDialog1 = new System.Windows.Forms.FolderBrowserDialog();
this.folderBrowserDialog2 = new System.Windows.Forms.FolderBrowserDialog();
this.groupBox1.SuspendLayout();
this.panel2.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBox2)).BeginInit();
this.panel1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit();
this.groupBox2.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.numericUpDown1)).BeginInit();
this.groupBox3.SuspendLayout();
this.SuspendLayout();
//
// groupBox1
//
this.groupBox1.Controls.Add(this.panel2);
this.groupBox1.Controls.Add(this.panel1);
this.groupBox1.Controls.Add(this.label2);
this.groupBox1.Controls.Add(this.label1);
this.groupBox1.Location = new System.Drawing.Point(3, 1);
this.groupBox1.Name = "groupBox1";
this.groupBox1.Size = new System.Drawing.Size(458, 81);
this.groupBox1.TabIndex = 0;
this.groupBox1.TabStop = false;
this.groupBox1.Text = "常規(guī)";
//
// panel2
//
this.panel2.BackColor = System.Drawing.Color.White;
this.panel2.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
this.panel2.Controls.Add(this.pictureBox2);
this.panel2.Controls.Add(this.txtSavePath);
this.panel2.Location = new System.Drawing.Point(130, 53);
this.panel2.Name = "panel2";
this.panel2.Size = new System.Drawing.Size(322, 21);
this.panel2.TabIndex = 5;
//
// pictureBox2
//
this.pictureBox2.Cursor = System.Windows.Forms.Cursors.PanSE;
this.pictureBox2.Image = global::CompressImg.Properties.Resources.文件夾打開;
this.pictureBox2.Location = new System.Drawing.Point(300, 0);
this.pictureBox2.Name = "pictureBox2";
this.pictureBox2.Size = new System.Drawing.Size(19, 18);
this.pictureBox2.TabIndex = 8;
this.pictureBox2.TabStop = false;
this.pictureBox2.Click += new System.EventHandler(this.pictureBox2_Click);
//
// txtSavePath
//
this.txtSavePath.BackColor = System.Drawing.Color.White;
this.txtSavePath.BorderStyle = System.Windows.Forms.BorderStyle.None;
this.txtSavePath.Location = new System.Drawing.Point(0, 1);
this.txtSavePath.Name = "txtSavePath";
this.txtSavePath.ReadOnly = true;
this.txtSavePath.Size = new System.Drawing.Size(302, 14);
this.txtSavePath.TabIndex = 1;
//
// panel1
//
this.panel1.BackColor = System.Drawing.Color.White;
this.panel1.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
this.panel1.Controls.Add(this.pictureBox1);
this.panel1.Controls.Add(this.txtPicPath);
this.panel1.Location = new System.Drawing.Point(130, 23);
this.panel1.Name = "panel1";
this.panel1.Size = new System.Drawing.Size(322, 21);
this.panel1.TabIndex = 4;
//
// pictureBox1
//
this.pictureBox1.Cursor = System.Windows.Forms.Cursors.PanSE;
this.pictureBox1.Image = global::CompressImg.Properties.Resources.文件夾打開;
this.pictureBox1.Location = new System.Drawing.Point(300, 0);
this.pictureBox1.Name = "pictureBox1";
this.pictureBox1.Size = new System.Drawing.Size(19, 18);
this.pictureBox1.TabIndex = 8;
this.pictureBox1.TabStop = false;
this.pictureBox1.Click += new System.EventHandler(this.pictureBox1_Click);
//
// txtPicPath
//
this.txtPicPath.BackColor = System.Drawing.Color.White;
this.txtPicPath.BorderStyle = System.Windows.Forms.BorderStyle.None;
this.txtPicPath.Location = new System.Drawing.Point(0, 1);
this.txtPicPath.Name = "txtPicPath";
this.txtPicPath.ReadOnly = true;
this.txtPicPath.Size = new System.Drawing.Size(302, 14);
this.txtPicPath.TabIndex = 1;
//
// label2
//
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(7, 57);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(125, 12);
this.label2.TabIndex = 2;
this.label2.Text = "處理后的圖片保存至:";
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(8, 28);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(125, 12);
this.label1.TabIndex = 0;
this.label1.Text = "等待處理的圖片位置:";
//
// groupBox2
//
this.groupBox2.Controls.Add(this.numericUpDown1);
this.groupBox2.Controls.Add(this.label4);
this.groupBox2.Controls.Add(this.label3);
this.groupBox2.Controls.Add(this.rbPercent);
this.groupBox2.Location = new System.Drawing.Point(3, 86);
this.groupBox2.Name = "groupBox2";
this.groupBox2.Size = new System.Drawing.Size(458, 47);
this.groupBox2.TabIndex = 1;
this.groupBox2.TabStop = false;
this.groupBox2.Text = "改變大小";
//
// numericUpDown1
//
this.numericUpDown1.Location = new System.Drawing.Point(188, 17);
this.numericUpDown1.Maximum = new decimal(new int[] {
200,
0,
0,
0});
this.numericUpDown1.Minimum = new decimal(new int[] {
1,
0,
0,
0});
this.numericUpDown1.Name = "numericUpDown1";
this.numericUpDown1.Size = new System.Drawing.Size(40, 21);
this.numericUpDown1.TabIndex = 8;
this.numericUpDown1.Value = new decimal(new int[] {
50,
0,
0,
0});
//
// label4
//
this.label4.AutoSize = true;
this.label4.Location = new System.Drawing.Point(234, 22);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(11, 12);
this.label4.TabIndex = 4;
this.label4.Text = "%";
//
// label3
//
this.label3.AutoSize = true;
this.label3.Location = new System.Drawing.Point(92, 22);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(89, 12);
this.label3.TabIndex = 2;
this.label3.Text = "改成原圖大小的";
//
// rbPercent
//
this.rbPercent.AutoSize = true;
this.rbPercent.Checked = true;
this.rbPercent.Location = new System.Drawing.Point(10, 20);
this.rbPercent.Name = "rbPercent";
this.rbPercent.Size = new System.Drawing.Size(71, 16);
this.rbPercent.TabIndex = 0;
this.rbPercent.TabStop = true;
this.rbPercent.Text = "按百分比";
this.rbPercent.UseVisualStyleBackColor = true;
this.rbPercent.Enter += new System.EventHandler(this.rbPercent_Enter);
//
// groupBox3
//
this.groupBox3.Controls.Add(this.progressBar1);
this.groupBox3.Controls.Add(this.label13);
this.groupBox3.Controls.Add(this.lblComplete);
this.groupBox3.Controls.Add(this.lblPicNum);
this.groupBox3.Controls.Add(this.label8);
this.groupBox3.Controls.Add(this.label7);
this.groupBox3.Location = new System.Drawing.Point(3, 139);
this.groupBox3.Name = "groupBox3";
this.groupBox3.Size = new System.Drawing.Size(458, 85);
this.groupBox3.TabIndex = 9;
this.groupBox3.TabStop = false;
this.groupBox3.Text = "操作顯示";
//
// progressBar1
//
this.progressBar1.Location = new System.Drawing.Point(107, 54);
this.progressBar1.Name = "progressBar1";
this.progressBar1.Size = new System.Drawing.Size(302, 18);
this.progressBar1.Step = 1;
this.progressBar1.TabIndex = 16;
//
// label13
//
this.label13.AutoSize = true;
this.label13.Location = new System.Drawing.Point(42, 57);
this.label13.Name = "label13";
this.label13.Size = new System.Drawing.Size(53, 12);
this.label13.TabIndex = 15;
this.label13.Text = "處理進(jìn)度";
//
// lblComplete
//
this.lblComplete.AutoSize = true;
this.lblComplete.Location = new System.Drawing.Point(339, 25);
this.lblComplete.Name = "lblComplete";
this.lblComplete.Size = new System.Drawing.Size(11, 12);
this.lblComplete.TabIndex = 12;
this.lblComplete.Text = "0";
//
// lblPicNum
//
this.lblPicNum.AutoSize = true;
this.lblPicNum.Location = new System.Drawing.Point(149, 26);
this.lblPicNum.Name = "lblPicNum";
this.lblPicNum.Size = new System.Drawing.Size(11, 12);
this.lblPicNum.TabIndex = 11;
this.lblPicNum.Text = "0";
//
// label8
//
this.label8.AutoSize = true;
this.label8.Location = new System.Drawing.Point(255, 26);
this.label8.Name = "label8";
this.label8.Size = new System.Drawing.Size(77, 12);
this.label8.TabIndex = 10;
this.label8.Text = "已經(jīng)處理成功";
//
// label7
//
this.label7.AutoSize = true;
this.label7.Location = new System.Drawing.Point(42, 26);
this.label7.Name = "label7";
this.label7.Size = new System.Drawing.Size(101, 12);
this.label7.TabIndex = 9;
this.label7.Text = "待處理的圖片共有";
//
// button1
//
this.button1.Location = new System.Drawing.Point(305, 230);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(75, 23);
this.button1.TabIndex = 10;
this.button1.Text = "開始壓縮";
this.button1.UseVisualStyleBackColor = true;
this.button1.Click += new System.EventHandler(this.button1_Click);
//
// button2
//
this.button2.Location = new System.Drawing.Point(386, 230);
this.button2.Name = "button2";
this.button2.Size = new System.Drawing.Size(75, 23);
this.button2.TabIndex = 11;
this.button2.Text = "取消";
this.button2.UseVisualStyleBackColor = true;
this.button2.Click += new System.EventHandler(this.button2_Click);
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(463, 261);
this.Controls.Add(this.button2);
this.Controls.Add(this.button1);
this.Controls.Add(this.groupBox3);
this.Controls.Add(this.groupBox2);
this.Controls.Add(this.groupBox1);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "Form1";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "無損壓縮圖片";
this.Load += new System.EventHandler(this.Form1_Load);
this.FormClosed += new System.Windows.Forms.FormClosedEventHandler(this.Form1_FormClosed);
this.groupBox1.ResumeLayout(false);
this.groupBox1.PerformLayout();
this.panel2.ResumeLayout(false);
this.panel2.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBox2)).EndInit();
this.panel1.ResumeLayout(false);
this.panel1.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit();
this.groupBox2.ResumeLayout(false);
this.groupBox2.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.numericUpDown1)).EndInit();
this.groupBox3.ResumeLayout(false);
this.groupBox3.PerformLayout();
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.GroupBox groupBox1;
private System.Windows.Forms.TextBox txtPicPath;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.GroupBox groupBox2;
private System.Windows.Forms.Label label4;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.RadioButton rbPercent;
private System.Windows.Forms.GroupBox groupBox3;
private System.Windows.Forms.Label label13;
private System.Windows.Forms.Label lblComplete;
private System.Windows.Forms.Label lblPicNum;
private System.Windows.Forms.Label label8;
private System.Windows.Forms.Label label7;
private System.Windows.Forms.Button button1;
private System.Windows.Forms.Button button2;
private System.Windows.Forms.Panel panel1;
private System.Windows.Forms.PictureBox pictureBox1;
private System.Windows.Forms.Panel panel2;
private System.Windows.Forms.PictureBox pictureBox2;
private System.Windows.Forms.TextBox txtSavePath;
private System.Windows.Forms.ProgressBar progressBar1;
private System.Windows.Forms.FolderBrowserDialog folderBrowserDialog1;
private System.Windows.Forms.FolderBrowserDialog folderBrowserDialog2;
private System.Windows.Forms.NumericUpDown numericUpDown1;
}
到此這篇關(guān)于C#實(shí)現(xiàn)無損壓縮圖片的示例詳解的文章就介紹到這了,更多相關(guān)C#無損壓縮圖片內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
C#實(shí)現(xiàn)過濾html標(biāo)簽并保留a標(biāo)簽的方法
這篇文章主要介紹了C#實(shí)現(xiàn)過濾html標(biāo)簽并保留a標(biāo)簽的方法,文中的自定義函數(shù)采用正則過濾實(shí)現(xiàn)了該功能,是非常實(shí)用的技巧,需要的朋友可以參考下2014-09-09
C#實(shí)現(xiàn)單鏈表(線性表)完整實(shí)例
這篇文章主要介紹了C#實(shí)現(xiàn)單鏈表(線性表)的方法,結(jié)合完整實(shí)例形式分析了單鏈表的原理、實(shí)現(xiàn)方法與相關(guān)注意事項(xiàng),需要的朋友可以參考下2016-06-06
C# dump系統(tǒng)lsass內(nèi)存和sam注冊表詳細(xì)
這篇文章主要介紹了C# dump系統(tǒng)lsass內(nèi)存和sam注冊表,在這里選擇 C# 的好處是體積小,結(jié)合 loadAssembly 方便免殺,希望對讀者們有所幫助2021-09-09
淺談C# 非模式窗體show()和模式窗體showdialog()的區(qū)別
下面小編就為大家?guī)硪黄獪\談C# 非模式窗體show()和模式窗體showdialog()的區(qū)別。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2016-07-07

