Fuad Hashimov
Fuad Hashimov

Reputation: 41

Reduce the size of the PNG image

I want to compress PNG image

I am using below code: (Below code is working fine for jpeg,jpg) but not for png.

        var qualityParam = new EncoderParameter(Encoder.Quality,80);
        // PNG image codec 
        var pngCodec = GetEncoderInfo(ImageFormat.Png);
        var encoderParams = new EncoderParameters(1) { Param = { [0] = qualityParam } };

        rigImage.Save(imagePath, pngCodec, encoderParams);

        private static ImageCodecInfo GetEncoderInfo(ImageFormat format)
        {
          // Get image codecs for all image formats 
          var codecs = ImageCodecInfo.GetImageEncoders();

          // Find the correct image codec 
          return codecs.FirstOrDefault(t => t.FormatID == format.Guid);
         }

Upvotes: 2

Views: 1389

Answers (2)

yv989c
yv989c

Reputation: 1543

As @Masklinn said, PNG is a lossless format, and I think the BCL in .NET does not have an API that can help you to "optimize" the size of the PNG.

Instead, you could use the libimagequant library; you can get more information about this library here, and how to use it from .NET here.

This is the same library used by PNGoo, I have got really impressive results with it when optimizing PNGs in my projects.

Also, if you are planning to use the library in a commercial project, keep in mind the license terms, as indicated at https://pngquant.org/lib/.

Upvotes: 0

Masklinn
Masklinn

Reputation: 42282

JPEG "works fine" because it can always discard more information.

PNG is a lossless image compression format, so getting better compression is trickier and there's a pretty high "low mark". There are tools like PNGOut or OxiPNG which exist solely to optimise PNG images, but most strategies are very computationally expensive so your average image processing library just doesn't bother:

  • you can discard irrelevant metadata chunk
  • you can enumerate and try out various filtering strategies, this amounts to compressing the image dozens of time with slightly different tuning and checking out the best
  • you can switch out the DEFLATE implementation from the default (usually the stdlib or system's standard) to something better but much more expensive like zopfli
  • finally — and this one absolutely requires human eyeballs — you can try and switch to palletised

As noted above, most image libraries simply won't bother with that, they'll use a builtin zlib/deflate and some default filter, it can takes minutes to make a PNG go through an entire optimisation pipeline, and there's a chance the gain will be non-existent.

Upvotes: 2

Related Questions