Home >Backend Development >PHP Tutorial >How can I resize animated GIFs in PHP while preserving animation?

How can I resize animated GIFs in PHP while preserving animation?

Linda Hamilton
Linda HamiltonOriginal
2024-11-07 21:16:03466browse

How can I resize animated GIFs in PHP while preserving animation?

Resizing Animated GIFs with Animation Preservation in PHP

Resizing animated GIFs while maintaining the animation can be achieved using external tools like ImageMagick or through a combination of GD library functions.

ImageMagick Method:

If you have access to ImageMagick, the following commands can resize an animated GIF:

system("convert big.gif -coalesce coalesce.gif");
system("convert -size 200x100 coalesce.gif -resize 200x10 small.gif");

GD Library Method:

For PHP users without ImageMagick access, resizing animated GIFs involves several steps:

1. Detect Image Type:
Determine if the image is an animated GIF using GD.

2. Split into Frames:
Separate the GIF into individual frames using a GD library or third-party class.

3. Resize Frames:
Resize each individual frame using GD library functions.

4. Recomposite Frames:
Reassemble the resized frames into a new animated GIF using GD or a specialized library.

Example Code:

// Get image
$sourceGif = imagecreatefromgif("big.gif");

// Determine if animated
if (gdImageAnimationLen($sourceGif) > 1) {
    // Split into frames
    $frames = $frames = gdImageSplitAnimation($sourceGif);

    // Resize frames
    $resizedFrames = [];
    foreach ($frames as $frame) {
        $resizedFrames[] = gdImageScale($frame, $newWidth, $newHeight);
    }

    // Recomposite GIF
    $newGif = $newGif = gdImageCreateAnimatedGif() ;
    foreach ($resizedFrames as $frame) {
        gdImageAddGif($newGif, $frame);
    }

    // Output GIF
    imagegif($newGif, "small.gif");
}

Note that this method may produce a larger file size due to the coalescing and deoptimization process. If performance is a concern, consider using ImageMagick instead.

The above is the detailed content of How can I resize animated GIFs in PHP while preserving animation?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn