Search code examples
phpimagemagickpnggifimagick

How to convert multiple PNGs into a single animated GIF using PHP's Imagick


I have several PNG format Imagick objects which are intended as individual frames for an animated GIF. How would I convert these frames into a single animated GIF?


Solution

  • You're going to want to append each file to a an image magic object. Check out this answer which includes a great code sample for creating an animated gif:

    Make an animated GIF with PHP's ImageMagick API

    You may need to complete gif creation by using the writeimages method, which is missing from the above sample: http://www.php.net/manual/en/imagick.writeimages.php

    I'm not sure if this is helpful, but I have created animated gifs in Ruby using imagemagic. The code below is a simple sample of what I have done. I hope this is useful and may give you an idea on how to construct your program.

    require 'rubygems'
    require 'rmagick'
    include Magick
    
    dir_contents = Dir.glob("xmas_tree_files/*.gif")
    
    image_list = ImageList.new
    image_list.delay = 20 # delay 1/5 of a second between images.
    
    dir_contents.each do |file_name|
      image = Image.read("#{file_name}").first
      image_list << image
    end
    
    #make sure to write the animated gif to a different dir 
    #than the one that contains your original images,
    #otherwise you'll get weirdly animated gifs when you rerun the program
    image_list.write("animated_tree.gif")