使用PHP GD展平多个透明PNG [英] Flatten multiple transparent PNGs with PHP GD

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

问题描述

我正在构建一个产品配置模块,该模块要求将多个相同大小的透明PNG(代表产品零件)展平到一个图像上.

I am building a product configuration module which requires that multiple transparent PNGs of the same size (which represent product parts) be flattened onto one image.

起初,我尝试使用此方法制作了3张图片,但背景为黑色:

At first I tried this which made the composition of the 3 images but on a black background:

<?php

$x = 500;
$y = 500;

$final_img = imagecreatetruecolor($x, $y);
$images = array('1.png', '2.png', '3.png');

foreach ($images as $image) {
    $image_layer = imagecreatefrompng($image);
    imagecopy($final_img, $image_layer, 0, 0, 0, 0, $x, $y);
}

imagealphablending($final_img, true);
imagesavealpha($final_img, true);

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

?>

然后我发现此功能可以解决黑色背景问题并为我提供透明效果,但是现在仅显示添加到构图中的最后一张图像.

Then I found this function which fixes the black background issue and gives me a transparent one but now only the last image added to the composition is shown.

<?php

$x = 500;
$y = 500;

function imageCreateTransparent($x, $y) {
    $image = imagecreatetruecolor($x, $y);
    imagealphablending($image, false);
    imagesavealpha($image, true);
    $col = imagecolorallocatealpha($image,255,255,255,127);
    imagefill($image, 0, 0, $col);
    return $image;
}

$final_img = imageCreateTransparent($x, $y);
$images = array('1.png', '2.png', '3.png');

foreach ($images as $image) {
    $image_layer = imagecreatefrompng($image);
    imagecopy($final_img, $image_layer, 0, 0, 0, 0, $x, $y);
}

imagealphablending($final_img, true);
imagesavealpha($final_img, true);

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

?>

如何获得透明背景并显示所有3张合并的图像.

How can I get a transparent background AND show all 3 images merged together.

谢谢

推荐答案

我修改了您的第一个示例以使其正常工作.

I've modified your first example to make that work.

    <?php

$x = 500;
$y = 500;

$final_img = imagecreatetruecolor($x, $y);


imagesavealpha($final_img, true);


$trans_colour = imagecolorallocatealpha($final_img, 0, 0, 0, 127);
imagefill($final_img, 0, 0, $trans_colour);


$images = array('1.png', '2.png', '3.png');

foreach ($images as $image) {
    $image_layer = imagecreatefrompng($image);
    imagecopy($final_img, $image_layer, 0, 0, 0, 0, $x, $y);
}

//imagealphablending($final_img, true);
imagesavealpha($final_img, true);
imagealphablending($final_img, true);


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

?>

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

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