How can PNG image transparency be preserved when using PHP code for Thumbnail Generation

StackOverflow https://stackoverflow.com/questions/23285595

  •  09-07-2023
  •  | 
  •  

Frage

I am trying to preserve the transparency of PNG or GIF images but with my code of generating thumbnails, I am getting black background of images instead of transparent.

Here is my code :

function create_image($source_image_path, $thumbnail_image_path, $real_width, $real_height,$source_image_height,$source_image_width)
{
   list($source_image_width, $source_image_height, $source_image_type) =     getimagesize($source_image_path);
$source_gd_image = false;
switch ($source_image_type) {
    case IMAGETYPE_GIF:
        $source_gd_image = imagecreatefromgif($source_image_path);
        break;
    case IMAGETYPE_JPEG:
        $source_gd_image = imagecreatefromjpeg($source_image_path);
        break;
    case IMAGETYPE_PNG:
        $source_gd_image = imagecreatefrompng($source_image_path);
        break;
}
if ($source_gd_image === false) {
    return false;
}


$thumbnail_gd_image = imagecreatetruecolor($real_width, $real_height);
if(($source_image_type == 1) || ($source_image_type==3)){
    imagealphablending($thumbnail_gd_image, false);
    imagesavealpha($thumbnail_gd_image, true);
    $transparent = imagecolorallocatealpha($thumbnail_gd_image, 255, 255, 255, 127);
    imagefilledrectangle($thumbnail_gd_image, 0, 0, $real_width, $real_height, $transparent);
}

imagecopyresampled($thumbnail_gd_image, $source_gd_image, 0, 0, 0, 0, $real_width, $real_height, $source_image_width, $source_image_height);
imagejpeg($thumbnail_gd_image, $thumbnail_image_path, 100);
imagedestroy($source_gd_image);
imagedestroy($thumbnail_gd_image);
return true;
}

With the above code I'm getting black background of image.

I tried using imagecolorallocate($thumbnail_gd_image, 255, 255, 255);. But with this imagefilledrectangle() give me white background.

Can anyone help me to get the transparent background for PNG or GIF images?

War es hilfreich?

Lösung

I think your problem is in the line below:

$thumbnail_gd_image = imagecreatetruecolor($real_width, $real_height);

According to http://www.php.net/manual/en/function.imagecreatetruecolor.php

imagecreatetruecolor() returns an image identifier representing a black image of the specified size.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top