Detect if a WEBP image is transparent, in PHP

1

I'm trying to check if a webp image is transparent in PHP or not. Is it possible?

Best would be in pure php.

Update:

After researching... i wrote this php function. Works great.

webp_info() detect transparent and animation in a webp image.

function webp_info($f) {
    // https://github.com/webmproject/libwebp/blob/master/src/dec/webp_dec.c
    // https://developers.google.com/speed/webp/docs/riff_container
    // https://developers.google.com/speed/webp/docs/webp_lossless_bitstream_specification
    // https://stackoverflow.com/questions/61221874/detect-if-a-webp-image-is-transparent-in-php

    $fp = fopen($f, 'rb');
    if (!$fp) {
        throw new Exception("webp_info(): fopen($f): Failed");
    }
    $buf = fread($fp, 25);
    fclose($fp);

    switch (true) {
        case!is_string($buf):
        case strlen($buf) < 25:
        case substr($buf, 0, 4) != 'RIFF':
        case substr($buf, 8, 4) != 'WEBP':
        case substr($buf, 12, 3) != 'VP8':
            throw new Exception("webp_info(): not a valid webp image");

        case $buf[15] == ' ':
            // Simple File Format (Lossy)
            return array(
                'type'            => 'VP8',
                'has-animation'   => false,
                'has-transparent' => false,
            );


        case $buf[15] == 'L':
            // Simple File Format (Lossless)
            return array(
                'type'            => 'VP8L',
                'has-animation'   => false,
                'has-transparent' => (bool) (!!(ord($buf[24]) & 0x00000010)),
            );
        case $buf[15] == 'X':
            // Extended File Format
            return array(
                'type'            => 'VP8X',
                'has-animation'   => (bool) (!!(ord($buf[20]) & 0x00000002)),
                'has-transparent' => (bool) (!!(ord($buf[20]) & 0x00000010)),
            );

        default:
            throw new Exception("webp_info(): could not detect webp type");
    }
}

var_export(webp_info('image.webp'));
php
asked on Stack Overflow Apr 15, 2020 by Hans-Jürgen Petrich • edited Apr 16, 2020 by Hans-Jürgen Petrich

0 Answers

Nobody has answered this question yet.


User contributions licensed under CC BY-SA 3.0