Save JPG in C# and Specify Compression Level

Thumbnail image of Jason Bauer
Jason Bauer
December 24, 2015 (Last Updated: ) | Reading Time: 1 minutes

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.

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.



googlebot - 2021-02-24 15:04:11


Fix your code, it's embarrassing.


Jason Bauer - 2021-02-26 17:07:02

Got it. It was the "Crayon Syntax Highlighter". Apparently, it's not compatible with the newest version of WP. Found the fix here:

Leave a reply

Thank you! Your comment has been successfully submitted. It will be approved as soon as possible.

More from Efundies