How To Detect Transparency In PNG Images

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.

This entry was posted in Code, php and tagged , , , , . Bookmark the permalink.

One Response to How To Detect Transparency In PNG Images

  1. Ben says:

    You saved my day, thank you!
    If you know how to do the same with a Gif, please let me know 😉

Leave a Reply

Your email address will not be published. Required fields are marked *