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

FastAPI将UploadFile转为Pillow Image遇识别错误的解决咨询

解决UploadFile转Pillow Image时的PIL.UnidentifiedImageError问题

以下是针对常见出错原因的修复方案:

1. 重置文件读取指针

调用img.file.read()后,文件指针会停在文件末尾,后续再读取会得到空数据。先把文件内容读到字节对象中,再重置指针避免失效:

from fastapi import File, APIRouter, UploadFile
from PIL import Image
from io import BytesIO

api = APIRouter()

@api.post("/myEndPoint")
def process_image(img: UploadFile = File(...)):
    # 读取文件字节内容
    img_bytes = img.file.read()
    # 重置文件指针到开头(后续若需复用img.file时必备)
    img.file.seek(0)
    
    try:
        # 转换为Pillow Image对象
        img_pillow = Image.open(BytesIO(img_bytes))
        # 可选:验证是否为PNG格式
        if img_pillow.format != "PNG":
            return {"error": "仅支持PNG格式图片"}
        # 此处编写你的后续处理逻辑
        return {"status": "success", "image_format": img_pillow.format}
    except Exception as e:
        return {"error": f"图片处理失败: {str(e)}"}

2. 补全FastAPI参数标注

原始代码缺少= File(...)标注,FastAPI需要该标识来正确识别form-data中的文件字段,否则可能无法解析上传的文件。

3. 验证上传文件有效性

  • 检查Postman中form-data的键名是否与代码参数名img完全一致
  • 确认上传的是完整、未损坏的PNG文件,先用本地正常PNG图片测试,排除文件本身问题
  • 可打印len(img_bytes),若长度为0则说明文件未正确上传

4. 用临时文件中转处理

若字节流直接转换存在问题,可先将文件保存到临时文件再用Pillow读取:

from fastapi import File, APIRouter, UploadFile
from PIL import Image
import tempfile
import os

api = APIRouter()

@api.post("/myEndPoint")
def process_image(img: UploadFile = File(...)):
    # 创建临时文件保存上传内容
    with tempfile.NamedTemporaryFile(delete=False, suffix=".png") as tmp_file:
        tmp_file.write(img.file.read())
        tmp_path = tmp_file.name
    
    try:
        img_pillow = Image.open(tmp_path)
        # 此处编写你的后续处理逻辑
        return {"status": "success"}
    finally:
        # 清理临时文件
        os.unlink(tmp_path)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 10:28:24