PHP将图片合成gif动图

**一、**要实现此功能首先需要安装一个扩展:imagick扩展

我这里php环境使用的docker,直接在Dockerfile文件中定义后,生成容器即可:

复制代码
# 安装Imagick PHP扩展
RUN pecl install imagick && \
docker-php-ext-enable imagick

其他方式,可以自行搜索下。

安装后,执行php -m查看是否已经安装成功,安装成功如下图,列表中会显示imagick:

**二、**多个图片生成GIF动图

复制代码
        $imageData = []; //图片数据
        foreach ($imageArr as $item){ //$imageArr 图片数据 数组,我代码这里只需要png格式的图片
            $char = substr($item, -4);
            if($char == '.png'){
                $imageData[] = $item;
            }
        }

        $freq = 20; //每秒播放多少图片
        $interval = (int) (100 / $freq); //图片播放间隔时长 100是1秒

        $generateGifResult = self::generateGif($imageData, $gifFilePath, $interval, $width, $high);



     /**
     * @param $imageData *图片数据 数组
     * @param $gifPath *要输出的gif路径(文件所在的文件夹路径需要存在) ./test/test.gif
     * @param $interval *图片播放间隔时长
     * @return bool
     * @throws \ImagickException
     */
    public static function generateGif($imageData, $gifPath, $interval, $width = 200, $high = 300, $addWatermark = false)
    {
        $animation = new Imagick();
        $animation->setFormat('gif');

        foreach ($imageData as $file) {
            $img = new Imagick($file);
            $img->thumbnailImage($width, $high);//读取本地图片 将图片大小修改成自己定义的宽高
            if($addWatermark){ // 设置水印
                $text = new ImagickDraw();
                $text->setFillColor('#000');
                $text->setFont('Arial');
                $text->setFontSize(30);
                $text->setGravity(Imagick::GRAVITY_SOUTH); //水印位置
                $img->annotateImage($text, 0, 0, 0, '水印');
                unset($text);
            }
            //设置图像处理方法 3:清除此帧覆盖之前的图像 2:使用背景色清除边框区域 1:不丢弃,只覆盖下一帧图像 0:未指定处置
            $img->setImageDispose(3);
            $animation->addImage($img);//将图片加入到gif中
            $animation->setImageDelay($interval);//转场动画时间 100是1秒
            $animation->nextImage();
            unset($img);
        }

        //保存gif
        $animation->writeImages($gifPath,true);

        return true;
    }

生成后就是一个gif格式的动图文件了

相关推荐
天高云淡ylz3 小时前
子网掩码的隐形陷阱:为何能ping通却无法HTTPS访问
开发语言·php
乱飞的秋天11 小时前
网络编程学习
网络·学习·php
Qlittleboy12 小时前
tp5的tbmember表闭包查询 openid=‘abc‘ 并且(wx_unionid=null或者wx_unionid=‘‘)
数据库·sql·php
会飞的土拨鼠呀14 小时前
Linux负载如何判断服务器的压力
linux·服务器·php
悠悠~飘18 小时前
php学习(第二天)
开发语言·学习·php
catchadmin18 小时前
开发 PHP 扩展新途径 通过 FrankenPHP 用 Go 语言编写 PHP 扩展
android·golang·php
Qlittleboy21 小时前
tp5.0如何配置session保存到文件里,方便删除
缓存·php
admin⁠21 小时前
php 实现 导入excel 带图片导入
php·excel
BingoGo21 小时前
PHP 性能优化实战 OPcache + FPM 极限优化配置
后端·php
好多171 天前
《Java中的IO流》
java·开发语言·php