我使用 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 发出请求并获取响应并直接处理图像。
另外,如果您知道我可以在上面的代码中进行任何改进以加快速度,也会很有帮助。
任何帮助表示赞赏。