How to extract animated GIF frames using PHP

I am looking for a long time how to extract frames from an animated GIF with PHP ... unfortunately, I just found how to get their duration ...

I really need to extract GIF frames and their duration in order to apply some resizing, rotation, etc. for everyone, and then for the regeneration of GIFs with edited frames!

I do not want to use any software, an external library (for example, ImageMagick), just PHP: in fact, I need to allow my class http://phpimageworkshop.com/ to work with animated GIFs.

If you have any ideas, I'm listening ^^!

+8
php extract gif animated-gif frame
source share
4 answers

I spent my day creating a class based on this to achieve what I wanted to use only PHP!

You can find it here: https://github.com/Sybio/GifFrameExtractor

Thank you for your responses!

+20
source share

Well, I really do not recommend doing this, but here is an option. Animated gifs are actually just a few gifs combined together by a delimiter: \ x00 \ x21 \ xF9 \ x04. Knowing this, you simply draw the image in PHP as a string, start blowing up and loop the array in which your conversion is performed. The code might look something like this.

$image_string = file_get_contents($image_path); $images = explode("\x00\x21\xF9\x04", $image_string); foreach( $images as $image ) { // apply transformation } $new_gif = implode("\x00\x21\xF9\x04", $images); 

I'm not 100% sure about the specifics of re-concatenating the image, but here is the wikipedia page regarding the animated GIF file format .

+3
source share

I am the author of the https://github.com/stil/gif-endec library, which is significantly faster (about 2.5 times) when decoding GIFs than the Sybio/GifFrameExtractor library from the accepted answer. It also has less memory use, since it allows you to process one frame after another during decoding without loading everything into memory at once.

An example of a small code:

 <?php require __DIR__ . '/../vendor/autoload.php'; use GIFEndec\Events\FrameDecodedEvent; use GIFEndec\IO\FileStream; use GIFEndec\Decoder; /** * Open GIF as FileStream */ $gifStream = new FileStream("path/to/animation.gif"); /** * Create Decoder instance from MemoryStream */ $gifDecoder = new Decoder($gifStream); /** * Run decoder. Pass callback function to process decoded Frames when they're ready. */ $gifDecoder->decode(function (FrameDecodedEvent $event) { /** * Write frame images to directory */ $event->decodedFrame->getStream()->copyContentsToFile( __DIR__ . "/frames/frame{$event->frameIndex}.gif" ); }); 
+2
source share

I do not want to use any software, an external library (e.g. ImageMagick)

Well, good luck with that, because 90% of the functionality that the Zend Engine exports to the PHP runtime comes from libraries.

If you have any ideas, Iโ€™m listening to you ^^!

Parse binary data in GIF format. You can use unpack (), by the way.

+1
source share

All Articles