Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Resize image gives black background

I am using this code for resizing:

  <?php
// Function for resizing any 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);
}
?>

But everytime I upload a transparant png image it turns out with a black background. How do I prevent this from happening and maintain the transparant background?

like image 645
DaViDa7 Avatar asked Mar 26 '12 10:03

DaViDa7


1 Answers

try this before imagecopyresampled, added alpha blending, and then save alpa

imagealphablending($tci, false);
imagesavealpha($tci,true);
$transparent = imagecolorallocatealpha($tci, 255, 255, 255, 127);
imagefilledrectangle($tci, 0, 0, $w, $h, $transparent);
like image 59
Muhammad Cahya Avatar answered Oct 20 '22 08:10

Muhammad Cahya