How to PHP get bit depth of a given PNG image file?

独自空忆成欢 提交于 2019-12-01 03:34:06

问题


In PHP code, given an .png image path, I need to detect the bit-depth of that image. How can I do that?

I've tried to use getImageSize() and read the bits as below sample code but it always returns '8' for 24-bits/32-bits image.

Please help.

class Utils {
    //Ham de lay bits cua image
    public static function getBits($image) {
        $info = getImageSize($image);
        return $info['bits'];
    }
}

回答1:


PNG Images are not that supported for channels and bits by getimagesize(). However you can use a little function to obtain these values: get_png_imageinfo():

$file = 'Klee_-_Angelus_Novus.png';
$info = get_png_imageinfo($file);
print_r($info);

Gives you for the example picture:

Array
(
    [bit-depth] => 4
    [bits] => 4
    [channels] => 1
    [color] => 3
    [color-type] => Indexed-colour
    [compression] => 0
    [filter] => 0
    [height] => 185
    [interface] => 0
    [width] => 291
)

It returns the channels and bits as well like some would expect them from getimagesize() next to some more information specific to the PNG format. The meaning of the values next to bits and channels are documented in the PNG specification.




回答2:


From the getImageSize documentation:

bits is the number of bits for each color.

So 8 bits is correct, because if there's three channels (RGB) with eight bits each, you end up with a total of 24 bits. An additional alpha channel gives you another eight bits, totalling 32.

Try returning this:

return $info['channels'] * $info['bits'];

This doesn't work for every kind of image type, however. Read the documentation for how gifs and jpegs work.



来源:https://stackoverflow.com/questions/6355692/how-to-php-get-bit-depth-of-a-given-png-image-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!