在PHP中将一张图片添加到另一张图片底部

3
我想在 PHP 中在一张图片底部添加另一张图片。 我有以下代码来加载图片:
//load top
$top = @imagecreatefrompng($templateTop);
//load bottom
$bottom = @imagecreatefrompng($templateBottom);

现在我想将它们添加到一张图片中,同时显示顶部和底部。我应该用什么方法实现呢?谢谢!
3个回答

19

使用imagecopy函数:

$top_file = 'image1.png';
$bottom_file = 'image2.png';

$top = imagecreatefrompng($top_file);
$bottom = imagecreatefrompng($bottom_file);

// get current width/height
list($top_width, $top_height) = getimagesize($top_file);
list($bottom_width, $bottom_height) = getimagesize($bottom_file);

// compute new width/height
$new_width = ($top_width > $bottom_width) ? $top_width : $bottom_width;
$new_height = $top_height + $bottom_height;

// create new image and merge
$new = imagecreate($new_width, $new_height);
imagecopy($new, $top, 0, 0, 0, 0, $top_width, $top_height);
imagecopy($new, $bottom, 0, $top_height+1, 0, 0, $bottom_width, $bottom_height);

// save to file
imagepng($new, 'merged_image.png');

但是如果我想合并带有 alpha 通道的图像呢?现在,具有相同尺寸的第二个图像会重叠在第一个图像上。 - Aleksandrs

1
为了实现这个目标,您需要: a)将图像合并并将结果存储在文件中 b)生成一个适当的标签来指向它。 c)避免再次使用该文件名,直到该人离开。
如果您只想一次组合两个图像,请使用ImageMagick。
如果您经常想要在下面显示两个图像,请使用适当的HTML,并让浏览器完成。
例如,将图像放在
中,您可以按照正常方式使用PHP生成它。(这比让标签出现在此处更容易 :))

2
这听起来一点也不像他要求的... 不知道他的用例,这可能不是一个可行的解决方案。我猜他想为CSS精灵做这件事。 - mpen

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

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


// Place "photo_to_paste.png" on "white_image.png"
imagecopy($im, $im2, 20, 10, 0, 0, imagesx($im2), imagesy($im2));

// Save output image.
imagepng($im, "output.png", 0);

可能不是这个问题的答案,但由于如果您想要将两个图像放在彼此上方,这就是答案,所以它不应该被投票否决。 - Wanjia

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接