gif-endec
接下来就介绍下这个开源项目:gif-endec
地址:https://github.com/stil/gif-endec
可通过composer安装
composer require stil/gif-endec
实现gif倒放很简单,以第一张图举例:
<?php /** * Created by PhpStorm. * User: Tioncico * Date: 2019/3/1 0001 * Time: 10:04 */ include "./vendor/autoload.php"; use GIFEndec\\Color; use GIFEndec\\Encoder; use GIFEndec\\Frame; use GIFEndec\\IO\\FileStream; use GIFEndec\\Events\\FrameDecodedEvent; use GIFEndec\\Decoder; //解析gif图片 //打开gif图片文件流 $gifStream = new FileStream("./Temp/1.gif"); //创建解析对象 $gifDecoder = new Decoder($gifStream); $gifDecoder->decode(function (FrameDecodedEvent $event) { $paddedIndex = str\_pad($event->frameIndex, 3, '0', STR\_PAD_LEFT); //将每一帧存入指定文件夹 $event->decodedFrame->getStream()->copyContentsToFile( \_\_DIR\_\_ . "/frames/frame{$paddedIndex}.gif" ); }); //创建gif生成对象 $gif = new Encoder(); $gifFilesArr = glob(\_\_DIR\_\_ . '/frames/frame*.gif'); //由于一开始生成的时候,是通过分析图片帧来的,而且是顺序读出,如果需要倒序,必须要先倒序下数组 $gifFilesArr = array_reverse($gifFilesArr); foreach ($gifFilesArr as $file) { $stream = new FileStream($file); $frame = new Frame(); $frame->setDisposalMethod(1); $frame->setStream($stream); $frame->setDuration(1); //每个图片的停留时间,1为0.01秒 $frame->setTransparentColor(new Color(255, 255, 255)); $gif->addFrame($frame); } $gif->addFooter(); // Copy result animation to file $gif->getStream()->copyContentsToFile('skateboarder/test.gif');
就这样,我们就得到了一张倒放的图:
同时,我们可以倒放之后再顺放一遍,例如上面的吃棉花糖图:
<?php /** * Created by PhpStorm. * User: Tioncico * Date: 2019/3/1 0001 * Time: 10:04 */ include "./vendor/autoload.php"; use GIFEndec\\Color; use GIFEndec\\Encoder; use GIFEndec\\Frame; use GIFEndec\\IO\\FileStream; use GIFEndec\\Events\\FrameDecodedEvent; use GIFEndec\\Decoder; //解析gif图片 //打开gif图片文件流 $gifStream = new FileStream("./Temp/2.gif"); //创建解析对象 $gifDecoder = new Decoder($gifStream); $gifDecoder->decode(function (FrameDecodedEvent $event) { $paddedIndex = str\_pad($event->frameIndex, 3, '0', STR\_PAD_LEFT); //将每一帧存入指定文件夹 $event->decodedFrame->getStream()->copyContentsToFile( \_\_DIR\_\_ . "/frames/frame{$paddedIndex}.gif" ); }); //创建gif生成对象 $gif = new Encoder(); $gifFilesArr = glob(\_\_DIR\_\_ . '/frames/frame*.gif'); //先倒放,后顺放 $gifFilesArr = array\_merge( array\_reverse($gifFilesArr),$gifFilesArr); foreach ($gifFilesArr as $file) { $stream = new FileStream($file); $frame = new Frame(); $frame->setDisposalMethod(1); $frame->setStream($stream); $frame->setDuration(1); //每个图片的停留时间,1为0.01秒 $frame->setTransparentColor(new Color(255, 255, 255)); $gif->addFrame($frame); } $gif->addFooter(); // Copy result animation to file $gif->getStream()->copyContentsToFile('skateboarder/test3.gif');
哈哈哈哈哈