phppngbit-depth

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


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'];
    }
}

Solution

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