這一篇我們呢采用的壓縮方式跟上一篇是一樣的,不同的是,這次我們會同時融入一個等比壓縮寬高的方法,這兩個一起使用,會使文件空間大幅度減小,同時也可以單獨(dú)壓縮寬高,質(zhì)量等級不要變(直接用100即可);
實(shí)現(xiàn)功能:
開發(fā)環(huán)境:
開發(fā)工具:Visual Studio 2013
.NET Framework版本:4.5
實(shí)現(xiàn)代碼:
private void btnOld_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = "圖片|*.jpg;*.jpeg;*.png";
if (ofd.ShowDialog() == DialogResult.OK)
{
txtOld.Text = ofd.FileName;
}
}
private void btnNew_Click(object sender, EventArgs e)
{
FolderBrowserDialog fbd = new FolderBrowserDialog();
fbd.ShowNewFolderButton = true;
if (fbd.ShowDialog() == DialogResult.OK)
{
txtNew.Text = fbd.selectedPath;
}
}
private void btnCompressSize_Click(object sender, EventArgs e)
{
ImgSizeCompress(10L);
ImgSizeCompress(50L);
ImgSizeCompress(70L);
MessageBox.Show("成功");
}
private void ImgSizeCompress(long level)
{
Image img = Image.fromFile(txtOld.Text);
ImageFormat imgFormat = img.RawFormat;
Size newSize = new Size(img.Width / 2, img.Height / 2);
Bitmap outBmp = new Bitmap(newSize.Width, newSize.Height);
Graphics g = Graphics.fromImage(outBmp);
g.CompositingQuality = CompositingQuality.HighQuality;
g.SmoothingMode = SmoothingMode.HighQuality;
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
g.DrawImage(img, new Rectangle(0, 0, newSize.Width, newSize.Height), 0, 0, img.Width, img.Height, GraphicsUnit.Pixel);
g.Dispose();
img.Dispose();
EncoderParameters encoderParams = new EncoderParameters();
encoderParams.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, level);
ImageCodecInfo codecInfo = GetEncoder(imgFormat);
string savePath = txtNew.Text + "\\" + DateTime.Now.Ticks + "." + codecInfo.FormatDescription;
outBmp.Save(savePath, codecInfo, encoderParams);
outBmp.Dispose();
}
private ImageCodecInfo GetEncoder(ImageFormat format)
{
ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();
foreach (ImageCodecInfo codec in codecs)
{
if (codec.FormatID == format.Guid)
{
return codec;
}
}
return null;
}
實(shí)現(xiàn)效果:
上面是將寬度和高度分別縮小了一半,看得出來,效果還是比較明顯的
該文章在 2023/2/27 10:46:40 編輯過