How to check PNG for grayscale / alpha type?

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

I was wondering if anyone knows of a color type testing method to notify the user of incompatibilities?

Example:

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

the code:

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

Greetings

Aron

+7
php png gd
source share
3 answers

The color type of the PNG image is stored at byte offset 25 in the file (counting from 0). Therefore, if you can get the actual bytes of the PNG file, just look at byte 25 (I don't do PHP, so I don't know how to do this):

  • 0 - shades of gray
  • 2 - RGB
  • 3 - RGB with a palette
  • 4 - shades of gray + alpha
  • 6 - RGB + alpha

The previous byte (offset 24) gives the number of bits per channel. See the PNG specification for details.

In a small twist, a PNG file may have β€œ1-bit alpha” (for example, GIF), having a tRNS fragment (when it has a color type of 0 2 or 3).

+8
source share

I landed here today to find a way to tell (via php) if the particular .png image is alpha png one -
David Jones answer points in the right direction, very easy to implement in php:

file_get_contents to download only this 25-byte (here it is, really!) and
ord () to get its ASCII value to check it (against "6" in my case)

 if(ord(file_get_contents($alpha_png_candidate, NULL, NULL, 25, 1)) == 6) { is_alpha_png_so_do_something(); } 

In fact, I need this to ensure backward compatibility with ie6 in cms-user-generated-pages, to replace all alpha-png <img> with the built-in <spans> block - then the alpha-png file will be used as a variable for ms-patented CSS Property Filter

 .alpha_png_span{ filter: progid:DXImageTransform.Microsoft.AlphaImageLoader( src='$alpha_png_candidate', sizingMethod='crop') } 

... and everything works, so thanks!

paolo

+4
source share

see this answer

Another useful note for those using ImageCreateFromPng: PHP and GD do not recognize grayscale / alpha images.

So, if you use grayscale images with transparency from 0% to 100%, save the image as RGB.

At least this is true for PHP versions 4.4.2-1 and 5.1.2-1 with images made using GIMP 2.2.8.

url: http://php.net/manual/en/function.imagecreatefrompng.php

0
source share