PNG Images Turned Black with imagecreatefrompng()
Problem:
Users have encountered an issue where PHP's imagecreatefrompng() function is converting transparent areas in PNG images to solid black when creating thumbnails using the GD library.
PHP Thumbnail Creation Code:
<code class="php">function cropImage($nw, $nh, $source, $stype, $dest) { // ... switch($stype) { case 'png': $simg = imagecreatefrompng($source); break; // ... } // ... }</code>
Solution:
To resolve this issue, additional steps before imagecreatetruecolor() are required, specifically for PNG and GIF images. These steps involve:
<code class="php">// Before imagecreatetruecolor() $dimg = imagecreatetruecolor($width_new, $height_new); // png ?: gif // Additional steps for PNG and GIF switch ($stype) { case 'gif': case 'png': // Black color $background = imagecolorallocate($dimg , 0, 0, 0); // Remove black from placeholder imagecolortransparent($dimg, $background); // Turn off alpha blending imagealphablending($dimg, false); // Turn on alpha channel saving imagesavealpha($dimg, true); break; default: break; }</code>
By implementing these additional steps, transparent areas in PNG images will be preserved when creating thumbnails using imagecreatefrompng().
The above is the detailed content of Why are PNG images turning black with `imagecreatefrompng()` in PHP?. For more information, please follow other related articles on the PHP Chinese website!