PHP: GIF animation splitter (Split any GIF animiations – frame by frame properly!)

I have been looking for a GIF animation splitting script for quite awhile, but have not found any luck with any basic ones. There has been a couple but they do not process GIF animations properly anymore, because GIFs now are optimized etc You will end up getting frames that aren’t ‘complete’ frames because they need to be coalesced.

I ended up finding a nice module for PHP called ImageMagick (requires PHP5.3+), which can be found here: You will need both the binary releases and the actual extension for PHP 5. The extension also needs to be added to the php.ini file as well. There is a quick guide here for windows based systems by Mikko, but you can follow something similar for Linux. You can also Google around to find out how to setup ImageMagick. It’s not hard at all though!

After you have it all setup and ready to go, this SIMPLE following code I created will split the frames very easily, and even handle coalesced type GIF animations. Virtually, any GIF animation should split up nicely here, and you can even do different format outputs, such as GIF, JPG, PNG, etc.

function animationWriteFrames($filename, $format="frame%0d.gif", $destination="")
		$animation = new Imagick($filename);
		$coalesced = $animation->coalesceImages();
		// total frames
		// $total = $coalesced->getNumberImages();
		foreach ($coalesced as $frame)
			$index = 1 + $frame->getImageIndex();
			$tofilename = $destination . sprintf($format, $index);
	catch(Exception $e)
		echo $e->GetMessage(), "\n";
		return FALSE;
	return TRUE;

As you see, most of the handling is done via the PHP EXTENSION and the build files, making it pretty easy compared to most scripts that try to handle this (Most scripts are giant when handling this!). Now! To call it, here are three examples:

animationWriteFrames("sample.gif", "frame%05d.png", "./framesPNG/");
animationWriteFrames("sample.gif", "frame%05d.jpeg", "./framesJPG/");
animationWriteFrames("sample.gif", "frame%05d.gif", "./framesGIF/");

Simple right? Calling these will split the frames of the sample.gif animation into either PNG/JPEG/GIF in the examples, depending on which one you use. Basically animationWriteFrames takes three variables: "Image to split, Output filenames/extension, Folder to place split images too". Super simple and can be called virtually anywhere! Any errors will be echoed, so you may want to handle that as well.

Splitting GIF animations is super simple! I’ll probably throw up an example sometime soon. Working on a special script using images themselves!


Related posts:

  1. PHP: Easy to use logging class for your scripts.

About the Author

I mainly focus on Javascript/PHP/C++/.NET applications for everyday and work. I also am working on a remake of Stellar Frontier, an old 2D top down space battle game with a few fellow programmers.