对我来说,这些解决方案都没有用,因为它们总是将源图像上的透明像素转换为目标图像上的黑色。有效的方法是将imagecopy/imagecopymerge/imagecopymerge_alpha更改为imagecopyresampled,并将相同的宽度和高度传递两次。
//Create destination image.
$png = imagecreatetruecolor(1024, 1024);
imagealphablending($png, false);
imagesavealpha($png, true);
//Make destination image be all transparent.
$color = imagecolorallocatealpha($png, 0, 0, 0, 127); //127 means completely transparent.
imagefill($png, 0, 0, $color);
//Load source image.
$png2 = imagecreatefrompng($sourceurl);
imagealphablending($png2, false);
imagesavealpha($png2, true);
$sizex = imagesx($png2);
$sizey = imagesy($png2);
//Copy to destination and save to file.
imagecopyresampled( $png, $png2,
0, 0,
0, 0,
$sizex, $sizey,
$sizex, $sizey);
imagepng($png, "result.png");
$black = imagecolorallocate($output, 0, 0, 0); imagecolortransparent($output, $black);
在imagecopy之前。 - 2by