admin管理员组文章数量:1654275
问题
Python 的 Image.Open(xxx)
遇到如下错误
$ python dev.py
Traceback (most recent call last):
File "dev.py", line 37, in <module>
img_down('aaa', img_url)
File "dev.py", line 12, in img_down
image = Image.open(image_file)
File "C:\Users\\xchenhao\AppData\Local\Programs\Python\Python37-32\lib\site-packages\PIL\Image.py", line 3298, in open
raise UnidentifiedImageError(msg)
PIL.UnidentifiedImageError: cannot identify image file <_io.BytesIO object at 0x01C6C6F0>
原因
图片从网络上下载下来,未加请求头(如 User-Agent)直接请求,网站为了防盗链会进行拦截处理
解决
下载图片时,添加请求头
示例
import requests
import io
from PIL import Image
response = requests.get('https://foo/bar.jpg', headers={
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0',
}).content
image_file = io.BytesIO(response)
image = Image.open(image_file)
with open('bar.jpg', "wb") as f:
image.save(f)
本文标签: 报错UnidentifiedImageErroridentifyPythonPIL
版权声明:本文标题:Python 遇到 PIL.UnidentifiedImageError: cannot identify image file <_io.BytesIO object 报错的解决 内容由热心网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:https://m.elefans.com/xitong/1729650483a1208980.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论