问题
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.com/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)
文章讲述了在使用Python的Image.Open处理网络图片时遇到的UnidentifiedImageError,原因是未添加请求头导致网站防盗链拦截。提供了添加User-Agent请求头的示例代码来解决问题。

8645

被折叠的 条评论
为什么被折叠?



