将一个图像复制到下一个图像上,同时保持透明度

时间:2014-02-17 18:30:39

标签: php gd

我正在努力使用PHP的GDLib。我试图将两个.PNG图像叠加在彼此之上,到目前为止工作正常。

我遇到的一个问题是,有时候,叠加图像会带有白色背景。我可以使其透明(使用imagecolortransparent功能),但是当我将此图像复制到新图像时,不会保存此透明度。

// Load the background image first

$background = imagecreatefrompng($this->background);

// Load the overlaying image next, and set white as a transparent color

$overlay = imagecreatefrompng($this->image);
imagecolortransparent($overlay, imagecolorallocate($overlay, 255, 255, 255));

// So far, this all works. But when I create a new image,
// and paste both $background and $overlay into it,
// $overlay loses transparency and reverts to a white fill.

$image = imagecreatetruecolor(16, 16);
imagesavealpha($image, true);
$trans_colour = imagecolorallocatealpha($image, 255, 255, 255, 127);
imagefill($image, 0, 0, $trans_colour);

imagecopyresampled($image, $background, 0, 0, 0, 0, 16, 16, 16, 16);
imagecopyresampled($image, $overlay, 0, 0, 0, 0, 16, 16, 16, 16);
@mkdir(dirname($file), 0777, true);
imagepng($image, $file);

// The new $image is now mostly white. The transparency on $overlay
// was lost, meaning that the $background image is completely invisible.

$overlay复制到新图像时,如何保持透明度?

1 个答案:

答案 0 :(得分:2)

$photo_to_paste = "photo_to_paste.png";
$white_image = "white_image.png";

$im = imagecreatefrompng($white_image);
$im2 = imagecreatefrompng($photo_to_paste);

imagecopy($im, $im2, (imagesx($im) / 2) - (imagesx($im2) / 2), (imagesy($im) / 2) - (imagesy($im2) / 2), 0, 0, imagesx($im2), imagesy($im2));

// Save alpha for the destination image.
imagesavealpha($im, true);
$trans_colour = imagecolorallocatealpha($im, 0, 0, 0, 127);
imagefill($im, 0, 0, $trans_colour);

// Save final image after placing one on another image
imagepng($im, "output.png", 0);

imagedestroy($im);
imagedestroy($im2);