How to Save a PNG File in C#

By FoxLearn 12/26/2024 9:01:23 AM   11
In C#, it's simple to work with images by manipulating them as Bitmap objects.

This article will guide you through the steps to save an Image or Bitmap to disk in the PNG format, while allowing you to control the compression quality.

Image Decoders

Before saving any image, you need to specify an image encoder. In C#, ImageCodecInfo objects handle image encoders and decoders for various formats. These decoders allow the system to convert the image into the desired format (e.g., PNG, JPEG, etc.) when saving it to disk.

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 that you have a way to retrieve the image encoder, you can save an image to disk using the Save() method. This method allows you to specify the format, along with various encoder parameters like compression quality.

// Assuming you already have a Bitmap object called 'bmp'
var filePathAndName = @"C:\path\to\your\image.png";

// Create encoder parameters with quality set to 90L (lowest quality)
var encoderParameters = new EncoderParameters(1);
encoderParameters.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 90L);

// Save the image to disk as a PNG with specified quality
bmp.Save(filePathAndName, GetEncoder(ImageFormat.Png), encoderParameters);

In this example:

  • We first specify the path and name of the file where we want to save the image (filePathAndName).
  • The EncoderParameters object is created with one parameter that sets the quality level to 90L. The quality value can range from 0 (lowest quality) to 100 (highest quality).
  • We then call bmp.Save() to save the Bitmap to the specified path using the PNG format, with the desired encoder settings.

In C#, saving images as a Bitmap to disk is straightforward once you’ve got the right image encoder in place. By using the helper function GetEncoder(), you can easily retrieve the correct encoder for the image format you need (like PNG or JPEG).