【问题标题】:How to return a list of PIL image files from fastapi response?如何从 fastapi 响应中返回 PIL 图像文件列表?
【发布时间】:2021-01-06 14:09:55
【问题描述】:

我使用 fastapi 创建了一个 rest-api,它以文档 (pdf) 作为输入并返回它的 jpeg 图像,我正在使用一个名为 docx2pdf 的库进行转换。

from docx2pdf import convert_to    
from fastapi import FastAPI, File, UploadFile

app = FastAPI()

@app.post("/file/convert")
async def convert(doc: UploadFile = File(...)):
    if doc.filename.endswith(".pdf"):
        # convert pdf to image
        with tempfile.TemporaryDirectory() as path:
            doc_results = convert_from_bytes(
                doc.file.read(), output_folder=path, dpi=350, thread_count=4
            )

            print(doc_results)

        return doc_results if doc_results else None

这是doc_results的输出,基本上是PIL图像文件的列表

[<PIL.PpmImagePlugin.PpmImageFile image mode=RGB size=2975x3850 at 0x7F5AB4C9F9D0>, <PIL.PpmImagePlugin.PpmImageFile image mode=RGB size=2975x3850 at 0x7F5AB4C9FB80>]

如果我运行我当前的代码,它会将 doc_results 作为 json 输出返回,我无法在另一个 API 中加载这些图像。

如何在不将图像文件保存到本地存储的情况下返回图像文件?所以,我可以向这个 api 发出请求并获得响应并直接处理图像。

此外,如果您知道我可以对上述代码进行任何改进以加快速度,也会有所帮助。

感谢任何帮助。

【问题讨论】:

    标签: python python-3.x python-imaging-library fastapi uvicorn


    【解决方案1】:

    除非你把它转换成通用的东西,否则你不能返回它。

    这基本上是说,你有一个 PIL 对象在你的记忆中,这是它的位置

    您能做的最好的事情是将它们转换为字节并返回一个字节数组。


    您可以创建一个函数来获取 PIL 图像并从中返回字节值。

    import io
    
    def get_bytes_value(image):
        img_byte_arr = io.BytesIO()
        img.save(img_byte_arr, format='JPEG')
        return img_byte_arr.getvalue()
    

    那么在返回响应的时候就可以使用这个函数了

    return [get_bytes_value(image) for image in doc_results] if doc_results else None
    

    【讨论】:

    • 你能提供一些示例代码来帮助我吗,我从过去几个小时一直在尝试实现它,但到目前为止无法弄清楚我们如何返回字节数组?跨度>
    • 我收到一个错误UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte,我已经尝试过这个解决方案,但对我没有用。
    • 您是否尝试过来自此question 的该错误的解决方案?
    • 我能够找出问题所在,我必须使用 base64 编码。
    • 啊,太好了,很高兴它有帮助。
    猜你喜欢
    • 1970-01-01
    • 2019-09-16
    • 1970-01-01
    • 2022-08-10
    • 2020-05-02
    • 2014-03-28
    • 1970-01-01
    • 1970-01-01
    • 2020-07-24
    相关资源
    最近更新 更多