C# 大图片压缩算法,减少图片体积
当前位置:点晴教程→知识管理交流
→『 技术文档交流 』
声明: 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;
}
/// ///
/// 圖片流
/// 壓縮質量0-100之間 數值越大質量越高
///
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 编辑过 |
关键字查询
相关文章
正在查询... |