The following is a description of the problem by using a GIF animation from the CS cop game:
GIF animated Picture: Old.gif
To make the problem clearer, we first restore the frames of the animation:
Select one: Use the Imagick module in PHP:
Copy Code code as follows:
<?php
$image = new Imagick (' old.gif ');
$i = 0;
foreach ($image as $frame) {
$frame->writeimage (' old_ '. $i + +. '. gif ');
}
?>
Option two: Convert command provided with ImageMagick:
Copy Code code as follows:
Shell> Convert Old.gif old_%d.gif
The results of the GIF animation frame diagram are as follows:
Illustration of each frame of GIF animation
It is obvious that GIF animation in order to compress, will be the first frame as a template, the rest of the frames in accordance with the appropriate offset to accumulate, and only keep different pixels, the result is that the size of each frame is not the same, the thumbnail creates a barrier.
Here's how to use the Imagick module in PHP to achieve the perfect GIF animation thumbnail:
Copy Code code as follows:
<?php
$image = new Imagick (' old.gif ');
$image = $image->coalesceimages ();
foreach ($image as $frame) {
$frame->thumbnailimage (50, 50);
}
$image = $image->optimizeimagelayers ();
$image->writeimages (' New.gif ', true);
?>
The most critical part of the code is the Coalesceimages method, which ensures that the frames are the same size, as in the manual:
Composites a set of images while respecting the any page offsets and disposal methods. GIF, MIFF, and MNG animation sequences typically start with a image background and all subsequent image varies in size a nd offset. Returns a new Imagick object where each of the sequence is the same size as the "I" and composited with the next I Mage in the sequence.
Also pay attention to the Optimizeimagelayers method, which deletes duplicate pixel content, in the words of the manual:
Compares each image is the GIF disposed forms of the previous image in the sequence. From this it attempts to select the smallest cropped image to replace all frame while preserving the results of the Anim ation.
BTW: If the requirement is more perfect, you can use the Quantizeimages method to further compress it.
Note: Whether it is coalesceimages, or optimizeimagelayers, is to return the new Imagick Object!
If you are more accustomed to manipulating the shell, then you can implement the GIF animation thumbnail:
Copy Code code as follows:
Shell> convert old.gif-coalesce-thumbnail 50x50-layers optimize new.gif
The generated new.gif are as follows:
There is a specific problem: The convert version will be smaller than the PHP version, which is the result of inconsistent API implementations.
In addition, if the thumbnail size does not conform to the original ratio, in order to avoid deformation, but also to consider cutting or filler, because this article mainly discusses the specificity of GIF animation thumbnail, it will not continue to discuss these issues, interested in their own.