1

我有一个自定义的自行车配置器,它使用 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);
4

3 回答 3

1

您必须替换此代码

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为了保存图像。

于 2013-08-21T11:39:36.347 回答
0

试试这个解决方案:在 PHP 中合并两个带有透明度的图像

使用 imagecopyresampled 而不是 imagecopymerge

于 2013-12-04T22:16:22.887 回答
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');

?>
于 2014-04-03T17:49:19.680 回答