减小图像大小 C#

28

我的情境:

我希望能够减小图像的大小(从10 KB 减少至 3 KB)。


1
请查看以下网址:http://stackoverflow.com/questions/2933918/reduce-image-size-in-bytes-without-resize-and-quality-lose-in-c - Pratik
3个回答

78

好的,你想要的可能是这样的:

// Make sure to include this at the top
using System.Drawing.Imaging;

 

/// <summary> 
/// Saves an image as a jpeg image, with the given quality 
/// </summary> 
/// <param name="path"> Path to which the image would be saved. </param> 
/// <param name="quality"> An integer from 0 to 100, with 100 being the highest quality. </param> 
public static void SaveJpeg (string path, Image img, int quality) 
{ 
    if (quality<0  ||  quality>100) 
        throw new ArgumentOutOfRangeException("quality must be between 0 and 100."); 

     // Encoder parameter for image quality 
     EncoderParameter qualityParam = new EncoderParameter(Encoder.Quality, quality); 
     // JPEG image codec 
     ImageCodecInfo jpegCodec = GetEncoderInfo("image/jpeg"); 
     EncoderParameters encoderParams = new EncoderParameters(1); 
     encoderParams.Param[0] = qualityParam; 
     img.Save(path, jpegCodec, encoderParams); 
} 

/// <summary> 
/// Returns the image codec with the given mime type 
/// </summary> 
private static ImageCodecInfo GetEncoderInfo(string mimeType) 
{ 
     // Get image codecs for all image formats 
     ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders(); 

     // Find the correct image codec 
     for(int i=0; i<codecs.Length; i++) 
         if(codecs[i].MimeType == mimeType) 
             return codecs[i]; 

     return null; 
 } 

然后你可以这样做:

// First load the image somehow
Image myImage = Image.FromFile(pathToImage, true); 
// Save the image with a quality of 50% 
SaveJpeg (destImagePath, myImage, 50); 

请参考VB论坛上的这篇文章这篇博客文章


1
这是一个完美的解决方案,将我的图像大小从5.5MB减小到1.7MB,并且保持了70%的质量。 - Mohammad Mahroz
2
我在上面的代码中遇到了“参数无效”的问题,我不得不使用长整型值来代替上面的整型值以解决这个问题。 - David Lindon
杰出的努力... - Ragesh S

2

使用 GDI+

请参考这个示例。使用 GDI+ 调整照片大小。希望能对您有所帮助。


-12

图片不可能神奇地变小,所以你要么压缩它,要么将其缩小。


8
可以的。通过 C# 的魔力,可以在保持比例的同时降低质量,无需压缩。 - hofnarwillie

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接