Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check a PNG for grayscale/alpha color type?

Tags:

php

png

gd

PHP and GD seem to have trouble creating images from PNGs of type greyscale with alpha when using imagecreatefrompng(). The results are incredibly distorted.

I was wondering if anyone knew of a way to test for the colour type in order to notify the user of the incompatibility?

Example:

Original Image: http://dl.dropbox.com/u/246391/Robin.png
Resulting Image: http://dl.dropbox.com/u/246391/Robin_result.png

Code:

<?php

$resource = imagecreatefrompng('./Robin.png');
header('Content-type: image/png');
imagepng($resource);
imagedestroy($resource);

Cheers,

Aron

like image 761
ac94 Avatar asked Jan 13 '10 15:01

ac94


People also ask

How can you tell if a PNG is alpha channel?

To check if the image has an alpha channel, go to the channel dialog and verify that an entry for “Alpha” exists, besides Red, Green and Blue. If this is not the case, add a new alpha channel from the layers menu; Layer+Transparency → Add Alpha Channel.

Does PNG contain alpha?

Alpha channel. An alpha channel, representing transparency information on a per-pixel basis, can be included in grayscale and truecolor PNG images. An alpha value of zero represents full transparency, and a value of (2^bitdepth)-1 represents a fully opaque pixel.

Can PNG be grayscale?

PNG supports two kinds of transparency with grayscale and RGB images.

Is PNG alpha transparency?

PNG files support transparency, but JPGs do not. If you save a PNG image as a JPG file, the JPG format doesn't know what to do with the alpha channel. That's why all the transparency turns into an opaque white background instead.


1 Answers

The colour type of a PNG image is stored at byte offset 25 in the file (counting from 0). So if you can get hold of the actual bytes of the PNG file, simply look at byte 25 (I don't do PHP, so I don't know how to do that):

  • 0 - greyscale
  • 2 - RGB
  • 3 - RGB with palette
  • 4 - greyscale + alpha
  • 6 - RGB + alpha

The preceding byte (offset 24) gives the number of bits per channel. See the PNG spec for more details.

In a slight twist a PNG file may have "1-bit alpha" (like GIFs) by having a tRNS chunk (when it is colour type 0 2 or 3).

like image 113
David Jones Avatar answered Sep 28 '22 11:09

David Jones