Current Location: Home> Latest Articles> Flip dynamic images: combine imagegif() to process multiple frames

Flip dynamic images: combine imagegif() to process multiple frames

M66 2025-06-02

In PHP, imageflip() is a very practical function that can be used to flip images. It can flip static images, but when you work on dynamic images (such as GIF animations), how do you handle every frame? This article will combine the imagegif() function to introduce how to flip GIF animation frame by frame.

Step 1: Load the GIF image

First, you need to load a GIF animation and get each frame of the image. We can load dynamic images through imagecreatefromgif() and use imagegif() to save the modification results of each frame.

 <?php
// load GIF Movie pictures
$imagePath = "path_to_your_gif.gif";
$image = imagecreatefromgif($imagePath);

// Get GIF Number of frames
$frames = [];
$delays = [];
$frameCount = count($frames);

for ($i = 0; $i < $frameCount; $i++) {
    // 逐帧Get图像
    $frame = imagecreatefromgif($image);
    $frames[] = $frame;
    $delays[] = 100; // Set the frame delay time to100
}
?>

Step 2: Use imageflip() to flip each frame

For each frame of the image, we can use imageflip() to flip the image. imageflip() can accept a directional parameter such as horizontal or vertical flip. Commonly used parameters include:

  • IMG_FLIP_HORIZONTAL : Horizontal flip

  • IMG_FLIP_VERTICAL : vertical flip

Here we choose to flip each frame horizontally.

 <?php
foreach ($frames as $frame) {
    // use imageflip() Flip each frame horizontally
    imageflip($frame, IMG_FLIP_HORIZONTAL);
}
?>

Step 3: Save and output new GIF animations

Next, use imagegif() to save each processed frame as a GIF animation. Before saving, we need to make sure that the order and delay time of each frame are applied correctly.

 <?php
// Set the output GIF File path
$outputPath = "path_to_output_gif.gif";
$imagegif($frames[0], $outputPath); // Save the first frame

// Save the remaining frames
for ($i = 1; $i < count($frames); $i++) {
    // Add every frame to GIF Movie pictures
    imagegif($frames[$i], $outputPath);
}
?>

Step 4: Free Resources

After image processing is completed, all resources need to be released to avoid memory leaks.

 <?php
// Release every frame of image resources
foreach ($frames as $frame) {
    imagedestroy($frame);
}
// Free original image resources
imagedestroy($image);
?>

Summarize

With imageflip() and imagegif() , you can conveniently flip and save a new GIF animation frame by frame. This method is especially suitable for scenes where each frame needs to be flipped and a new GIF is output. You can also apply different processing methods to each frame, or even add animation effects as needed.