Search code examples
phpimagemagickimagick

Cropping animation with imagick results in blue background


I have compiled ImageMagick 6.8.7-10 Q8 x86_64 on Ubuntu 13.04 64-bit. I also installed imagick 3.2.0RC1 for PHP 5.5.7.

I am using the following to crop an animated gif:

$imagick = new \Imagick('anim2.gif');

$imagick = $imagick->coalesceImages();

foreach ($imagick as $frame) {
    $frame->cropImage(80, 80, 0, 0);
    $frame->thumbnailImage(80, 80);
    $frame->setImagePage(80, 80, 0, 0);
}

$imagick = $imagick->deconstructImages();

$imagick->writeImages('test.gif', true);

This is the original image: enter image description here

And the cropped image becomes: enter image description here

Notice that the cropped image gains a blue background in the second frame.

Why is this happening?


Solution

  • The problem is that coalesce introduces the background. This may or may not be a bug in imagemagick.

    If running from the command line, you need to set the background to none before coalescing:

    convert anim2.gif -background none -coalesce temporary.gif
    

    From PHP's imagick library, you need to set all the frames' backgrounds to none:

    $imagick = new \Imagick('anim2.gif');
    
    foreach ($imagick as $frame) {
       $frame->setImageBackgroundColor('none'); //This is important!
    }
    
    $imagick = $imagick->coalesceImages();
    
    foreach ($imagick as $frame) {
        $frame->cropImage(80, 80, 0, 0);
        $frame->thumbnailImage(80, 80);
        $frame->setImagePage(80, 80, 0, 0);
    }
    
    $imagick = $imagick->deconstructImages();
    
    $imagick->writeImages('test.gif', true);
    

    The result: enter image description here