Displaying Images on HTML Page with Flask

A webpage cannot exist without its images. In this tutorial, you will learn how to use Flask, a well-liked Python microweb -framework, for displaying images on an HTML page. The contents include setting up the project structure, serving images, and displaying images in an HTML template with your image.

Displaying  static images

Static images are the local images that are already available on the system. To display static images, we use the url_for method.

Setting up the project Structure

Firstly, we set up the flask directory in this manner:

flask directory
├── app.py
├── static
   └── images
       └── img.jpg
└── templates
    └── index.html

The static folder contains images folder that we will display. The templates folder contain the html page that we want to render as a web page using the flask app running on app.py.

Creating Flask application

We set up the app.py to serve the static image files as follows:

from flask import Flask,render_template,url_for
app=Flask(__name__)
@app.route('/')
def index():
    return render_template('index.html')
if __name__=='__main__':
    app.run(debug=True,port=8000)

Creating HTML template

In the templates folder, we create the index.html page that is rendered using Flask application

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Display Image</title>
</head>
<body>
    <h1>Image Display Example</h1>
    <img src="{{url_for('static',filename='images/img1.jpg')}}" alt="Example Image">
</body>
</html>

Here, we use Jinja templating where we use the url_for function to get the URL of the image located in the static folder in the <img> tag of HTML page.

If we run the app now, we will see the displayed image.

jinja templating in Flask

Displaying Dynamic Images

Dynamic images require the images to be uploaded and then saved to a particular folder from where they are served using a flask application to display them on a web page. For this case, we use a variable to store the image which is itself used in the img tag.

Firstly, we set up the project directory in the same way as mentioned above. Additionally, we set up an ‘uploads’ folder inside the ‘static’ directory. Then we create the flask application like this:

from flask import Flask, render_template, request
import os
 
app = Flask(__name__)
 
upload=os.path.join('static','uploads')
app.config['UPLOAD_DIRECTORY'] =upload
 
@app.route('/', methods=['GET', 'POST'])
def index():
    if request.method == 'POST':
        file = request.files['file']
        image = os.path.join(app.config['UPLOAD_DIRECTORY'], file.filename)
        file.save(image)
        return render_template('index.html', img=image)
    return render_template('index.html')
 
 
if __name__ == '__main__':
    app.run(debug=True, port=9010)

Here, we configure the ‘uploads’ folder path to the ‘UPLOAD_DIRECTORY’  variable. Then, in the index function if the request method is a POST method, the uploaded file is saved and the image variable is sent as a parameter in the render_template function.

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Displaying Image in Flask</title>
</head>
<body>
<form action="/" enctype="multipart/form-data" method="POST">
    <input name="file" type="file"/>
    <input type="submit"/>
</form>
 
{% if img %}
<h1>Uploaded Image</h1>
<img src="{{img}}" alt="">
{% else %}
<h1>Image will be shown here...</h1>
{% endif %}
</body>
</html>

While in the index.html page, we use the img variable as the source in the <img> tag.

On running the application, we get the following output:

Before uploading image

flask HTML page

After uploading image

flask HTML page

Leave a Reply

Your email address will not be published. Required fields are marked *