在C#中壓縮圖片并保持質量的方法可以使用以下代碼示例:
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
public static class ImageHelper
{
public static void CompressImage(string sourcePath, string destinationPath, long quality)
{
using (Bitmap bmp = new Bitmap(sourcePath))
{
ImageCodecInfo jpgEncoder = GetEncoder(ImageFormat.Jpeg);
Encoder encoder = Encoder.Quality;
EncoderParameter encoderParameter = new EncoderParameter(encoder, quality);
EncoderParameters encoderParameters = new EncoderParameters(1);
encoderParameters.Param[0] = encoderParameter;
bmp.Save(destinationPath, jpgEncoder, encoderParameters);
}
}
private static ImageCodecInfo GetEncoder(ImageFormat format)
{
ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();
foreach (ImageCodecInfo codec in codecs)
{
if (codec.FormatID == format.Guid)
{
return codec;
}
}
return null;
}
}
// 使用示例
string sourcePath = @"C:\input.jpg";
string destinationPath = @"C:\output.jpg";
long quality = 50; // 壓縮質量,范圍從0到100
ImageHelper.CompressImage(sourcePath, destinationPath, quality);
在上面的示例中,首先通過Bitmap
類加載圖片,然后獲取JPEG編碼器并設置壓縮質量參數。最后保存壓縮后的圖片到指定路徑。您可以調整quality
參數來控制壓縮質量,值范圍從0到100,0表示最低質量,100表示最高質量。