服务器环境,需安装imageMagick软件,
下载地址:https://imagemagick.org/script/download.php
PHP合成生成GIF动图:https://blog.csdn.net/qq_16494241/article/details/127245975
接到的需求要生成透明GIF图,发现生成的GIF图有帧重叠的情况,可能不知道imagick扩展中的方法,并未GET全,
通过调研最终找到其他解决方案:
cmd 命令行工具执行 ImageMagick - magick 命令
magick convert -delay 10 -loop 0 "D:/pngs/*.png" -set dispose background +repage "D:/pngs/res.gif"
-delay 10 可以根据实际情况进行调整,越小播放速度就越快
PHP执行 cmd 命令的方法
$path:图片所在目录
$gif:合成的图片名称
$command:cmd 执行的命令
$command = 'magick convert -delay 15 -loop 0 "' . $path . '*.png" -set dispose background +repage "' . $path . $gif . '"';
exec($command);
示例:
后台处理接收的 base64图片 帧序列,处理再返回给前端合成的GIF图片(base64图片)
<?php
header("Access-Control-Allow-Origin: *");
$filelist = $_POST['filelist'];
// upfile 目录需要有可写权限
$path = $_SERVER['DOCUMENT_ROOT'] . '/upfile/';
if (!is_dir($path)) {
mkdir($path, 0777);
}
// 创建 本次生成GIF图目录
$rand_dir = time() . rndStr() . '/';
if (!is_dir($path . $rand_dir)) {
mkdir($path . $rand_dir, 0777);
}
// 处理保存每一帧图片 至 本次生成GIF图目录
$file_arr = [];
foreach ( $filelist as $key => $file ) {
// 存储base64图片
if(stripos($file,'base64,')){
$fileArr = explode('base64,',$file);
$img = str_replace(' ', '+', $fileArr[1]);
}else{
$img = str_replace(' ', '+', $file);
}
$img = base64_decode($img);
// 经测试,根据文件名生成GIF图时,11至19会生成到2至10前
$prefix = ceil(($key+1) / 10);
$f = fopen($path . $rand_dir . $prefix . $key . '.png', 'w+');
$file_arr[] = $path . $rand_dir . $prefix . $key . '.png';
fwrite($f, $img);
fclose($f);
}
// 执行 cmd 命令的方法,合成、保存GIF图 至 本次生成GIF图目录
$gif = rndStr() . '.gif';
$file_arr[] = $path . $rand_dir . $gif;
$command = 'magick convert -delay 15 -loop 0 "' . $path . $rand_dir . '*.png" -set dispose background +repage "' . $path . $rand_dir . $gif . '"';
exec($command);
// 传递给前端base64图片
$pic = "data:image/gif;base64," . base64_encode(file_get_contents($path . $rand_dir . $gif));
echo $pic;
// 删除 每一帧图片 及 合成的GIF图片
foreach ($file_arr as $file) {
@unlink($file);
}
// 删除 本次生成GIF图目录
@rmdir ($path . $rand_dir);
function rndStr(){
$string = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$len = rand(0,3)+5;
$rst = '';
$strl = strlen($string);
for($i=0;$i<$len;$i++){
$ind = rand(0, $strl);
$s = $string[$ind];
$rst .= $s;
}
return $rst;
}
?>