我正在尝试使用以下代码调整PNG透明图像的大小:
$src=ImageCreateFrompng($uploadedfile);
$background=imagecolorallocate($src,0,0,0);
imagecolortransparent($src,$background);
imagealphablending($src,false);
imagesavealpha($src,true);
$dst=ImageCreateTrueColor($tn_width,$tn_height);
imagecopyresampled($dst,$src,0,0,0,0,$tn_width,$tn_height,$width,$height);
Imagepng($dst,$dstfile);
我使用了imagealphablending($src,false)
和imagesavealpha($src,true)
但它仍然上传了黑色背景而不是透明背景的图像。
问题出在哪里?
这是因为您将透明图像复制到黑色图像上。您的 aplhablending 错误设置仅适用于原始图像,因此当您在新图像上复制时,aplha 混合处于打开状态。
您的代码只需要一点点改进:
$transparent = imagecolorallocatealpha($dst, 0,0,0,127); //Transparent background color
imagealphablending($dst,false); //Not to compound transparent colors with opaque
imagesavealpha($dst,true); //Allow transparency
imagefilledrectangle($dst, 0, 0, imagesx($dst), imagesy($dst), $transparent); //Give the destination image transparent background
//Now you can copy
或者只是
imagealphablending($dst,false); //I'm not 100% sure this will make it, but its worth a try
imagecolorallocate($src,0,0,0);
该行看起来像是从源获取图像,然后使用 000 背景。这将是黑色的。只是猜测,不熟悉功能