有時候我們對一些較大的圖片進行保存的時候,需要進一步壓縮以縮小其占用空間,達到節(jié)約內(nèi)存的目的,亦或者前后端傳輸?shù)臅r候,壓縮空間以增快傳輸效率。
所以本篇文章在下面分三個質(zhì)量等級對圖片進行了壓縮,在效果圖中可以看到明顯的大小變化以及圖片質(zhì)量的變化。
多的就不寫了,代碼比較簡單,大家自行運行測試吧
實現(xiàn)功能:
開發(fā)環(huán)境:
開發(fā)工具:Visual Studio 2013
.NET Framework版本:4.5
實現(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 btnCompress_Click(object sender, EventArgs e)
{
ImgCompress(10L);
ImgCompress(50L);
ImgCompress(70L);
MessageBox.Show("成功");
}
private void ImgCompress(long level)
{
Image img = Image.fromFile(txtOld.Text);
ImageFormat imgFormat = img.RawFormat;
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;
img.Save(savePath, codecInfo, encoderParams);
img.Dispose();
}
private ImageCodecInfo GetEncoder(ImageFormat format)
{
ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();
foreach (ImageCodecInfo codec in codecs)
{
if (codec.FormatID == format.Guid)
{
return codec;
}
}
return null;
}
實現(xiàn)效果:
該文章在 2023/2/27 10:41:33 編輯過