c# 图片压缩工具的实现代码(图文)

发布时间:2021-01-13编辑:脚本学堂
要求如下:将视频采集卡采集过来的图片进行压缩处理,原有一张JPG默认320*240大小为300KB,经过压缩之后为6KB,压缩50倍!

c#实现的图片压缩工具的截图如下:
图片压缩工具

可以添加单个文件,支持多选,也可以添加文件夹,自动遍历文件夹中的图片。

完整代码,用到了皮肤加载,在构造函数中。
有兴趣的朋友,慢慢研究吧,注释没有,可能看起来要费点劲了。
 

复制代码 代码示例:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using SKINPPDOTNETLib;

namespace EcanPicTools
{
    public partial class frmMain : Form
    {
        Image img;
        Bitmap bmp;
        Graphics grap;
        int width, height;

        SKINPPDOTNETLib.SkinPPDotNetClass myskin = new SkinPPDotNetClass();
        public frmMain()
        {
            InitializeComponent();
            this.txtbili.KeyPress += new KeyPressEventHandler(txt_KeyPress);
            this.txtWidth.KeyPress += new KeyPressEventHandler(txt_KeyPress);
            this.txtHeight.KeyPress += new KeyPressEventHandler(txt_KeyPress);
            Control.CheckForIllegalCrossThreadCalls = false;
            myskin.LoadSkin(Application.StartupPath + @"spring.ssk", true);
        }

        private void frmMain_Load(object sender, EventArgs e)
        {
            init();
        }

        private void init()
        {
            this.Text = "图片压缩工具(作者:刘典武)---普通模式";
            labTransparent.Text = "透明值:100%";
            txtWidth.Enabled = false;
            txtHeight.Enabled = false;
            rbtnbili.checked = true;
            txtbili.Focus();
        }

        private void txt_KeyPress(object sender, KeyPressEventArgs e)
        {
            if ((e.KeyChar < 48 || e.KeyChar > 57) && (e.KeyChar != 8))
            {
                e.Handled = true;
            }
            base.OnKeyPress(e);
        }

        private void yasuo(string frompath, string topath)
        {
            try
            {
                img = Image.FromFile(frompath);

                if (rbtnbili.Checked)
                {
                    width = Convert.ToInt32(img.Width * (Convert.ToDouble(txtbili.Text) / 100));
                    height = Convert.ToInt32(img.Height * (Convert.ToDouble(txtbili.Text) / 100));
                }
                else
                {
                    width = Convert.ToInt32(txtWidth.Text.Trim());
                    height = Convert.ToInt32(txtHeight.Text.Trim());
                }

                bmp = new Bitmap(width, height);
                grap = Graphics.FromImage(bmp);
                grap.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                grap.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                grap.DrawImage(img, new Rectangle(0, 0, width, height));

                bmp.Save(topath, System.Drawing.Imaging.ImageFormat.Jpeg);
                bmp.Dispose();
                img.Dispose();
                grap.Dispose();
            }
            catch (Exception ex) { MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error); }
            finally { }
        }

        private void btnStart_Click(object sender, EventArgs e)
        {
            if (lboxPicPath.Items.Count <= 0)
            {
                MessageBox.Show("你还没有选择要压缩的图片!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            if (txtSavePath.Text == "")
            {
                MessageBox.Show("你还没有选择要保存的文件夹路径!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            pbar.Maximum = lboxPicPath.Items.Count;
            pbar.Value = 0;

            if (rbtnbili.Checked && txtbili.Text == "")
            {
                MessageBox.Show("请填好比例值!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                txtbili.Focus();
                return;
            }
            else if (rbtnkg.Checked && (txtHeight.Text == "" || txtWidth.Text == ""))
            {
                MessageBox.Show("请填好宽高值!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                txtWidth.Focus();
                return;
            }

            for (int i = 0; i < lboxPicPath.Items.Count; i++)
            {
                pbar.Value = i + 1;
                this.yasuo(lboxPicPath.Items[i].ToString(), txtSavePath.Text + "" + Path.GetFileName(lboxPicPath.Items[i].ToString()));
                labInfo.Text = "已经压缩图片张数:" + Convert.ToString(i + 1);
            }
            MessageBox.Show("恭喜,压缩图片成功!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        private void btnShow_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog fbd = new FolderBrowserDialog();
            if (fbd.ShowDialog() == DialogResult.OK)
            {
                this.getFile(fbd.SelectedPath);
            }
        }

        private void getFile(string path)
        {
            DirectoryInfo pic = new DirectoryInfo(path);
            foreach (FileInfo file in pic.GetFiles("*.*"))
            {
                lboxPicPath.Items.Add(file.FullName);
            }
        }

        private void btnShowSavePath_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog fbd = new FolderBrowserDialog();
            fbd.Description = "请选择保存输出图像路径";
            fbd.ShowNewFolderButton = true;

            if (fbd.ShowDialog() == DialogResult.OK)
            {
                if (fbd.SelectedPath.ToString() != "")
                {
                    txtSavePath.Text = fbd.SelectedPath;
                }
            }
        }

        private void btnSelect_Click(object sender, EventArgs e)
        {
            OpenFileDialog open = new OpenFileDialog();
            open.Title = "请选择要压缩的图片";
            open.Filter = "图片文件(*.jpg,*.bmp,*.png,*.gif)|*.jpg;*.bmp;*.png;*.gif";
            open.Multiselect = true;
            if (open.ShowDialog() == DialogResult.OK)
            {
                foreach (string file in open.FileNames)
                {
                    lboxPicPath.Items.Add(file);
                }
            }
        }

        private void picTop_Click(object sender, EventArgs e)
        {
            if (this.TopMost)
            {
                this.TopMost = false;
                this.Text = "图片压缩工具(作者:刘典武)---普通模式";
            }
            else
            {
                this.TopMost = true;
                this.Text = "图片压缩工具(作者:刘典武)---置顶模式";
            }
        }

        private void tbarTransparent_Scroll(object sender, EventArgs e)
        {
            labTransparent.Text = "透明值:" + Convert.ToString(100 - tbarTransparent.Value) + "%";

            this.Opacity = 1 - (float)(tbarTransparent.Value) / 100;
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            if (lboxPicPath.SelectedItems.Count > 0)
            {
                for (int i = lboxPicPath.SelectedItems.Count - 1; i >= 0; i--)
                {
                    lboxPicPath.Items.Remove(lboxPicPath.SelectedItems[i]);
                }
            }
            else
            {
                MessageBox.Show("请选择要移除的文件", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        private void rbtnbili_CheckedChanged(object sender, EventArgs e)
        {
            txtbili.Enabled = rbtnbili.Checked;
            if (rbtnbili.Checked)
            {
                txtbili.Focus();
            }
        }

        private void rbtnkg_CheckedChanged(object sender, EventArgs e)
        {
            txtWidth.Enabled = rbtnkg.Checked;
            txtHeight.Enabled = rbtnkg.Checked;
            if (rbtnkg.Checked)
            {
                txtWidth.Focus();
            }
        }

    }
}

附:c# 图片压缩工具的源代码下载地址