2

I want to crop my image file using PIL library and display it using Flask and Jinja.

I have tried this code:

@bp.route('/media/<fname>')
def fetch_media(fname):
...
    image = Image.open(path)
    cropped_image = image.crop(box)
    return cropped_image

This gives a TypeError:

The view function did not return a valid response. The return type must be a string, dict, tuple, Response instance, or WSGI callable, but it was a Image.

How can I return the Image to html page?

ROOT
  • 11,363
  • 5
  • 30
  • 45
Juha M
  • 380
  • 3
  • 13
  • Not at a computer, but you need `cropped_image.save()` of type `PNG` into a BytesIO object and then return a `Response` of `bytesio.getvalue()` with MIME-type `image/png` – Mark Setchell Feb 16 '20 at 17:58
  • You can see the BytesIO aspect of saving an image to memory here... https://stackoverflow.com/a/52281257/2836621 – Mark Setchell Feb 16 '20 at 18:03

1 Answers1

3

Untested, but certainly pretty close to this:

import io
from PIL import Image
from flask import Response

....
....
buffer = io.BytesIO()
cropped_image.save(buffer, format="PNG")
return Response(buffer.getvalue(), mimetype='image/png')
Mark Setchell
  • 191,897
  • 31
  • 273
  • 432
  • Yes, that is beatiful and works, thank you! Only there is missing `from flask import Response` clause from your example – Juha M Feb 17 '20 at 12:23
  • I have added it in now - I was assuming you were familiar with all the `flask` stuff as you were already using it :-) Good luck with your project. – Mark Setchell Feb 17 '20 at 12:56