Flatten multiple transparent PNGs with PHP GD

僤鯓⒐⒋嵵緔 提交于 2021-02-18 18:09:52

问题


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.

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

?>

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

Thank you


回答1:


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

?>



回答2:


You could try this library for compiling transparent images. Just treat each image to layer as a new watermark image.



来源:https://stackoverflow.com/questions/11628324/flatten-multiple-transparent-pngs-with-php-gd

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!