JPEG 图像不能有透明背景。
相反,您可以根据以下内容制作图像imagesavealpha()
:
$targ_w = $targ_h = 150;
$newImage = imagecreatetruecolor($targ_w, $targ_h);
imagealphablending($newImage, false);
imagesavealpha($newImage, true);
$transparent = imagecolorallocatealpha($newImage, 255, 255, 255, 127);
imagefilledrectangle($newImage, 0, 0, $targ_w, $targ_h, $transparent);
$src = $_POST['n'];
$img_r = imagecreatefromstring(file_get_contents($src));
$img_r_size = getimagesize($src);
$width_r = $img_r_size[0];
$height_r = $img_r_size[1];
if($width_r > $height_r){
$width_ratio = $targ_w / $width_r;
$new_width = $targ_w;
$new_height = $height_r * $width_ratio;
} else {
$height_ratio = $targ_h / $height_r;
$new_width = $width_r * $height_ratio;
$new_height = $targ_h;
}
imagecopyresampled($newImage, $img_r, 0, 0, 0, 0, $new_width, $new_height, $width_r, $height_r);
$new_src = str_replace('/temp','',$_POST['n']);
imagepng($newImage, $new_src);
它将从 PNG 和 GIF 制作一个 PNG(具有透明背景,并调整为 150x150。
这只是一个示例,因为它不限制比例。