Skip to content

Returning a Pillow image that only exists in memory #1010

Closed Answered by provinzkraut
Vuizur asked this question in Q&A
Discussion options

You must be logged in to vote

Two things:

  1. Your return annotation is incorrect. You are not returning io.BytesIO but a Response
  2. If you want to send a "raw" response, you should provide bytes, not io.BytesIO.

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.

Replies: 2 comments 1 reply

Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
1 reply
@Vuizur
Comment options

Answer selected by Goldziher
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
3 participants