如何使用 Python Imaging Library (PIL) 将上传的图像保存到 FastAPI?

haw*_*waj 2 python python-imaging-library fastapi

我正在使用图像压缩来减小图像大小。提交帖子请求时,我没有收到任何错误,但无法弄清楚为什么图像没有保存。这是我的代码:

@app.post("/post_ads")
async def create_upload_files(title: str = Form(),body: str = Form(), 
    db: Session = Depends(get_db), files: list[UploadFile] = File(description="Multiple files as UploadFile")):
    for file in files:
        im = Image.open(file.file)
        im = im.convert("RGB")
        im_io = BytesIO()
        im = im.save(im_io, 'JPEG', quality=50) 
Run Code Online (Sandbox Code Playgroud)

Chr*_*ris 6

PIL.Image.open()视为fp以下参数:

\n
\n

fp\xe2\x80\x93 一个filename(字符串)、pathlib.Path对象或file对象。\n文件对象必须实现file.read()file.seek()和\nfile.tell()方法,并以二进制模式打开。

\n
\n

使用BytesIO流,您需要具有如下所示的内容(如本答案客户端所示所示):

\n
Image.open(io.BytesIO(file.file.read()))\n
Run Code Online (Sandbox Code Playgroud)\n

但是,您实际上不必使用内存中的字节缓冲区,因为您可以使用 的属性获取实际的文件.file对象UploadFile。根据文档

\n
\n

file:一个SpooledTemporaryFile(一个file-like对象)。\n这是实际的 Python 文件,您可以将其直接传递给其他\n需要“类似文件”对象的函数或库。

\n
\n

示例 - 将图像保存到磁盘:

\n
Image.open(io.BytesIO(file.file.read()))\n
Run Code Online (Sandbox Code Playgroud)\n

示例 - 将图像保存到内存字节缓冲区(请参阅此答案):

\n
# ...\nfrom fastapi import HTTPException\nfrom PIL import Image\n\n@app.post("/upload")\ndef upload(file: UploadFile = File()):\n    try:        \n        im = Image.open(file.file)\n        if im.mode in ("RGBA", "P"): \n            im = im.convert("RGB")\n        im.save(\'out.jpg\', \'JPEG\', quality=50) \n    except Exception:\n        raise HTTPException(status_code=500, detail=\'Something went wrong\')\n    finally:\n        file.file.close()\n        im.close()\n
Run Code Online (Sandbox Code Playgroud)\n

有关如何使用 FastAPI 上传文件/图像的更多详细信息和代码示例,请查看此答案此答案。另外,请查看此答案,def了解有关使用或定义端点的更多信息async def

\n