我在一个项目中工作,其中用户可以上传webp图像。我知道如何将webp图像转换为jpg/png,但我不知道如何识别webp图像是静态的(非动画的)还是动画的。
我想识别它们,因为我使用不同的命令进行转换:
非动画webp到jpg的命令:
dwebp nonanimated.webp -o jpg.jpg
动画webp到非动画webp的命令(第2帧):
webpmux -get frame 2 animated.webp -o nonanimated.webp
但是我找不到一个可以同时处理这两种情况的命令。
我在服务器端使用PHP,前端使用HTML和Javascript。
发布于 2017-07-20 13:41:34
经过大量的研究,我发现当在文本编辑器中打开时,动画webp图像总是包含一些字符串,而非动画图像则不包含。这些字符串是ANMF和ANIM。我在我拥有的所有webp图像中检查了这些字符串。所以这对我来说是完美的。以下是PHP、Javascript和Shell Script中的一些解决方案
在PHP中:
<?php
function isWebpAnimated($src){
$webpContents = file_get_contents($src);
$where = strpos($webpContents, "ANMF");
if ($where !== FALSE){
// animated
$isAnimated = true;
}
else{
// non animated
$isAnimated = false;
}
return $isAnimated;
}
?>在Javascript中:
function isAnimatedGif(src) {
var request = new XMLHttpRequest();
request.open('GET', src, true);
request.addEventListener('load', function () {
if(request.response.indexOf("ANMF") != -1){
// animated
alert(true);
}
else{
// non animated
alert(false);
}
});
request.send();
}但在大型图像情况下,PHP和Javascript不能很好地工作,所以最好的解决方案是使用Shell Script,如果你有Ubuntu的话。
在Shell脚本中:
echo $(grep -c "ANMF" ~/animated.webp)如果不是动画,则返回0,否则返回非零值。
发布于 2020-04-16 11:14:40
根据Sven Liivak的isWebpAnimated()的说法,有一个小错误。
fseek($fh, 16);
应该是:
fseek($fh, 20);
因为位置16是VP8X中的chunk_size位置。但我们需要20的flag职位。
固定功能:
function isWebpAnimated($fn){
$result = false;
$fh = fopen($fn, "rb");
fseek($fh, 12);
if(fread($fh, 4) === 'VP8X'){
fseek($fh, 20);
$myByte = fread($fh, 1);
$result = ((ord($myByte) >> 1) & 1)?true:false;
}
fclose($fh);
return $result;
}发布于 2018-09-14 21:37:09
在Webp头中有标志,动画等等。检查它的小函数:
function isWebpAnimated($fn){
$result = false;
$fh = fopen($fn, "rb");
fseek($fh, 12);
if(fread($fh, 4) === 'VP8X'){
fseek($fh, 16);
$myByte = fread($fh, 1);
$result = ((ord($myByte) >> 1) & 1)?true:false;
}
fclose($fh);
return $result;
}ANIM和ANMF来自下一个块标头。
https://stackoverflow.com/questions/45190469
复制相似问题