c# 图片压缩工具的实现代码(图文)
本文导语: c#实现的图片压缩工具的截图如下: 可以添加单个文件,支持多选,也可以添加文件夹,自动遍历文件夹中的图片。 完整代码,用到了皮肤加载,在构造函数中。 有兴趣的朋友,慢慢研究吧,注释没有,可能看起来要费点劲...
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)
{
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# 图片压缩工具的源代码下载地址。