In PHP, imagepng() accepts a filter parameter. How

2020-07-02 08:31发布

问题:

How do these filters affect the output of imagepng() in PHP?

  • PNG_NO_FILTER
  • PNG_FILTER_NONE
  • PNG_FILTER_SUB
  • PNG_FILTER_UP
  • PNG_FILTER_AVG
  • PNG_FILTER_PAETH
  • PNG_ALL_FILTERS

The documentation simply says, "A special PNG filter, used by the imagepng() function" for each of them.

It seems that using PNG_NO_FILTER will reduce the filesize of the output, but other than that, I am unsure as to how it is affected. Any insight would be really appreciated.

回答1:

According to the PNG Specifications at http://www.w3.org/TR/PNG-Filters.html The purpose of these filters is to prepare the image data for optimum compression.

With the None filter, the scanline is transmitted unmodified; it is only necessary to insert a filter type byte before the data.

The Sub filter transmits the difference between each byte and the value of the corresponding byte of the prior pixel.

The Up filter is just like the Sub filter except that the pixel immediately above the current pixel, rather than just to its left, is used as the predictor.

The Average filter uses the average of the two neighbouring pixels (left and above) to predict the value of a pixel.

The Paeth filter computes a simple linear function of the three neighbouring pixels (left, above, upper left), then chooses as predictor the neighboring pixel closest to the computed value. This technique is due to Alan W. Paeth [PAETH].*



回答2:

From the imagepng() man page linked to the question,

filters

Allows reducing the PNG file size. It is a bitmask field which may be set to any combination of the PNG_FILTER_XXX constants. PNG_NO_FILTER > or PNG_ALL_FILTERS may also be used to respectively disable or activate all filters.

So, to let libpng try the none, sub, and up filters, you'd use

PNG_FILTER_NONE|PNG_FILTER_SUB|PNG_FILTER_UP

PNG_ALL_FILTERS is just shorthand for

PNG_FILTER_NONE|PNG_FILTER_SUB|PNG_FILTER_UP|PNG_FILTER_AVG|PNG_FILTER_PAETH

As for which filter to use, it depends upon the image. Images with 256 or fewer colors generally compress better with PNG_NO_FILTER, while images with many colors (such as photos) generally compress better with PNG_FILTER_SUB or PNG_ALL_FILTERS. Applications like "optipng" or my "pngcrush" try to optimize the filter selection. If you're going to use one of those third-party applications for final optimization, you should just use PNG_NO_FILTERS for your working copies, for speed.



回答3:

Those are all different algorithms the PNG encoder can use to determine pixel values. Don't know a whole lot, but this page seems to go into some depth: http://www.w3.org/TR/PNG-Filters.html