Python 遇到 PIL.UnidentifiedImageError: cannot identify image file <_io.BytesIO object 报错的解决

问题

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)