How to send image generated by PIL to browser with Python Flask?

Sometimes, we want to send image generated by PIL to browser with Python Flask.

In this article, we’ll look at how to send image generated by PIL to browser with Python Flask.

How to send image generated by PIL to browser with Python Flask?

To send image generated by PIL to browser with Python Flask, we can use the StringIO class.

For instance, we write

def serve_pil_image(pil_img):
    img_io = StringIO()
    pil_img.save(img_io, 'JPEG', quality=70)
    img_io.seek(0)
    return send_file(img_io, mimetype='image/jpeg')

@app.route('some/route/')
def serve_img():
    img = Image.new('RGB', ...)
    return serve_pil_image(img)

to create the serve_pil_image that calls send_file with the img_io StringIO object.

We populate it with the image data by writing

pil_img.save(img_io, 'JPEG', quality=70)

Then we use img_io.seek(0) to back to the beginning of the image.

And then we call send_file with img_io and the mimetype to return the image.

Then we call serve_pil_image with the PIL image img to return that as the response in our view.

Conclusion

To send image generated by PIL to browser with Python Flask, we can use the StringIO class.