使用php合并多个重叠的透明png图像

时间:2013-08-16 20:10:07

标签: php gd

我有一个自定义自行车配置器,它使用css对透明的png文件进行分层。 http://www.gallantbicycles.com/build/no1/

我需要添加将它们动态组合到一个文件中的功能,以便用户可以下载图像或共享它。

这就是我现在所处的位置,但它会产生黑色背景,结果中只显示最前面的图像:

$width = 720;
$height = 500;

$layers = array();
$layers[] = imagecreatefrompng("pathtomyimage/image.png");
$layers[] = imagecreatefrompng("pathtomyimage/image.png");
$layers[] = imagecreatefrompng("pathtomyimage/image.png");

$image = imagecreatetruecolor($width, $height);
imagealphablending($image, false);
imagesavealpha($image, true);

for ($i = 0; $i < count($layers); $i++) {
  imagecopymerge($image, $layers[$i], 0, 0, 0, 0, $width, $height, 100);
}

header('Content-type: image/png');
imagepng($image);

3 个答案:

答案 0 :(得分:0)

您必须替换此代码

imagealphablending($image, false);
imagesavealpha($image, true);

for ($i = 0; $i < count($layers); $i++) {
  imagecopymerge($image, $layers[$i], 0, 0, 0, 0, $width, $height, 100);
}

通过

imagealphablending($image, true);
for ($i = 0; $i < count($layers); $i++) {
  imagecopymerge($image, $layers[$i], 0, 0, 0, 0, $width, $height, 100);
}
imagealphablending($image, false);
imagesavealpha($image, true);

imagealphablending必须为true才能正确堆叠图层,但必须false才能保存图像。

答案 1 :(得分:0)

尝试此解决方案:Merge two images with transparencies in PHP

使用imagecopyresampled而不是imagecopymerge

答案 2 :(得分:0)

这是有效的代码:     

$width = 210;
$height = 190;

$layers = array();
$layers[] = imagecreatefrompng("img/01_boy_faceB.png");
$layers[] = imagecreatefrompng("img/01_boy_hairB.png");

$image = imagecreatetruecolor($width, $height);

// to make background transparent
imagealphablending($image, false);
$transparency = imagecolorallocatealpha($image, 0, 0, 0, 127);
imagefill($image, 0, 0, $transparency);
imagesavealpha($image, true);

/* if you want to set background color
$white = imagecolorallocate($image, 255, 255, 255);
imagefill($image, 0, 0, $white);
*/

imagealphablending($image, true);
for ($i = 0; $i < count($layers); $i++) {
    imagecopy($image, $layers[$i], 0, 0, 0, 0, $width, $height);
}
imagealphablending($image, false);
imagesavealpha($image, true);

imagepng($image, 'final_img.png');

?>
相关问题