I recently came across a problem where I needed to check for transparency in PNG images using PHP. After some digging with the help of my partner Josh, we came up with the following php function:
function png_has_transparency( $filename ) {
if ( strlen( $filename ) == 0 || !file_exists( $filename ) )
return false;
if ( ord ( file_get_contents( $filename, false, null, 25, 1 ) ) & 4 )
return true;
$contents = file_get_contents( $filename );
if ( stripos( $contents, 'PLTE' ) !== false && stripos( $contents, 'tRNS' ) !== false )
return true;
return false;
}
The first file check:
ord ( file_get_contents( $filename, false, null, 25, 1 ) ) & 4
will check for transparency in a 32-bit PNG. The second check
stripos( $contents, 'PLTE' ) !== false && stripos( $contents, 'tRNS' ) !== false
works to detect transparency in 8-bit PNG’s. Big thanks to this article which expains how these parts work in a bit more detail.
Depending on how likely you are to have transparency (or 32-bit png’s) you might want to modify this function to only do one file access, but the advantage here is that if it is a 32-bit png with transparency we only need to read in part of the file. This was faster in my early testing of a sample of our images, but your results may vary.
Hope this helps someone else out there.
One Response to How To Detect Transparency In PNG Images