【问题标题】:how to identify webp image type with python如何用python识别webp图像类型
【发布时间】:2015-03-21 00:54:50
【问题描述】:

我想识别图像的类型以判断它是否为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_typeNone 这表明imghdr 库不知道webp 类型,所以有什么办法可以用 python 确定这是webp 图像吗?


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


【问题讨论】:

  • 是的,这个结论是在我的问题中发布的,我不知道有没有办法识别webp 图像,有或没有imghdrPIL
  • 你有不是 webp 的扩展名为 .webp 的文件吗?
  • @PadraicCunningham 是的,事实上,该文件是直接从互联网上下载的,因此文件扩展名不可靠,content-type 也不可靠,如果这就是您的意思。 确定判断文件是否为webp的唯一方法是根据其二进制结构,接受的答案提供了解决此问题的好方法。

标签: python image python-imaging-library webp


【解决方案1】:

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)

【讨论】:

  • @JashShah: imghdr.test_webp 现在存在,是的,从 Python 3.5 开始。
猜你喜欢
  • 2016-09-26
  • 2019-11-25
  • 2017-05-16
  • 2017-03-28
  • 2012-09-16
  • 1970-01-01
  • 1970-01-01
  • 2019-01-31
  • 1970-01-01
相关资源
最近更新 更多