C# 按质量等级压缩图片(二)
|
admin
2023年2月27日 10:46
本文热度 485
|
这一篇我们呢采用的压缩方式跟上一篇是一样的,不同的是,这次我们会同时融入一个等比压缩宽高的方法,这两个一起使用,会使文件空间大幅度减小,同时也可以单独压缩宽高,质量等级不要变(直接用100即可);
实现功能:
开发环境:
开发工具:Visual Studio 2013
.NET Framework版本:4.5
实现代码:
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;
}
实现效果:
上面是将宽度和高度分别缩小了一半,看得出来,效果还是比较明显的
该文章在 2023/2/27 10:46:40 编辑过