欢迎光临

木子屋

标题: C#大图片压缩算法

作者: dnawo

日期: 2020-06-13 11:32 PM

分类: Win编程

内容: 复制内容到剪贴板 程序代码using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
public class ImageHelper
{
/// <summary>
/// GetEncoderInfo
/// </summary>
/// <param name="mimeType"></param>
/// <returns></returns>
private static ImageCodecInfo GetEncoderInfo(string mimeType)
{
ImageCodecInfo[] encoders = ImageCodecInfo.GetImageEncoders();
for (int i = 0; i < encoders.Length; ++i)
{
if (encoders[i].MimeType == mimeType)
return encoders[i];
}
return null;
}
/// <summary>
/// 图片压缩(降低质量以减小文件的大小)
/// </summary>
/// <param name="srcBitmap">传入的Bitmap对象</param>
/// <param name="destStream">压缩后的Stream对象</param>
/// <param name="level">压缩等级，0-100</param>
private static void Compress(Bitmap srcBitmap, Stream destStream, long level)
{
ImageCodecInfo myImageCodecInfo;
Encoder myEncoder;
EncoderParameter myEncoderParameter;
EncoderParameters myEncoderParameters;
// Get an ImageCodecInfo object that represents the JPEG codec.
myImageCodecInfo = GetEncoderInfo("image/jpeg");
// Create an Encoder object based on the GUID
// for the Quality parameter category.
myEncoder = Encoder.Quality;
// Create an EncoderParameters object.
// An EncoderParameters object has an array of EncoderParameter
// objects. In this case, there is only one
// EncoderParameter object in the array.
myEncoderParameters = new EncoderParameters(1);
// Save the bitmap as a JPEG file with 给定的 quality level
myEncoderParameter = new EncoderParameter(myEncoder, level);
myEncoderParameters.Param[0] = myEncoderParameter;
srcBitmap.Save(destStream, myImageCodecInfo, myEncoderParameters);
}
/// <summary>
/// 图片压缩(降低质量以减小文件的大小)
/// </summary>
/// <param name="srcFile"></param>
/// <param name="destFile"></param>
/// <param name="level"></param>
public static void Compress(string srcFile, string destFile, long level)
{
using (Image image = Image.FromFile(srcFile))
{
using (Bitmap bitmap = new Bitmap(image))
{
using (FileStream destStream = new FileStream(destFile, FileMode.Create))
{
Compress(bitmap, destStream, level);
}
}
}
}
}
调用示例:
复制内容到剪贴板 程序代码ImageHelper.Compress(@"C:\mzwu_com.jpg", @"C:\mzwu_net.jpg", 50L);

+ 查看当前日志评论 (0)

登录

────────────

木子屋

PJBlog3 v3.2.9.518 Inside.

Processed In 3.678 ms

返回

标题: C#大图片压缩算法

你没有权限发表评论

────────────

木子屋

PJBlog3 v3.2.9.518 Inside.

Processed In 3.678 ms

返回

暂无评论

返回

────────────

木子屋

PJBlog3 v3.2.9.518 Inside.

Processed In 3.771 ms

返回