Home > Enterprise >  How can I display PIL image to html with render_template flask?
How can I display PIL image to html with render_template flask?

Time:01-25

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>

CodePudding user response:

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(stream.getvalue()).decode('ascii')
    return render_template('image.html', image_data=dataurl)

CodePudding user response:

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>
  •  Tags:  
  • Related