使用 PHP GD 库合并两个 PNG 图像
有人有可以合并两个 PNG 图像的脚本吗?
满足以下条件:
- 两个图像都有透明区域
- 第二个图像必须具有 50% 的不透明度(它覆盖在第一个图像上)
这是我尝试的做但运气不好:
<?php
function imagecopymerge_alpha($dst_im, $src_im, $dst_x, $dst_y, $src_x, $src_y, $src_w, $src_h, $pct){
$cut = imagecreatetruecolor($src_w, $src_h);
imagecopy($cut, $dst_im, 0, 0, $dst_x, $dst_y, $src_w, $src_h);
imagecopy($cut, $src_im, 0, 0, $src_x, $src_y, $src_w, $src_h);
imagecopymerge($dst_im, $cut, $dst_x, $dst_y, 0, 0, $src_w, $src_h, $pct);
}
$image1 = imagecreatefrompng('a.png'); //300 x 300
$image2 = imagecreatefrompng('b.png'); //150 x 150
$merged_image = imagecreatetruecolor(300, 300);
imagealphablending($merged_image, false);
imagesavealpha($merged_image, true);
imagecopy($merged_image, $image1, 0, 0, 0, 0, 300, 300);
imagecopymerge_alpha($merged_image, $image2, 0, 0, 0, 0, 150, 150, 50);
header('Content-Type: image/png');
imagepng($merged_image);
?>
编辑:
- 第一张图片(左)和第二张图片(右)
- 这就是它应该的样子(左)和我的代码的结果(右)
- 提出的解决方案的结果dqhendricks
Does anybody have a script which can merge two PNG images?
With the following conditions:
- Both images have transparent areas
- The second image must have 50% opacity (it is overlaid over the first image)
Here is what I tried to do but without luck:
<?php
function imagecopymerge_alpha($dst_im, $src_im, $dst_x, $dst_y, $src_x, $src_y, $src_w, $src_h, $pct){
$cut = imagecreatetruecolor($src_w, $src_h);
imagecopy($cut, $dst_im, 0, 0, $dst_x, $dst_y, $src_w, $src_h);
imagecopy($cut, $src_im, 0, 0, $src_x, $src_y, $src_w, $src_h);
imagecopymerge($dst_im, $cut, $dst_x, $dst_y, 0, 0, $src_w, $src_h, $pct);
}
$image1 = imagecreatefrompng('a.png'); //300 x 300
$image2 = imagecreatefrompng('b.png'); //150 x 150
$merged_image = imagecreatetruecolor(300, 300);
imagealphablending($merged_image, false);
imagesavealpha($merged_image, true);
imagecopy($merged_image, $image1, 0, 0, 0, 0, 300, 300);
imagecopymerge_alpha($merged_image, $image2, 0, 0, 0, 0, 150, 150, 50);
header('Content-Type: image/png');
imagepng($merged_image);
?>
Edit:
- First Image (left) and Second Image (right)
- This is how it should be (left) and the result of my code (right)
- The result of the solution proposed by dqhendricks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这应该就是你所需要的。 $image1 应保存合并图像,其中 image2 已覆盖 50% 不透明度。最后一个参数是合并副本的 alpha。
http://php.net/manual/en/function.imagecopymerge.php
this should be all you need. $image1 should hold the merged image where image2 has been overlayed with 50% opacity. the last argument is the alpha of the merged copy.
http://php.net/manual/en/function.imagecopymerge.php