Piar
Piar

Reputation: 11

Display image on HTML page using flask

I am trying to display an image from a list of JPEG images into an HTML page. I tried to use the following code on flask :

from flask import Flask, render_template, request
from Daily_runs import func,func_2
import os
import glob


app = Flask(__name__)

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

@app.route('/hello', methods=['POST'])
def hello():
    path = request.form['path']
    func(path)
    func_2()
    images = glob.glob(os.path.join(path,'*.jpg'))
    image = os.path.abspath(images[0])


    return render_template('Image.html', user_image = image)

HTML template code :

<!DOCTYPE html>
<html>
<head>
    <title>Index</title>
</head>
<body>
    <img src={{user_image)}} alt="User Image">
</body>
</html>

The images does not get displayed instead only the alt text is displayed. Tried various other methods listed in this forum but could not succeed. Can anyone help on this ?

Upvotes: 1

Views: 11881

Answers (2)

Ajax1234
Ajax1234

Reputation: 71451

To display images stored locally with flask and render_template, you must ensure that you save the desired images in a static/images folder in the parent directory of your application:

your_project_folder
|  - static/
      - images/
          - your_imagename.jpg
|  -templates
     - Image.html

   -main_app_file.py

Now, in your route:

import os
@app.route('/hello', methods=['POST'])
def hello():
   path = request.form['path']
   func(path)
   func_2()
   image = [i for i in os.listdir('static/images') if i.endswith('.jpg')][0]
   return render_template('Image.html', user_image = image)

In Image.html:

<img src='/static/images/{{user_image}}' alt="User Image">

Upvotes: 3

AHB
AHB

Reputation: 31

Have you tried putting the Jinja code within quotes in the html file?

i.e:

<img src="{{  user_image  }}" alt="User Image">

Also, it could just be a typo here, but there is an extra ")" in the image tag (removed above) which could be causing your issue.

Upvotes: 2

Related Questions