How to Save a PNG File in C#

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 PNG 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 PNG
var encoderParameters = new EncoderParameters(1);
encoderParameters.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 1L);
bmp.Save(filePathAndName, GetEncoder(ImageFormat.Png), encoderParameters);

How To Set the PNG Quality

Unfortunately in .net and in C# you can not specify the PNG encoding level. The "Quality" parameter above is actually ignored.

Save as JPG

If you want to save the image as a JPG and specify the compression level 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

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

More from Efundies