我正在使用此代码进行大小调整:
<?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图像时都会看到黑色背景。如何防止这种情况发生并保持透明背景?
答案 0 :(得分:5)
在imagecopyresampled之前尝试此操作,添加alpha混合,然后保存alpa
imagealphablending($tci, false);
imagesavealpha($tci,true);
$transparent = imagecolorallocatealpha($tci, 255, 255, 255, 127);
imagefilledrectangle($tci, 0, 0, $w, $h, $transparent);
答案 1 :(得分:0)
尝试使用imagecolortransparent设置透明色:
http://il.php.net/manual/en/function.imagecolortransparent.php
答案 2 :(得分:0)
尝试此操作,以制作重新调整大小的功能
<?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);