PHP GD 和透明图像有时工作

PHP GD and transparent images sometimes work

在阅读 PHP 中合并透明图像的问题时,似乎每个人都在 "it works" 或 "it doesn't work" 阵营中。我找到了一种方法来演示每个案例。

我想拍摄一张 PNG,在其中切出一个 ALPHA 孔,然后将其合并到另一张图片之上。在这种情况下,我从 google 地图的图像中剪下一个洞,并将其粘贴到一个红色块上。我有两张来自 google 地图的图片。一张在曼哈顿,一张在我家。一种有效,另一种无效。唯一的区别是 "saved" 通过浏览器。

如果您 运行 下面的代码,您将看到输出的差异。有谁知道为什么相同的代码会完全不同地处理两个 PNG 文件?肯定是PNG文件本身的区别,那又是什么呢?

<?php
sometimesworks("https://maps.googleapis.com/maps/api/staticmap?center=40.714728,-73.998672&zoom=12&size=400x400&maptype=hybrid", "google");
sometimesworks("https://lh4.googleusercontent.com/UQvV_dpBa3_rVf25pvLXKD3OwzF4FtPnHBHkzdWqjCQ5mlFqcFfId9echIgDMv_xYRRYzLaKEXphw7g=w2447-h1106", "myhouse");

function sometimesworks($p_image, $p_prefix)
{
$image_top =imagecreatefrompng($p_image);
$brush = imagecolorallocate($image_top, 0, 0, 0);  //create a black brush
imagefilledpolygon($image_top, explode(",", "10,10, 120,22, 80,280, 200, 191"), 4, $brush);  //fill a polygon
imagecolortransparent($image_top, $brush);  //turn the black to be transparent
imagepng($image_top, './'.$p_prefix.'.transparent.png');  //save the file to confirm that it is working.

//create a big red square
$image_bottom = imagecreatetruecolor(imagesx($image_top), imagesy($image_top));
$red = imagecolorallocate($image_bottom, 255, 0, 0);
imagefill($image_bottom, 0, 0, $red);
imagepng($image_bottom, './'.$p_prefix.'.red.png');

//merge the top onto the bottom.
$out = imagecreatetruecolor(imagesx($image_top), imagesy($image_top));
imagecopy($out, $image_bottom, 0, 0, 0, 0, imagesx($image_top), imagesy($image_top));
imagecopy($out, $image_top, 0, 0, 0, 0, imagesx($image_top), imagesy($image_top));
imagepng($out, './'.$p_prefix.'.out.png');
}

上述代码的问题在于 PNG 文件的类型不同。一个是真彩色图像,另一个是调色板。合并文件的代码因正在执行的操作而异。

这是合并具有透明度的 "palette" 基础 PNG 文件的很好参考。