PHP GD和透明图像有时可以工作

PHP GD和透明图像有时可以工作,php,gd,Php,Gd,在阅读有关在PHP中合并透明图像的问题时,似乎每个人都在it工作或不工作的阵营中。我找到了一种方法来演示每个案例 我希望采取一个PNG,削减一个阿尔法洞,然后合并到另一个图像的顶部。在本例中,我在谷歌地图的图像上剪了一个洞,然后将它粘贴到一个红色块上。我有两张来自谷歌地图的图片。一个是曼哈顿,一个是我家。一个工作,一个不工作。唯一的区别是一个是通过浏览器保存的 如果运行下面的代码,您将看到输出的差异。有人知道为什么相同的代码会以完全不同的方式处理两个PNG文件吗?这一定是PNG文件本身的不同,但

在阅读有关在PHP中合并透明图像的问题时,似乎每个人都在it工作或不工作的阵营中。我找到了一种方法来演示每个案例

我希望采取一个PNG,削减一个阿尔法洞,然后合并到另一个图像的顶部。在本例中,我在谷歌地图的图像上剪了一个洞,然后将它粘贴到一个红色块上。我有两张来自谷歌地图的图片。一个是曼哈顿,一个是我家。一个工作,一个不工作。唯一的区别是一个是通过浏览器保存的

如果运行下面的代码,您将看到输出的差异。有人知道为什么相同的代码会以完全不同的方式处理两个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文件的类型不同。一个是真彩色图像,另一个是调色板。合并文件的代码因执行的操作而异

对于将基于调色板的PNG文件与透明度合并,这是一个很好的参考