Search code examples
phppngtransparency

PNG with transparent background = thumbnail with black backgroud


Can you support me? I have the following script in order to create a thumbnail, works fine! BUT, when I upload a PNG file with transparent background, for some reason the background change to black.

<?php
// Function for resizing jpg, gif, or png image files
function ak_img_resize($target, $newcopy, $w, $h, $ext) {
    list($w_orig, $h_orig) = getimagesize($target);
    $scale_ratio = $w_orig / $h_orig;
    if (($w / $h) > $scale_ratio) {
           $w = $h * $scale_ratio;
    } else {
           $h = $w / $scale_ratio;
    }
    $img = "";
    $ext = strtolower($ext);
    if ($ext == "gif"){ 
      $img = imagecreatefromgif($target);
    } else if($ext =="png"){ 
      $img = imagecreatefrompng($target);
    } else { 
      $img = imagecreatefromjpeg($target);
    }
    $tci = imagecreatetruecolor($w, $h);
    // imagecopyresampled(dst_img, src_img, dst_x, dst_y, src_x, src_y, dst_w, dst_h, src_w, src_h)
    imagecopyresampled($tci, $img, 0, 0, 0, 0, $w, $h, $w_orig, $h_orig);
    imagejpeg($tci, $newcopy, 80);
}
?>

If the background of the PNG it's transparent, I need the thumbnail transparent also, can you please support me? Any help will be GREAT!

Thanks in advance


Solution

  • Using:

    $tci = imagecreate($w, $h);
    

    Instead:

    $tci = imagecreatetruecolor($w, $h);
    

    My issue is now solved :)