Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create thumbnail and reduce image size

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?

like image 321
leora Avatar asked Mar 26 '09 00:03

leora


1 Answers

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);
like image 117
David Brown Avatar answered Sep 23 '22 07:09

David Brown