Save JPG in C# and Specify Compression Level

In C# it’s easy to open and edit images as a Bitmap object.

If you have an Image or a Bitmap object and you want to save it to disc you need to do a couple of steps first.

This guide will walk you through the steps required to save an Image or Bitmap to disc in the JPG format and allow you to specify the compression quality.

Image Decoders

Before saving an image to disc you need to specify an Image Decoder.

These are really easy to work with in C#. Start by Copy / Pasting this little helper function in to your program. It will make all image saves easier in the future.

private static ImageCodecInfo GetEncoder(ImageFormat format)
{
    var codecs = ImageCodecInfo.GetImageDecoders();
    foreach (var codec in codecs)
    {
        if (codec.FormatID == format.Guid)
        {
            return codec;
        }
    }
    return null;
}

Now you are ready to use that helper function to save your Bitmap to a file. In this example we’ll save it as a PNG file.

// We're going to save it as JPG, so create the EncoderParameters to do that
var encoderParameters = new EncoderParameters(1);
encoderParameters.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 1L);
bmp.Save(filePathAndName, GetEncoder(ImageFormat.Jpeg), encoderParameters);

How To Set the JPG Quality

The JPG qualtity is set to “1L” in the example above. You can use any value between 1 and 100 for the quality, just be sure to put an L after it.

  • 1L = Lowest Quality
  • 25L = Low Quality
  • 50L = Medium Quality
  • 75L = High Quality
  • 100L = Highest Quality

Save as PNG

If you want to save the image as a PNG we have a guide for that as well.

You may want to check out our other C# Image Processing Guides while you’re here.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.