[英]How to return a list of PIL image files from fastapi response?
I have created an rest-api using fastapi, which takes a document (pdf) as input and return a jpeg image of it, I am using a library called docx2pdf for conversion.我使用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
This is the output of doc_results
, basically a list of PIL image files这是 doc_results 的doc_results
,基本上是 PIL 图像文件的列表
[<PIL.PpmImagePlugin.PpmImageFile image mode=RGB size=2975x3850 at 0x7F5AB4C9F9D0>, <PIL.PpmImagePlugin.PpmImageFile image mode=RGB size=2975x3850 at 0x7F5AB4C9FB80>]
If I run my current code, it is returning the doc_results as json output and I am not being able to load those images in another API.如果我运行我当前的代码,它将返回 doc_results 作为 json output 并且我无法将这些图像加载到另一个 API 中。
How can I return image files without saving them to local storage?如何返回图像文件而不将它们保存到本地存储? So, I can make a request to this api and get the response and work on the image directly.所以,我可以向这个 api 发出请求,并得到响应并直接处理图像。
Also, if you know any improvements I can make in the above code to speed up is also helpful.此外,如果您知道我可以在上述代码中进行的任何改进以加快速度,也会有所帮助。
Any help is appreciated.任何帮助表示赞赏。
You can not return that unless you convert it to something universal.除非您将其转换为通用的东西,否则您无法返回它。
<PIL.PpmImagePlugin.PpmImageFile image mode=RGB size=2975x3850 at 0x7F5AB4C9F9D0 <PIL.PpmImagePlugin.PpmImageFile 图像模式=RGB 大小=2975x3850 在 0x7F5AB4C9F9D0
This basically says, You have an object of PIL at your memory here is the location for it .这基本上是说,你的 memory 有一个 PIL 的 object 这里是它的位置。
The best thing you can do is, convert them to bytes and return an array of bytes.您可以做的最好的事情是将它们转换为字节并返回一个字节数组。
You can create a function that takes a PIL image and returns the byte value from it.您可以创建一个 function 获取 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()
Then you can use this function when returning the response然后你可以在返回响应时使用这个 function
return [get_bytes_value(image) for image in doc_results] if doc_results else None
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.