How to check if an image has transparency using GD?

后端 未结 8 1376
耶瑟儿~
耶瑟儿~ 2020-12-09 18:48

How do I check if an image has transparent pixels with php\'s GD library?

8条回答
  •  一生所求
    2020-12-09 19:23

    I know this is an old thread, but in my opinion it needs improvement since walking through a huge png by checking all pixels only to find out it is not transparent is a waste of time. So after some googleing I found Jon Fox's Blog and I improved his code with the help of the W3C PNG Specification further to be reliable, fast and have a minimum on memory imprint:

    function IsTransparentPng($File){
        //32-bit pngs
        //4 checks for greyscale + alpha and RGB + alpha
        if ((ord(file_get_contents($File, false, null, 25, 1)) & 4)>0){
            return true;
        }
        //8 bit pngs
        $fd=fopen($File, 'r');
        $continue=true;
        $plte=false;
        $trns=false;
        $idat=false;
        while($continue===true){
            $continue=false;
            $line=fread($fd, 1024);
            if ($plte===false){
                $plte=(stripos($line, 'PLTE')!==false);
            }
            if ($trns===false){
                $trns=(stripos($line, 'tRNS')!==false);
            }
            if ($idat===false){
                $idat=(stripos($line, 'IDAT')!==false);
            }
            if ($idat===false and !($plte===true and $trns===true)){
                $continue=true;
            }
        }
        fclose($fd);
        return ($plte===true and $trns===true);
    }
    

提交回复
热议问题