PHP调整图像大小为黑色背景


PHP Resize image gives black background

我正在使用以下代码调整大小:

  <?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图片,结果都是黑色背景。如何防止这种情况发生并保持透明背景?

在imagecopy重新采样之前尝试此操作,添加alpha混合,然后保存alpha

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

尝试使用imagecolortransparent:设置透明颜色

http://il.php.net/manual/en/function.imagecolortransparent.php

试试这个,让你的重定尺寸函数

<?php
    $file_name =testimg.jpg // your file name
    extension= explode(".", strtolower($file_name));//get ext of your image
    if($extension[1]=="jpg" || $extension[1]=="jpeg" )
    {
        $src = imagecreatefromjpeg($filename); // Check ext and set src 
    }
    else if($extension[2]=="png")
    {
        $src = imagecreatefrompng($filename); // Check ext and set src 
    }
    else 
    {
        $src = imagecreatefromgif($filename); // Check ext and set src 
    } 
    list($width,$height)=getimagesize($filename);
    $newwidth=round($width/10);   //resized image width
    $newheight=round($height/10);  //resized image height
    $tmp=imagecreatetruecolor($newwidth,$newheight);
    imagecopyresampled($tmp,$src,0,0,0,0,$newwidth,$newheight,$width,$height);
    $resizedfile = "resizeduploads/". $name;
    if($extension[1]=="jpg" || $extension[1]=="jpeg" )
    {
        imagejpeg($tmp,$resizedfile);
    }
    else if($extension[1]=="png")
    {
        imagepng($tmp,$resizedfile);
    }
    else 
    {
        imagegif($tmp,$resizedfile);
    }
    imagedestroy($src);
    imagedestroy($tmp);