Search code examples
casperjsimagemagick-convert

maintain smooth movement after modifying gif with casperjs and imagemagick


I'm trying to add static text to a div with a background gif animation using js+css, and exporting the result to a new gif merging everything.

The problem is related to the number of screenshots that I need to take, and the time between those, to re-assemble using imagemagick and maintain the fps or rate.

This is what I have now:

  1. Obtain info of the gif

    identify -format "Frame %s: %Tcs\n" gif.gif
    Frame 0: 3cs
    Frame 1: 3cs 
    ....
    Frame 60: 3cs 
    

  1. create a simply html+css+js
  2. use casperjs for take screenshoots (30 millisecond == 3 centiseconds, and I'm using 60 screenshots related to the 60 frames that's identify point me out)

    casper.start('git-animation.html', function()
    {
    casper.waitForSelector('#parent', function()
    {
        for (var i=0; i <= 60; i++)
        {
            casper.wait(1, function()
            {
                var file = output + 'frame' + n + '.png';
                casper.captureSelector(output + 'frame' + n + '.png', '#animation');
                n++;
            });
        }
    });
    });
    
  3. Use php/imagemagick to assemble everything in one gif (I'm using 3 centiseconds for the delay)

    $app->services['imagick']->setFormat('GIf');
    
        for($i = 0; $i <= 60; $i++)
        {
            $frame = new Imagick($app->config['paths']['exported_images'] . $sha1 . '/frame' . $i . '.png');
            $app->services['imagick']->addImage($frame);
            $app->services['imagick']->setImageDelay(3);
            $app->services['imagick']->nextImage();
        }
    
        // save gif animation
        $app->services['imagick']->writeImages($app->config['paths']['exported_images'] . '/' . $sha1 . $ext, true);
    

Original gif

Modified gif

As you can see, the animation is clearly different, how can this be improved?


Solution

  • The reason for the animation to be different is that this technique of splitting the image via taking screenshots is not very accurate. You can instead split it into the component images using imagemagick directly, like so

    convert mhhdh.gif mhhdh.png

    which will give you a directory full of silly little .png files. You can alter those to your heart's content and then reassemble as you see fit, after any possible modifications you want to make.