Today’s example was requested by a user called Devo. This example illustrates making an animated GIF image by creating the frames from scratch. It’s been so long since I’ve really drawn anything so I decided to use text as the base for this animation.

You could of course use existing images to simulate motion or even strip frames from videos to create GIF animations. The example is pretty straightforward but please post any questions you might have.

  1. <?php
  2.  
  3. /* This object will hold the animation */
  4. $animation = new Imagick();
  5.  
  6. /* Set the format to gif. All created images will be gifs*/
  7. $animation->setFormat( "gif" );
  8.  
  9. /* Create a pixel to handle colors */
  10. $color = new ImagickPixel( "white" );
  11.  
  12. /* The first frame */
  13. $color->setColor( "white" );
  14.  
  15. /* This is the string we print on the image
  16.     Character by character */
  17. $string = "HELLO WORLD!";
  18.  
  19. /* Create a new ImagickDraw object and set the font
  20.     Text color defaults to black */
  21. $draw = new ImagickDraw();
  22.  
  23. /* You can get configured fonts with $im->queryFonts
  24.     or use /path/to/file.ttf */
  25. $draw->setFont( "Helvetica" );
  26.  
  27. /* Loop trough the string.. */
  28. for ( $i = 0; $i <= strlen( $string ); $i++ )
  29. {
  30.     /* Take some characters for this frame */
  31.     $part = substr( $string, 0, $i );
  32.  
  33.     /* Create a new frame */
  34.     $animation->newImage( 100, 50, $color );
  35.    
  36.     /* Annotate the characters on the image */
  37.     $animation->annotateImage( $draw, 10, 10, 0, $part );
  38.  
  39.     /* Set a little higher delay for the frame*/
  40.     $animation->setImageDelay( 30 );
  41. }
  42.  
  43. /* The last frame contains the same text with bold */
  44. $draw->setFont( "Helvetica-Bold" );
  45.  
  46. /* One more frame */
  47. $animation->newImage( 100, 50, $color );
  48.  
  49. /* Annotate the bold text on the image */
  50. $animation->annotateImage( $draw, 10, 10, 0, $string );
  51.  
  52. /* The bold can be visible a little longer time */
  53. $animation->setImageDelay( 60 );
  54.  
  55. /* Display the output as an animation.
  56.     Use getImagesBlob to get all images combined */
  57. header( "Content-Type: image/gif" );
  58. echo $animation->getImagesBlob();
  59.  
  60. ?>

This is how the resulting image looks like:

animation