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格式的动图文件了

相关推荐
狂野小青年1 小时前
在PHP Web开发中,实现异步处理有几种常见方式的优缺点,以及最佳实践推荐方法
消息队列·php·最佳实践·异步任务
张鱼小丸子5 小时前
【无标题】云原生作业六
开发语言·php
哥坐11路20 小时前
网络IP跳动问题解决详
开发语言·php
一只哒布刘1 天前
第六次作业
开发语言·php
寰宇软件1 天前
PHP房屋出租出售高效预约系统小程序源码
前端·小程序·uni-app·vue·php
HUNAG-DA-PAO1 天前
Redis存在线程安全吗?为什么?
redis·安全·php
ianozo1 天前
BUU40 [安洵杯 2019]easy_serialize_php
android·开发语言·php
zgscwxd1 天前
php session数据存储位置选择
开发语言·php
ianozo2 天前
CTF 代码学习日记 PHP
java·学习·php
ontheway-xx2 天前
PHP+Apache+MySQL安装(Windows)
开发语言·php