C# 大圖片壓縮算法,減少圖片體積
當(dāng)前位置:點晴教程→知識管理交流
→『 技術(shù)文檔交流 』
聲明: private void button3_Click(object sender, EventArgs e)
{
using (OpenFileDialog ofd = new
OpenFileDialog())
{ ofd.Filter = "圖片|*.jpg;*.png;*.gif;*.jpeg;*.bmp"; if
(ofd.ShowDialog() == DialogResult.OK) { using
(FileStream file = new FileStream(ofd.FileName, FileMode.Open)) { var
img = CompressionImage(file, 50L); MessageBox.Show(CreateImageFromBytes(AppDomain.CurrentDomain.BaseDirectory
+ @"\" + Guid.NewGuid().ToString(), img)); } }
}
}
///
public static Image BytesToImage(byte[]
buffer)
{
MemoryStream ms = new MemoryStream(buffer);
Image image = System.Drawing.Image.FromStream(ms);
return image;
}
///
public static string CreateImageFromBytes(string fileName, byte[] buffer)
{
string file = fileName;
Image image = BytesToImage(buffer);
ImageFormat format = image.RawFormat;
if (format.Equals(ImageFormat.Jpeg))
{ file += ".jpeg";
}
else if (format.Equals(ImageFormat.Png))
{ file += ".png";
}
else if (format.Equals(ImageFormat.Bmp))
{ file += ".bmp";
}
else if (format.Equals(ImageFormat.Gif))
{ file += ".gif";
}
else if (format.Equals(ImageFormat.Icon))
{ file += ".icon";
}
System.IO.FileInfo info = new System.IO.FileInfo(file);
System.IO.Directory.CreateDirectory(info.Directory.FullName);
File.WriteAllBytes(file, buffer);
return file;
}
/// ///
/// 圖片流
/// 壓縮質(zhì)量0-100之間 數(shù)值越大質(zhì)量越高
///
private byte[] CompressionImage(Stream fileStream, long
quality)
{
using (System.Drawing.Image img =
System.Drawing.Image.FromStream(fileStream))
{ using
(Bitmap bitmap = new Bitmap(img)) { ImageCodecInfo CodecInfo
= GetEncoder(img.RawFormat);
System.Drawing.Imaging.Encoder myEncoder =
System.Drawing.Imaging.Encoder.Quality; EncoderParameters myEncoderParameters
= new EncoderParameters(1); EncoderParameter
myEncoderParameter = new EncoderParameter(myEncoder, quality); myEncoderParameters.Param[0]
= myEncoderParameter; using
(MemoryStream ms = new MemoryStream()) { bitmap.Save(ms,
CodecInfo, myEncoderParameters);
myEncoderParameters.Dispose();
myEncoderParameter.Dispose(); return ms.ToArray(); } }
}
}
private static ImageCodecInfo GetEncoder(ImageFormat
format)
{
ImageCodecInfo[] codecs = ImageCodecInfo.GetImageDecoders();
foreach (ImageCodecInfo codec in
codecs)
{ if
(codec.FormatID == format.Guid) { return
codec; }
}
return null;
} 該文章在 2021/3/18 11:09:27 編輯過 |
關(guān)鍵字查詢
相關(guān)文章
正在查詢... |