0

I tried to display my edited image with PIL package, when I tried to make it to display on the html <img src=''></img> it doesn't appear anything, but I see the file name on inspect elements was <img src="<_io.BytesIO object at 0x000001EDA8F76E00>">. How do I make the edited image display properly?

app.py

@app.route("/api/games/shipper/image/", methods=["GET"])
def games_shipper():
    ... # My stuff up here
    image_io = BytesIO()
    img.save(image_io, "PNG")
    image_io.seek(0)
    return render_template('image.html', image_data=image_io)

image.html

   ... // My stuff up here
   <body>
      <center>
         <image src="{{ image_data }}"></image>
      </center>
   </body>
Interesting
  • 255
  • 1
  • 4
  • 16

2 Answers2

2

You can read the data from the buffer with the getvalue() function and then convert it. The base64 encoded data can then be passed to the src parameter as a data url.

from base64 import b64encode

@app.route("/api/games/shipper/image/", methods=["GET"])
def games_shipper():
    ... # My stuff up here
    image_io = BytesIO()
    img.save(image_io, 'PNG')
    dataurl = 'data:image/png;base64,' + b64encode(image_io.getvalue()).decode('ascii')
    return render_template('image.html', image_data=dataurl)

If you pass the image as a dataurl, there is no way to shrink the string. However, there is the possibility of serving the file as pure image data. You can use send_file in another endpoint for this. You serve the page (template) in one endpoint and the image file in a second.

from flask import send_file

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/image')
def game_shipper():
    # ...
    image_io = io.BytesIO()
    img.save(image_io, format='PNG')
    image_io.seek(0)
    return send_file(
        image_io,
        as_attachment=False,
        mimetype='image/png'
    )
  <body>
    <center>
      <img src="{{ url_for('game_shipper') }}" />
    </center>
  </body>
Detlef
  • 6,137
  • 2
  • 6
  • 24
  • Is there by any chance to not make it with very long url `(b64encode)` of the image? – Interesting Jan 26 '22 at 05:51
  • @Interesting I revised my answer. The image is served similarly to when you distribute a static file. I am available for any questions. – Detlef Jan 26 '22 at 15:43
0

You'll need to encode your image in Base64 to display it in the img tag directly, see e.g. How to display Base64 images in HTML

The traditional way to display images in Flask templates is to save the image in Flask's static folder and link to it in your template like so

<body>
      <center>
         <image src="/static/{{image_name}}.png"></image>
      </center>
   </body>
Simeon Nedkov
  • 1,097
  • 7
  • 11