You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

将图片读取逻辑嵌入类后触发PIL.UnidentifiedImageError问题求助

问题排查:类方法中读取网络图片触发PIL.UnidentifiedImageError

单独的测试代码可正常通过网络请求读取静态图片并保存,但将逻辑嵌入类方法后,触发PIL.UnidentifiedImageError,无法识别图片文件。

测试代码(可正常运行)

import requests
from io import BytesIO
from PIL import Image

master_ip = '192.168.1.10'
url = 'http://' + master_ip + '/liveimage.jpg'
response = requests.get(url=url)
img = Image.open(BytesIO(response.content))
img.save('test.jpg')

类方法代码(触发错误)

import requests
from io import BytesIO
from PIL import Image

class foo:

    def get_image(self) -> None:
     """Read the last image from the web ui."""
     url = 'http://' + self.master_ip + '/liveimage.jpg'
     response = requests.get(url=url)
     img = Image.open(BytesIO(response.content))
     img.save('test1.jpg')

错误栈

Traceback (most recent call last):
  File "/home/anon/code/test_keyence.py", line 9, in <module>
    img = driver.get_image()
  File "/home/anon/code/ambios-drivers/ambidrivers/keyence/sr5000.py", line 487, in get_image
    img = Image.open(BytesIO(response.content))
  File "/home/anon/ambi_venv/lib/python3.9/site-packages/PIL/Image.py", line 3298, in open
    raise UnidentifiedImageError(msg)
PIL.UnidentifiedImageError: cannot identify image file <_io.BytesIO object at 0x7fd0bd0e9630>

排查步骤

1. 验证self.master_ip的正确性

类中self.master_ip可能未被正确初始化,导致拼接后的URL无效,请求返回的不是图片数据(如404页面、错误文本):

  • 在get_image方法中添加URL打印,对比测试代码的URL:
    print(f"Request URL: {url}")
    
  • 确保类实例化时已赋值master_ip:
    class foo:
        def __init__(self, master_ip):
            self.master_ip = master_ip
    
    # 实例化时传入IP
    driver = foo('192.168.1.10')
    driver.get_image()
    

2. 检查请求响应的有效性

请求可能未成功返回图片,比如返回4xx/5xx错误状态码,此时response.content是HTML错误页面而非图片二进制:

  • 在类方法中添加响应检查:
    response = requests.get(url=url)
    response.raise_for_status()  # 触发HTTP错误异常
    print(f"Response status code: {response.status_code}")
    # 打印前10字节判断是否为图片格式(JPG开头为\xff\xd8)
    print(f"First 10 bytes: {response.content[:10]}")
    

3. 统一请求环境

测试代码与类方法的请求环境可能存在差异,比如目标服务器需要特定请求头或会话维持:

  • 添加与测试代码一致的请求头:
    headers = {'User-Agent': 'Mozilla/5.0'}
    response = requests.get(url=url, headers=headers)
    
  • 使用会话保持请求状态:
    class foo:
        def __init__(self, master_ip):
            self.master_ip = master_ip
            self.session = requests.Session()
    
        def get_image(self) -> None:
            url = 'http://' + self.master_ip + '/liveimage.jpg'
            response = self.session.get(url=url)
            # 后续处理逻辑
    

4. 调试响应内容

直接保存响应内容到本地,验证是否为有效图片:

with open('debug_response.bin', 'wb') as f:
    f.write(response.content)

打开该文件,确认是否为可识别的图片,或用文本编辑器查看是否是错误信息。


内容的提问来源于stack exchange,提问作者trycatch22

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 17:17:23