如何用python识别webp图像类型

2024-05-15 05:54:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我想标识一个图像的类型来判断它是否是webp格式,但我不能仅仅使用file命令,因为图像是以二进制形式存储在内存中的,它是从internet下载的。到目前为止,我在PIL库或imghdr库中找不到任何方法来执行此操作

以下是我不想做的事情:

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是{},这表明{}库不知道webp类型,那么有没有什么方法可以让我用python确定它是一个webp图像?在


作为记录,我使用的是python2.7



Tags: the方法test图像imageimport类型if
1条回答
网友
1楼 · 发布于 2024-05-15 05:54:17

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)

相关问题 更多 >

    热门问题