PHP Resize图像给出黑色背景

标签 php png transparency image-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 图像时,它都会显示黑色背景。如何防止这种情况发生并保持透明背景?

最佳答案

在 imagecopyresampled 之前尝试这个,添加 alpha 混合,然后保存 alpa

imagealphablending($tci, false);
imagesavealpha($tci,true);
$transparent = imagecolorallocatealpha($tci, 255, 255, 255, 127);
imagefilledrectangle($tci, 0, 0, $w, $h, $transparent);

关于PHP Resize图像给出黑色背景,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9870854/

相关文章:

php - PHP/MYSQL 中的并发

php - 试图获取非对象的属性

css - 使输入字段透明

php - 如何通过ajax将回显响应(文本)放入警告框中?

php - Laravel/流明 PSR-4 : If I put classes into subdirectories do I have to use different namespaces then?

vb.net - 使用 .NET 将两个 PNG 图像合并为一张图像

css - PNG颜色问题

security - 内容未知的图片: Dangerous for a browser?

2d - 为什么透明像素在 WebGL 中不能正确混合

css - 有没有办法在网页开发中使用加法混色?