【发布时间】: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