Create thumbnail and reduce image size

leora picture leora · Mar 26, 2009 · Viewed 15.2k times · Source

I have very large images (jpg) and i want to write a csharp program to loop through the files and reduce the size of each image by 75%.

I tried this:

Image thumbNail = image.GetThumbnailImage(800, 600, null, new IntPtr());

but the file size is still very large.

Is there anyway to create thumbnails and have the filesize be much smaller?

Answer

David Brown picture David Brown · Mar 26, 2009
private void CompressAndSaveImage(Image img, string fileName, 
        long quality) {
    EncoderParameters parameters = new EncoderParameters(1);
    parameters.Param[0] = new EncoderParameter(Encoder.Quality, quality);
    img.Save(fileName, GetCodecInfo("image/jpeg"), parameters);
}

private static ImageCodecInfo GetCodecInfo(string mimeType) {
    foreach (ImageCodecInfo encoder in ImageCodecInfo.GetImageEncoders())
        if (encoder.MimeType == mimeType)
            return encoder;
    throw new ArgumentOutOfRangeException(
        string.Format("'{0}' not supported", mimeType));
}

Usage:

Image myImg = Image.FromFile(@"C:\Test.jpg");
CompressAndSaveImage(myImg, @"C:\Test2.jpg", 10);

That will compress Test.jpg with a quality of 10 and save it as Test2.jpg.

EDIT: Might be better as an extension method:

private static void SaveCompressed(this Image img, string fileName, 
        long quality) {
    EncoderParameters parameters = new EncoderParameters(1);
    parameters.Param[0] = new EncoderParameter(Encoder.Quality, quality);
    img.Save(fileName, GetCodecInfo("image/jpeg"), parameters);
}

Usage:

Image myImg = Image.FromFile(@"C:\Test.jpg");
myImg.SaveCompressed(@"C:\Test2.jpg", 10);