用PHP合并多个重叠的透明PNG图像 [英] Merging multiple overlapping transparent png images with php

查看:72
本文介绍了用PHP合并多个重叠的透明PNG图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个自定义的自行车配置器,可使用CSS将透明的png文件分层放置. http://www.gallantbicycles.com/build/no1/

I have a custom bicycle configurator that layers transparent png files with css. http://www.gallantbicycles.com/build/no1/

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

I need to add the ability to combine them into one file dynamically so the user can download an image or share it.

这是我现在所处的位置,但它会导致黑色背景,并且结果中仅显示最前面的图像:

This is where I'm at right now, but it results in a black background and only the front most image is seen in the result:

$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);

推荐答案

以下是适用的代码:

Here is code which works:

$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');

?>

这篇关于用PHP合并多个重叠的透明PNG图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆