Created
January 12, 2016 08:09
-
-
Save nenad-mitic-bg/04da3405f3d7ef2305f0 to your computer and use it in GitHub Desktop.
Merge two animated GIFs with PHP (ImageMagick)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/* | |
* This can be used to merge two animated gifs into one. Both GIFs should | |
* have the same size and frame rates. ImageMagick is needed for this to work | |
* | |
* Author: Nenad Mitic [email protected] | |
* | |
*/ | |
function splitToFrames($imagePath, $prefix) | |
{ | |
$dirPath = __DIR__ . '/temp'; | |
$coalesced = (new Imagick($imagePath))->coalesceimages(); | |
$i = 0; | |
while ($coalesced->hasnextimage()) { | |
$coalesced->setiteratorindex($i); | |
$coalesced->writeimage("$dirPath/$prefix-$i.png"); | |
$i++; | |
} | |
$coalesced = null; | |
gc_collect_cycles(); | |
} | |
function mergeFrames($backgroudPrefix, $foregroundPrefix, $amountOfFrames) | |
{ | |
$dirPath = __DIR__ . '/temp'; | |
for ($i = 0; $i < $amountOfFrames; $i++) { | |
$out = new Imagick("$dirPath/$backgroudPrefix-$i.png"); | |
$out->compositeimage(new Imagick("$dirPath/$foregroundPrefix-$i.png"), Imagick::COMPOSITE_DEFAULT, 0, 0); | |
$out->setimagecompression(9); | |
$out->writeimage(); | |
} | |
$out = null; | |
gc_collect_cycles(); | |
} | |
function createAnimation($prefix, $outputName, $amountOfFrames) | |
{ | |
$dirPath = __DIR__ . '/temp'; | |
$out = new Imagick(); | |
$out->setformat('gif'); | |
for ($i = 0; $i < $amountOfFrames; $i++) { | |
$out->addimage(new Imagick("$dirPath/$prefix-$i.png")); | |
$out->setimagedelay(4); | |
$out->setimageiterations(1); | |
} | |
$out->writeimages("$dirPath/$outputName.gif", true); | |
$out = null; | |
gc_collect_cycles(); | |
} | |
$background = __DIR__ . '/src/back.gif'; | |
$front = __DIR__ . '/src/front.gif'; | |
splitToFrames($background, 'back'); | |
$framesCount = count(glob(__DIR__ . '/temp/back-*.png')); | |
splitToFrames($front, 'front'); | |
mergeFrames('back', 'front', $framesCount); | |
createAnimation('back', 'out', $framesCount); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment