PHP调整大小图像给出黑色背景 [英] PHP Resize image gives black background

查看:233
本文介绍了PHP调整大小图像给出黑色背景的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用此代码来调整大小:

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);
}
?>

但是,每次我上传透明的png图像时,结果都是黑色背景.如何防止这种情况发生并保持透明的背景?

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?

推荐答案

在重新进行图像复制采样之前尝试此操作,添加alpha混合,然后保存Alpa

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);

这篇关于PHP调整大小图像给出黑色背景的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆