我使用docx2pdf创建了一个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发出请求,直接得到响应并处理图像。
另外,如果您知道我可以在上面的代码中进行任何改进,以加快速度也是有帮助的。
任何帮助都是非常感谢的。
发布于 2021-01-06 14:49:44
除非你把它转换成通用的东西,否则你不能返回它。
这基本上是说,,您的内存中有一个PIL对象,这里是的位置。
您能做的最好的事情就是将它们转换为字节并返回一个字节数组。
您可以创建一个函数,该函数接受PIL图像并从中返回字节值。
import io
def get_bytes_value(image):
img_byte_arr = io.BytesIO()
image.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 Nonehttps://stackoverflow.com/questions/65597315
复制相似问题