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

使用PIL Image.frombytes转换Google Photos图片报错ValueError: not enough image data

解决直接将Google Photos图片转为PIL Image的“not enough image data”错误

你遇到的问题根源在于使用了错误的PIL方法处理图片数据:从Google Photos下载的是压缩格式的图片(如JPEG/PNG),而Image.frombytes搭配raw解码器需要的是未经压缩的原始像素数据(比如RGBA模式下,总字节数必须等于宽×高×4),压缩后的图片字节数远小于这个值,所以会触发数据不足的错误。

修正后的代码

from PIL import Image
import io

for media_item in media_items:
    image_data_response = authed_session.get(media_item['baseUrl'] + "=w500-h250")
    # 将响应字节内容包装为类文件对象
    image_stream = io.BytesIO(image_data_response.content)
    # 让PIL自动识别并解析图片格式
    test = Image.open(image_stream)
    # 若需转为RGBA模式(可选,根据业务需求)
    test = test.convert("RGBA")
    result.append(test)

关键说明

  • io.BytesIO的作用是把字节数据模拟成文件流,让Image.open()可以直接读取,和读取本地图片文件的逻辑一致
  • Image.open()会自动解析图片的格式、尺寸、颜色模式,不需要手动指定,避免了硬编码尺寸或模式带来的错误
  • 如果业务确实需要RGBA格式,用convert("RGBA")转换即可,不要直接用raw解码器处理压缩图片数据

内容的提问来源于stack exchange,提问作者Linda Lawton - DaImTo

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 00:27:12