0

我想识别图像的类型以判断它是否是webp格式,但我不能只使用file命令,因为图像作为从互联网下载的二进制文件存储在内存中。PIL到目前为止,我在lib 或imghdrlib中找不到任何方法来执行此操作

这是我不想做的:

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表明imghdrlib 不知道webp类型,那么有什么方法可以webp用 python 确定它是一个图像吗?


作为记录,我使用的是 python 2.7


4

1 回答 1

3

imghdr模块尚不支持 webp 图像检测;它将被添加到 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)
于 2015-01-22T09:42:26.120 回答