Returning a Pillow image that only exists in memory #1010
-
I have a program that programmatically creates an image using Pillow. I want to return it using Starlite. I tried combining a bit FastAPI-inspired code from Stackoverflow + following the docs a bit, but couldn't get it to work. @get(
"randompic/{lang:str}",
media_type='image/jpeg'
)
def randompic(lang: str) -> io.BytesIO:
img = rdpgen.generate_random_definition_pic(lang)
# return img as bytes
buf = io.BytesIO()
img.save(buf, format="JPEG")
buf.seek(0)
return Response(content=buf, media_type="image/jpeg") If you send a request, then you get the response |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 1 reply
-
Have you tried using a streaming response: https://starlite-api.github.io/starlite/1.48/usage/5-responses/8-streaming-responses/ |
Beta Was this translation helpful? Give feedback.
-
Two things:
Therefore, the fix looks like this: @get(
"randompic/{lang:str}",
media_type='image/jpeg'
)
def randompic(lang: str) -> Response[bytes]:
img = rdpgen.generate_random_definition_pic(lang)
# return img as bytes
buf = io.BytesIO()
img.save(buf, format="JPEG")
buf.seek(0)
return Response(content=buf.read(), media_type="image/jpeg") Alternatively you could do what @Goldziher suggested and stream the file from memory, which depending on its size might be an advantage or a disadvantage. |
Beta Was this translation helpful? Give feedback.
Two things:
io.BytesIO
but aResponse
io.BytesIO
.Therefore, the fix looks like this:
Alternatively you could do what @Goldziher suggested and stream the file from memory, which depending on its size might be an advantage or a disadvantage.