Why are PNG images turning black with `imagecreatefrompng()` in PHP?

Susan Sarandon
Release: 2024-11-03 14:46:30
Original
440 people have browsed it

Why are PNG images turning black with `imagecreatefrompng()` in PHP?

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!