4

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'];
    }
}
Nam G VU
  • 33,193
  • 69
  • 233
  • 372
  • 3
    my guess it means 8bits per channel. – Rufinus Jun 15 '11 at 09:42
  • 1
    @cweiske I'm sorry about my 68% rate - I've got lot's of questions remained unanswerred. Can you help? – Nam G VU Jun 15 '11 at 18:21
  • @hakre I always pick the most correct answer to be the accepted one. I just need you understand that 32% of my questions remain incorrect answered and I leave them unaccepted - NOT because I am a careless man :). Thank you for your remind on that anyway. – Nam G VU Jun 26 '11 at 01:57

2 Answers2

7

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.

HertzaHaeon
  • 601
  • 5
  • 7
  • 2
    Yeah. It doesn't work for PNG image. So PHP cannot deal with PNG bit-depth issues, can it? I really feel weird since PHP is growing rapidly – Nam G VU Jun 15 '11 at 18:23
7

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.

hakre
  • 193,403
  • 52
  • 435
  • 836
  • 1
    `get_png_imageinfo` seems broken with PHP 5.5 (works perfect with 5.4). It fails at the `array_shift` comparison. Potentially something new within `unpack()`. – Jeff Jul 07 '14 at 19:13
  • 1
    With php 5.5+, replacing `A8sig` with `a8sig` (or equivalently, `Z8sig`) on line 22 does it. According to http://php.net/manual/en/function.pack.php, `a` and `Z` refers to a NUL-padded string, while `A` refers to a SPACE-padded string. – danmichaelo May 11 '18 at 14:38