在Python中将webp图像文件转换为jpg时出现错误。

14

我用Python写了一个小程序,将webp格式转换为jpg格式。

import imghdr
from PIL import Image

im = Image.open("unnamed.webp").convert("RGB")
im.save("test.jpg","jpeg")

执行时出现以下错误

No handlers could be found for logger "PIL.ImageFile"
Traceback (most recent call last):
  File "webptopng.py", line 3, in <module>
    im = Image.open("unnamed.webp").convert("RGB")
  File "/usr/local/lib/python2.7/dist-packages/PIL/Image.py", line 2286, in open
    % (filename if filename else fp))
IOError: cannot identify image file 'unnamed.webp'

我已经安装了支持webp格式的pillow库。下面是我的pillow安装输出:

--------------------------------------------------------------------
PIL SETUP SUMMARY
--------------------------------------------------------------------
version      Pillow 3.0.0
platform     linux2 2.7.3 (default, Jun 22 2015, 19:33:41)
             [GCC 4.6.3]
--------------------------------------------------------------------
--- TKINTER support available
--- JPEG support available
*** OPENJPEG (JPEG2000) support not available
--- ZLIB (PNG/ZIP) support available
*** LIBTIFF support not available
--- FREETYPE2 support available
*** LITTLECMS2 support not available
--- WEBP support available
*** WEBPMUX support not available
--------------------------------------------------------------------

请帮助我如何进行。


我从未使用过WebP,但是你的代码“应该”可以工作。你能验证一下“unnamed.webp”是否为有效的WebP文件吗?例如,使用ImageMagick的identifyconvert命令进行验证? - PM 2Ring
1
以下是Linux中file命令的输出:$ unnamed.webp: RIFF (little-endian) data以下是imagemagick的输出:$ convert: no decode delegate for this image format 'unnamed.webp' @ error/constitute.c/ReadImage/532. convert: missing an image filename '/dev/null' @ error/convert.c/ConvertImageCommand/3011. - Sandeep Kumar Singh
抱歉,我应该提到旧版的ImageMagick可能没有WebP支持。我能建议的是,可以进行十六进制转储以检查文件的前12个字节是否与WebP维基百科文章中显示的标题匹配。也可以尝试找一些更多的WebP文件来测试。 - PM 2Ring
文件正确,我已从维基百科验证。 - Sandeep Kumar Singh
4个回答

14

我使用了一个webp格式的图片并测试了您的代码,它与Pillow 2.9一起工作:

$ wget https://www.gstatic.com/webp/gallery3/2_webp_a.webp
>>> from PIL import Image
>>> im = Image.open("2_webp_a.webp").convert("RGB")
>>> im.save("test.jpg","jpeg")

你遇到了 Pillow 3.0 的问题,与你的错误相关,#1474

尝试将 Pillow 从 3.0 降级到 2.9 ,然后再试一次。


1
仍然无法使用Pillow 2.9.0,出现相同的错误。$ pip freeze | grep -i Pillow Pillow==2.9.0 - Sandeep Kumar Singh
你是否尝试过使用相同的webp图片和我使用的相同代码? 以及相同版本的Pillow吗? 如果是的话,我建议你在Pillow的github页面上提出问题。 - Paolo Melchiorre
是的,我已经使用了您提到的相同代码和相同文件。 - Sandeep Kumar Singh
@SandeepKumarSingh 我在 Pillow 的 Github 页面上看到了你的 问题,你的问题是由于你使用了旧版的 webp 库吗? - Paolo Melchiorre

8
这个问题现在已经解决了。我安装了最新的libwebp库,即libwebp-0.4.3,并重新安装了pillow。
如果有人遇到同样的问题,可以参考这里的github问题线程。

2

通过 pip install webptools 安装 webptools,然后执行以下操作:

from webptools import dwebp
print(dwebp("python_logo.webp","python_logo.jpg","-o"))

这个库的工作速度比较慢,但使用起来很容易。


0

使用 webp 加载图像并继续处理

from PIL import Image
import webp

im = webp.load_image('test.webp').convert('RGB')
im.save('test.jpg', 'jepg')

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接