2010-11-12 243 views
16

我的情景:缩小图像尺寸C#

我想期待缩小图像尺寸(10 KB到3 KB)

+1

看看http://stackoverflow.com/questions/2933918/reduce-image-size-in-bytes-without-resize-and-quality-lose-in-c – Pratik 2010-11-12 05:37:36

回答

41

好吧,你想要什么可以这样:

// 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); 

参考this post on VB Forumsthis blog post

+1

这是一个完美的解决方案,以70%的质量将我的图像尺寸从5.5MB减少到1.7MB。 – 2017-11-17 18:45:13

0

好,图像不能神奇地变小,所以你将不得不压缩它或将其缩小。

+4

是的,可以。由c#的魔力!在保持规模的同时降低质量。不需要压缩。 – hofnarwillie 2013-08-23 11:02:56

2

Use GDI

请看看这个样本。使用GDI +调整照片大小。希望它可以帮助你。