unpack_from requires a buffer of at least 4 bytes for unpacking 4 bytes at offse...
🚨 错误信息
Traceback (most recent call last):
File "/opt/anaconda3/envs/google/lib/python3.12/site-packages/PIL/ImageFile.py", line 374, in load
s = read(read_bytes)
^^^^^^^^^^^^^^^^
File "/opt/anaconda3/envs/google/lib/python3.12/site-packages/PIL/PngImagePlugin.py", line 996, in load_read
cid, pos, length = self.png.read()
^^^^^^^^^^^^^^^
File "/opt/anaconda3/envs/google/lib/python3.12/site-packages/PIL/PngImagePlugin.py", line 178, in read
length = i32(s)
^^^^^^
File "/opt/anaconda3/envs/google/lib/python3.12/site-packages/PIL/_binary.py", line 95, in i32be
return unpack_from(">I", c, o)[0]
^^^^^^^^^^^^^^^^^^^^^^^
struct.error: unpack_from requires a buffer of at least 4 bytes for unpacking 4 bytes at offset 0 (actual buffer size is 0)
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/Users/beihua/Code/gemini/draw.py", line 43, in <module>
response = client.models.generate_content(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/opt/anaconda3/envs/google/lib/python3.12/site-packages/google/genai/models.py", line 5230, in generate_content
response = self._generate_content(
^^^^^^^^^^^^^^^^^^^^^^^
File "/opt/anaconda3/envs/google/lib/python3.12/site-packages/google/genai/models.py", line 3988, in _generate_content
request_dict = _GenerateContentParameters_to_mldev(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/opt/anaconda3/envs/google/lib/python3.12/site-packages/google/genai/models.py", line 1306, in _GenerateContentParameters_to_mldev
for item in t.t_contents(getv(from_object, ['contents']))
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/opt/anaconda3/envs/google/lib/python3.12/site-packages/google/genai/_transformers.py", line 608, in t_contents
_handle_current_part(result, accumulated_parts, content)
File "/opt/anaconda3/envs/google/lib/python3.12/site-packages/google/genai/_transformers.py", line 586, in _handle_current_part
current_part = t_part(current_part)
^^^^^^^^^^^^^^^^^^^^
File "/opt/anaconda3/envs/google/lib/python3.12/site-packages/google/genai/_transformers.py", line 418, in t_part
return types.Part(inline_data=pil_to_blob(part))
^^^^^^^^^^^^^^^^^
File "/opt/anaconda3/envs/google/lib/python3.12/site-packages/google/genai/_transformers.py", line 303, in pil_to_blob
img.save(bytesio, format='PNG')
File "/opt/anaconda3/envs/google/lib/python3.12/site-packages/PIL/Image.py", line 2539, in save
self.load()
File "/opt/anaconda3/envs/google/lib/python3.12/site-packages/PIL/ImageFile.py", line 381, in load
raise OSError(msg) from e
OSError: image file is truncated
🤖 AI解决方案
报错分析报告
1. 错误翻译
原文:struct.error: unpack_from requires a buffer of at least 4 bytes for unpacking 4 bytes at offset 0 (actual buffer size is 0)
译文:结构体错误:unpack_from 需要至少 4 字节的缓冲区来解包 4 字节的数据(偏移量 0 处),实际缓冲区大小为 0
原文:OSError: image file is truncated
译文:操作系统错误:图像文件被截断(不完整)
2. 原因分析
这是一个典型的 图像文件损坏/不完整 问题:- 根本原因:你的 PNG 图像文件可能没有完全下载、保存时被中断,或者文件本身已损坏,导致文件结尾不完整
- 具体位置:错误发生在 PIL(Python Imaging Library)尝试读取 PNG 图像文件时,在解析文件头部信息时发现数据不足(缓冲区大小为 0)
- 错误链:用户程序 → Google Gemini API → PIL 图像处理 → PNG 解析失败
3. 解决方案
有两种修复方案:方案一:尝试修复图像文件(如果文件需要保留)
from PIL import Image
import io
def fix_truncated_image(image_path):
"""
尝试修复截断的图像文件
"""
try:
# 尝试读取并重新保存图像
with open(image_path, 'rb') as f:
image_data = f.read()
# 创建一个新的完整图像文件
image = Image.open(io.BytesIO(image_data))
image.load() # 强制加载所有数据
# 重新保存为完整文件
image.save(f"fixed_{image_path}")
return Image.open(f"fixed_{image_path}")
except Exception as e:
print(f"无法修复图像: {e}")
return None
# 使用示例
fixed_image = fix_truncated_image("your_image.png")
if fixed_image:
# 使用修复后的图像
response = client.models.generate_content(fixed_image)
方案二:重新获取图像文件(推荐)
import requests
from PIL import Image
import io
def download_and_verify_image(url, save_path="image.png"):
"""
下载图像并验证完整性
"""
try:
# 下载图像
response = requests.get(url, stream=True, timeout=30)
response.raise_for_status()
# 写入文件
with open(save_path, 'wb') as f:
for chunk in response.iter_content(chunk_size=8192):
f.write(chunk)
# 验证图像完整性
with Image.open(save_path) as img:
img.verify() # 验证图像数据
img.load() # 加载图像数据
print(f"图像验证成功: {save_path}")
return img
except Exception as e:
print(f"图像下载或验证失败: {e}")
# 删除可能损坏的文件
import os
if os.path.exists(save_path):
os.remove(save_path)
return None
# 使用示例
image = download_and_verify_image("https://your-image-url.com/image.png")
if image:
response = client.models.generate_content(image)
4. ️ 预防措施
# 在使用图像前进行验证
from PIL import Image
def verify_image(image_path):
try:
with Image.open(image_path) as img:
img.verify() # 验证但不加载
img.load() # 完整加载
return True
except Exception:
return False
- 使用
requests 库时启用 stream=True 和超时设置- 下载完成后立即验证文件完整性
- 使用临时文件,验证成功后再移动到最终位置
推荐工具:
file 命令检查文件类型truncate 或文件大小检查PIL.Image.verify() 方法在加载前验证图像