简体   繁体   中英

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);
         }

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.

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/ .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM