我想确定一个Image的类型来判断它是否是webp
格式,但我不能只使用file
命令,因为图像以二进制形式存储在内存中从互联网上下载。到目前为止,我找不到任何方法在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_type
为None
,表明imghdr
lib不知道{{1}类型,所以有什么方法可以告诉它是webp
图像肯定与python?
为了记录,我使用的是python 2.7
答案 0 :(得分:2)
imghdr
模块尚不支持webp图像检测;它应该是added to Python 3.5。
在较旧的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)