【问题标题】:How to merge images in PHP?如何在 PHP 中合并图像?
【发布时间】:2015-01-19 18:29:35
【问题描述】:

我有两个从外部 URL 加载的图像。我想将一个图像放在另一个图像之上(保持大小)。我实际上不知道图像的大小,因为它们来自外部 URL,并且每次都不同。

所以我想要一个可以像merge($url1,$url2,$final_name) 这样调用的函数。我已经用谷歌搜索过,但没有任何效果。

我想要这个3.png

--------------------------------------------------------------------------
                                                                          |
                              IMAGE 1                                     |
                                                                          |
                                                                          |
___________________________________________________________________________

                                                                          |
                              IMAGE 2                                     |
                                                                          |
                                                                          |
___________________________________________________________________________

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

这可以完成工作,但合并后的图像会失去颜色并变成几乎像这样的黑白:

【问题讨论】:

  • 如果只是 php,为什么还要标记 javascript?
  • @AkshayKhandelwal 我想用java脚本写这个document.write("Hello World"),就因为我加了这个标签!
  • 再次总结一下。您想从外部网址加载 2 张图片并将它们组合成一张大图,对吗?
  • @Andi 是的。我想做这个
  • @Andi 另见我的编辑

标签: php css image


【解决方案1】:

而不是这个:

// create new image and merge
$new = imagecreate($new_width, $new_height);

我用过:

// create new image and merge
$new = imagecreatetruecolor($new_width, $new_height);

成功了!

谢谢!

【讨论】:

    【解决方案2】:

    我查了你的代码,但我会把文件夹保存在这样的地方:

    $time = date('d-M-Y') . '-TIME-' . date('H-i-s');    
    $save_finalimage_socialmedia = public_path("storage/image-{$time}.jpeg");
            imagejpeg($new, $save_finalimage_socialmedia);
    

    PS:我是用jpeg格式做的,所以如果你愿意,你可以改变你的格式(png,jpg,...) PS:@user4273356 你的代码对我有用

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-07-28
      • 1970-01-01
      • 2012-10-10
      • 2012-02-10
      • 2019-03-12
      • 2011-12-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多