captain_jim1
captain_jim1

Reputation: 1001

Most EFFICIENT way to merge multiple PNGs in PHP

I run a website that needs to routinely loop through a bunch of PNGs with transparency's and merge them together. Sometimes this can be a LONG process so I was wondering what is the most efficient way to do this. I'm using GD as I hear ImageMagick isn't really any FASTER..

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

Upvotes: 0

Views: 589

Answers (2)

Danny Beckett
Danny Beckett

Reputation: 20806

According to a benchmark, ImageMagick is faster than GD. This would be a start at least.

I don't know whether you could also increase the priority of PHP to Above Normal/High?

Upvotes: 1

aebersold
aebersold

Reputation: 11516

You should definitely give ImageMagick a try. It's easy to implement, just use exec('composite 1.png 2.png');. It's well documented, not bound to PHPs memory limits and the performance is ok.

In addition, ImageMagick works great as a stand-alone for bash scripting or another terminal functions which means what you learn is useful outside of PHP.

Upvotes: 1

Related Questions