Display Images in HTML with Python: A Step-by-Step Guide (2026)
Learn to display images in HTML using Python. This guide covers setting up a Flask app for image uploads and rendering them on web pages effectively.
Display Images in HTML with Python: A Step-by-Step Guide (2026)
Displaying images in an HTML page using Python is a common task for many developers, especially those who work with web applications. Whether you want to dynamically render images or enable users to upload and view images, understanding how to bridge Python and HTML is key. This guide will walk you through the process, highlighting the essential steps and providing practical code examples.
Key Takeaways
- Learn how to serve images using a Python web server.
- Understand how to dynamically render images in HTML.
- Get insights into handling image uploads and displaying them on a webpage.
- Discover common pitfalls and troubleshooting techniques.
Prerequisites
- Basic knowledge of Python and HTML.
- Python 3.8 or later installed on your system.
- A basic text editor or IDE for writing code.
- Familiarity with Python's Flask web framework is a plus.
Step 1: Set Up Your Python Environment
Before we begin, it's important to ensure your Python environment is ready. We'll use Flask, a lightweight web framework, to serve HTML pages and images.
pip install FlaskStep 2: Create a Basic Flask Application
Start by setting up a simple Flask application. This application will handle HTTP requests and serve HTML content.
from flask import Flask, render_template, request, redirect, url_for
import os
app = Flask(__name__)
UPLOAD_FOLDER = 'static/uploads/'
@app.route('/')
def index():
return render_template('index.html')
if __name__ == '__main__':
if not os.path.exists(UPLOAD_FOLDER):
os.makedirs(UPLOAD_FOLDER)
app.run(debug=True)In this code, we create a basic Flask app with a route to the home page. We also define an upload folder for storing images.
Step 3: Develop the HTML Form for Image Upload
Next, create an HTML form that allows users to upload images. This form will be served by the Flask application.
<!DOCTYPE html>
<html>
<body>
<form action="/upload" method="post" enctype="multipart/form-data">
<p>File: <input type="file" name="file" /></p>
<p><input type="submit" value="Upload" /></p>
</form>
</body>
</html>This form uses the POST method to submit files to the '/upload' route, which we will define next.
Step 4: Handle Image Uploads in Flask
We need to extend our Flask application to handle image uploads and display the image back to the user.
from flask import send_from_directory
@app.route('/upload', methods=['POST'])
def upload_file():
if 'file' not in request.files:
return redirect(request.url)
file = request.files['file']
if file.filename == '':
return redirect(request.url)
if file:
filename = file.filename
file.save(os.path.join(UPLOAD_FOLDER, filename))
return redirect(url_for('uploaded_file', filename=filename))
@app.route('/uploads/<filename>')
def uploaded_file(filename):
return send_from_directory(UPLOAD_FOLDER, filename)Here, we handle the file upload by saving the image to the UPLOAD_FOLDER and then redirecting the user to a URL where they can view the uploaded image.
Step 5: Display the Uploaded Image
To display the uploaded image, update the HTML template to include a tag for the image.
<img src="{{ url_for('uploaded_file', filename=filename) }}" alt="Uploaded Image">This code snippet uses Flask's url_for() function to generate a URL for the uploaded image, which is then embedded in the HTML page.
Common Errors/Troubleshooting
- File Not Found Error: Ensure that the UPLOAD_FOLDER directory exists and has the correct permissions.
- Invalid File Type: Implement file type checking to ensure only images are uploaded.
- Large File Uploads: Configure Flask to handle larger files by adjusting its limits in the configuration.
Conclusion
By following these steps, you can effectively display images in HTML using Python. This guide provides a comprehensive approach to handling image uploads and rendering them on the web, making it a valuable technique for any web developer's toolkit.
Frequently Asked Questions
Can I use Django instead of Flask for this?
Yes, Django can also be used to handle file uploads and render images. The principles are similar, but Django's setup and routing differ slightly.
How can I restrict file types to images only?
You can check the file's extension and MIME type before saving it to ensure it is an image.
What if I encounter a 'File Not Found' error?
Ensure the upload directory exists and the file path is correct. Also, check for any typos in the filename or path.