Intervention Image
| Language | PHP 8.3 or later |
|---|---|
| License | MIT |
| Repository | github.com/Intervention/image |
| Documentation | image.intervention.io/v4 |
| Depends on | GD or Imagick (libvips with intervention/image-driver-vips); uses its own intervention/gif codec with GD |
| Read / write | yes / yes; animation with all drivers, loop count, frame delays, interlacing |
Intervention Image decodes animated GIFs into an image with one frame per animation frame, and every modification (scale, cover, crop, …) applies to all frames. Saving as GIF keeps the animation, delays and loop count. With the GD driver it uses its own pure-PHP GIF decoder and encoder (intervention/gif), so animations work even where only GD is installed.
Examples use version 4 of the API (ImageManager::usingDriver, decodePath).
Installation#
Shell
composer require intervention/image
Basic usage: resize an animated GIF#
PHP
<?php
require 'vendor/autoload.php';
use Intervention\Image\Drivers\Gd\Driver;
use Intervention\Image\ImageManager;
$manager = ImageManager::usingDriver(Driver::class);
$image = $manager->decodePath('anim.gif');
printf("%d x %d, animated: %s, %d frames, loops %d\n",
$image->width(), $image->height(),
$image->isAnimated() ? 'yes' : 'no', count($image), $image->loops());
$image->scaleDown(width: 320); // every frame
$image->save('small.gif'); // still animated
How to read frame delays#
PHP
$image = $manager->decodePath('anim.gif');
foreach ($image as $i => $frame) {
printf("frame %d: %.2f s\n", $i, $frame->delay()); // seconds
}
How to create an animated GIF from images#
PHP
$anim = $manager->createImage(200, 200, function ($animation) {
$animation->add('f1.png', delay: 0.25);
$animation->add('f2.png', delay: 0.25);
$animation->add('f3.png', delay: 0.5);
});
$anim->setLoops(0); // 0 = loop forever
$anim->save('anim.gif');
How to keep only the first frame#
PHP
$image = $manager->decodePath('anim.gif');
$image->removeAnimation(0); // keep frame 0 (or a percentage string like '50%')
$image->save('still.png');
How to load only the first frame#
Turn off animation decoding in the driver options; this is faster and uses less memory for thumbnails:
PHP
$manager = ImageManager::usingDriver(Driver::class, decodeAnimation: false);
$thumb = $manager->decodePath('anim.gif')->cover(100, 100);
$thumb->save('thumb.gif');
Tips#
- Converting an animated GIF to WebP with the Imagick or libvips driver keeps the animation:
$image->save('anim.webp'). - Long GIFs decoded with the GD driver hold every frame in PHP memory; raise
memory_limitor use the Imagick driver. encode(new GifEncoder(interlaced: true))writes an interlaced GIF.