Compress images with jpeg codec in C#

Today I’ll show you how to compress your images with help of the JPEG-codec in C#. You will be able to choose the grade of compression. So it’s your choice, if the function should produce smaller filesize or better quality of images.

private void CompressImage(Image sourceImage, int imageQuality, string savePath)
{
    try
    {
        //Create an ImageCodecInfo-object for the codec information
        ImageCodecInfo jpegCodec = null;

        //Set quality factor for compression
        EncoderParameter imageQualitysParameter = new EncoderParameter(
                    System.Drawing.Imaging.Encoder.Quality, imageQuality);

        //List all avaible codecs (system wide)
        ImageCodecInfo[] alleCodecs = ImageCodecInfo.GetImageEncoders();

        EncoderParameters codecParameter = new EncoderParameters(1);
        codecParameter.Param[0] = imageQualitysParameter;

        //Find and choose JPEG codec
        for (int i = 0; i < alleCodecs.Length; i++)
        {
             if (alleCodecs[i].MimeType == "image/jpeg")
             {
                    jpegCodec = alleCodecs[i];
                    break;
             }
        }

        //Save compressed image
        sourceImage.Save(savePath, jpegCodec, codecParameter);
   }
   catch (Exception e)
   {
        throw e;
   }
}

Call the function as follows:

CompressImage(Image.FromFile(Application.StartupPath + "\mySourcePicture.jpg"),
                             30, Application.StartupPath + "\myCompressedPicture.jpg");

2 Comments

  1. Maheshsays:

    Thank you for the post. Really worked great.

  2. shashanksays:

    Thanks for the article.It’s working fine for me.

Leave a Reply to shashank Cancel reply

Please be polite. We appreciate that. Your email address will not be published and required fields are marked