【问题标题】:Most EFFICIENT way to merge multiple PNGs in PHP在 PHP 中合并多个 PNG 的最有效方法
【发布时间】:2012-09-13 07:01:40
【问题描述】:

我运行一个网站,该网站需要定期遍历一堆具有透明度的 PNG 并将它们合并在一起。有时这可能是一个漫长的过程,所以我想知道最有效的方法是什么。我正在使用 GD,因为我听说 ImageMagick 并没有真正更快..

$firstTime = true;  // need to know if it's the first time through the loop
$img = null;        // placeholder for each iterative image
$base = null;       // will become the final merged image
$width = 0;
$height = 0;

while( $src = getNextImageName() ){
    $imageHandle = imagecreatefrompng($src);
    imageAlphaBlending($imageHandle, true);
    imageSaveAlpha($imageHandle, true);

    if( $firstTime ){
        $w = imagesx( $img );       // first time in we need to
        $h = imagesy( $img );       // save the width & height off
        $firstTime = false;
        $base = $img;               // copy the first image to be the 'base'
    } else {
        // if it's not the first time, copy the current image on top of base
        // and then delete the current image from memory
        imagecopy($base, $img, 0, 0, 0, 0, $w, $h);
        imagedestroy($img);
    }
}

// final cleanup
imagepng($base);
imagedestroy($base);

【问题讨论】:

  • 您是否通过 profiling 确认了哪个部分慢?这些其他功能的实现是什么?
  • 您想让它更高效或更快吗?有许多图像,您可以并行进行合并
  • 我没有特别介绍过任何东西。我正在使用所有 GD PHP 函数。 GetNextImageName() 是一个模拟函数——假装它从数组中弹出下一项......它只是一种传递源文件名的机制。我应该更清楚地了解效率与速度。我希望这更快。我只是在合并 9 层(2750x2500px - 大图像!)时对这个脚本进行了计时。从我的本地机器上花了 1:45。我将如何编写代码使其并行工作?
  • @AlexanderLarikov - 我在网上看到很多测试表明 imageMagick 并没有更快。你认为情况并非如此吗?
  • 由于您正在处理这样大小的图片,我建议您使用队列。例如:Youtube 不会对 POST 请求中的视频进行编码,而是将其放入一个队列中,由服务器场持续处理。在这种情况下,您可以使用本机应用程序(用 C++ 编写)来处理队列。该过程将是异步的,但不会出现性能问题。

标签: php performance image merge png


【解决方案1】:

您绝对应该尝试一下 ImageMagick。它很容易实现,只需使用exec('composite 1.png 2.png');。它有据可查,不受 PHP 内存限制,性能还可以。

此外,ImageMagick 可作为 bash 脚本或其他终端功能的独立工具使用,这意味着您所学的内容在 PHP 之外也很有用。

【讨论】:

    【解决方案2】:

    根据a benchmark,ImageMagick 比 GD 快。这至少是一个开始。

    我不知道你是否也可以将PHP的优先级提高到Above Normal/High?

    【讨论】:

      猜你喜欢
      • 2014-10-01
      • 1970-01-01
      • 2018-11-25
      • 2014-04-01
      • 1970-01-01
      • 2013-02-07
      • 1970-01-01
      • 2011-06-02
      • 2018-03-20
      相关资源
      最近更新 更多