问题
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