如何用python识别webp图像类型
我想确定图像的类型以判断它是否为如何用python识别webp图像类型,python,image,python-imaging-library,webp,Python,Image,Python Imaging Library,Webp,我想确定图像的类型以判断它是否为webp格式,但我不能仅使用file命令,因为图像以二进制形式存储在内存中,从internet下载。到目前为止,我在PILlib或imghdrlib中找不到这样做的方法 以下是我不想做的: from PIL import Image import imghdr image_type = imghdr.what("test.webp") if not image_type: print "err" else: print image_type
webp
格式,但我不能仅使用file
命令,因为图像以二进制形式存储在内存中,从internet下载。到目前为止,我在PIL
lib或imghdr
lib中找不到这样做的方法
以下是我不想做的:
from PIL import Image
import imghdr
image_type = imghdr.what("test.webp")
if not image_type:
print "err"
else:
print image_type
# if the image is **webp** then I will convert it to
# "jpeg", else I won't bother to do the converting job
# because rerendering a image with JPG will cause information loss.
im = Image.open("test.webp").convert("RGB")
im.save("test.jpg","jpeg")
当这个“test.webp”
实际上是一个webp
图像时,var-image\u-type
是None
,这表明imghdr
lib不知道webp
类型,所以我有没有办法用python确定它是webp
图像
作为记录,我使用的是Python2.7
imghdr
模块尚不支持webp图像检测;是的
将其添加到较旧的Python版本中非常简单:
import imghdr
try:
imghdr.test_webp
except AttributeError:
# add in webp test, see http://bugs.python.org/issue20197
def test_webp(h, f):
if h.startswith(b'RIFF') and h[8:12] == b'WEBP':
return 'webp'
imghdr.tests.append(test_webp)
是的,这个结论是在我的问题中发布的,我不知道有没有任何方法可以识别webp
图像,有没有imghdr
或PIL
?你有没有扩展名为.webp的文件不是webp的?@PadraicCunningham是的,事实上,该文件是直接从internet下载的,因此文件扩展名不可靠,内容类型
也不可靠,如果这是您的意思的话。判断文件是否为webp
的唯一方法是根据其二进制结构,接受的答案提供了一个很好的解决方法。@JashShah:imghdr.test\u webp
从Python 3.5开始就存在了。