Back to Python
2026-02-166 min read

Responsive Images (Python Programming)

Learn Responsive Images (Python Programming) step by step with clear examples and exercises.

Why This Matters

In today's digital world, creating a seamless user experience across various devices is crucial. Responsive web design plays an essential role in achieving this goal, especially when it comes to images. By learning how to create responsive images using Python programming, you will be able to improve the performance and user experience of your web applications on different screen sizes.

Prerequisites

To follow along with this tutorial, you should have a basic understanding of Python (version 3.x) and HTML. Familiarity with CSS media queries will also be helpful but is not required. If you are new to Python or need a refresher, check out our Python for Beginners series.

Core Concept

Responsive images are designed to adapt their size based on the device's screen size. This can be achieved using various techniques, such as using different image sizes for different devices or using CSS media queries. In this tutorial, we will focus on creating responsive images using Python and HTML.

The idea is to generate multiple versions of an image with different dimensions and serve the appropriate one based on the screen size. This can be done by analyzing the user agent string sent by the browser and matching it against predefined breakpoints.

Here's a high-level overview of the process:

  1. Create multiple images of different sizes for various screen resolutions.
  2. Use Python to analyze the user agent string sent by the browser.
  3. Serve the appropriate image based on the detected screen resolution.
  4. Optionally, use CSS media queries to enhance the responsiveness and adaptability of the images within the web page.

Let's dive into the details and write some code!

Worked Example

First, let's create multiple versions of an image for different screen resolutions. For this example, we will use a 500x500 pixel image as our base image. We will create smaller versions for mobile devices (320x480), tablets (768x1024), and large desktops/laptops (1366x768).

mkdir images
cd images
convert input.jpg -resize 320x480 output_mobile.jpg
convert input.jpg -resize 768x1024 output_tablet.jpg
convert input.jpg -resize 1366x768 output_desktop.jpg

Now that we have our images, let's write some Python code to serve the appropriate image based on the user agent string.

from http import Cookies
import os
from PIL import Image
import re

def get_user_agent():

Simulate getting user agent from request headers

In a real-world scenario, you would extract this information from the incoming request

return 'Mozilla/5.0 (Linux; Android 10; SM-G973F Build/QP1A.190711.020) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.88 Mobile Safari/537.36'

def get_screen_resolution(user_agent):

Define breakpoints for different screen resolutions

mobile = re.compile('Android|iPhone|SymbianOS|Windows Phone|iPad|iPod')

tablet = re.compile('Motorola Xoom|Dell Streak 7|BlackBerry Tablet|PlayBook|HTC HD|WebOS|Samsung Galaxy Tab')

desktop = re.compile('Desktop|Laptop|Macintosh|PC|Linux')

if mobile.search(user_agent):

return 'mobile'

elif tablet.search(user_agent):

return 'tablet'

elif desktop.search(user_agent):

return 'desktop'

else:

return None # Unknown device

def serve_image(user_agent, images_dir='images'):

screen_resolution = get_screen_resolution(user_agent)

if screen_resolution == 'mobile':

image_file = f'{images_dir}/output_mobile.jpg'

elif screen_resolution == 'tablet':

image_file = f'{images_dir}/output_tablet.jpg'

elif screen_resolution == 'desktop':

image_file = f'{images_dir}/output_desktop.jpg' # Serve the original image for desktop devices

else:

image_file = f'{images_dir}/input.jpg' # If we can't detect the device, serve the original image

with open(image_file, 'rb') as f:

image_data = f.read()

response = {

'Content-Type': 'image/jpeg',

'Content-Length': len(image_data)

}

return response, image_data

def main():

user_agent = get_user_agent()

screen_resolution = get_screen_resolution(user_agent)

if screen_resolution:

print(f'Serving {image_file} for {screen_resolution} device.')

response, image_data = serve_image(user_agent)

headers = [(k, v) for k, v in response.items()] + [('Set-Cookie', 'session=1234567890; Path=/')]

print('\n'.join('{}: {}'.format(*header) for header in headers))

print()

print(image_data)

else:

print('Unable to detect the device. Serving default image.')

if __name__ == '__main__':

main()


In this code, we first define a function `get_user_agent()` that simulates getting the user agent from request headers. Next, we create a function `get_screen_resolution(user_agent)` that checks if the user agent matches any of our predefined breakpoints for mobile, tablet, and desktop devices using regular expressions.

The `serve_image(user_agent)` function determines which image file to serve based on the screen resolution and returns the appropriate response headers and image data. Finally, in the `main()` function, we call these functions and print out the response headers and image data.

Common Mistakes

  1. Not creating multiple versions of the image for different screen resolutions: To create responsive images, you need to have multiple versions of your base image with different dimensions.
  2. Incorrectly detecting the user agent string: Make sure that your code accurately identifies the device type (mobile, tablet, or desktop) based on the user agent string.
  3. Serving the wrong image for a specific screen resolution: Double-check that you are serving the correct image file for each screen resolution.
  4. Not setting appropriate response headers: Be sure to set the Content-Type header to 'image/jpeg' and the Content-Length header to the length of your image data.
  5. Not considering additional screen resolutions: As devices with different screen sizes continue to emerge, it is essential to keep updating your breakpoints and image sizes to ensure optimal performance for all users.
  6. Ignoring caching mechanisms: Implementing caching can help improve the performance of your solution by reducing the number of times images need to be regenerated for the same user agent.
  7. Not using CSS media queries: While Python can help serve the appropriate image based on the user agent string, you can further enhance the responsiveness and adaptability of the images within the web page by using CSS media queries alongside your server-side solution.

Practice Questions

  1. Modify the code to support additional screen resolutions (e.g., for ultra-large desktops or 4K displays).
  2. Implement a function that generates thumbnails of different sizes automatically based on predefined breakpoints.
  3. Add a caching mechanism so that once an image is served, it doesn't need to be regenerated for the same user agent.
  4. Instead of checking the user agent string, implement a solution using JavaScript and CSS media queries to serve responsive images.
  5. Explore using libraries like Pillow-Slim or ImageMagick to optimize the size of your images without losing quality.
  6. Investigate using server-side solutions like Cloudinary or AWS Amplify for managing and serving responsive images in a production environment.

FAQ

  1. Why not use CSS media queries directly for serving responsive images? While CSS media queries are an effective way to create responsive images, they have limitations when it comes to serving different versions of the same image based on user agent string analysis. Python can help overcome these limitations by dynamically generating and serving appropriate image files.
  2. What if a device doesn't match any of the predefined breakpoints? In such cases, you can serve the original image or create additional breakpoints to cover more devices.
  3. How can I improve the performance of this solution? Implementing caching and serving compressed images (e.g., using gzip) can help improve the performance of this solution. Additionally, optimizing the images themselves (e.g., reducing their size without losing quality) can further enhance performance.
  4. What if a user disables JavaScript in their browser? If JavaScript is disabled, the responsive image solution won't work as intended. However, you can still serve responsive images using server-side techniques or by providing multiple image sources in your HTML and letting the browser choose the appropriate one based on the device capabilities.
  5. Can I use this approach for video files as well? Yes, similar techniques can be applied to serve different versions of video files based on screen size and user agent string analysis. However, keep in mind that video files are typically larger than images, so serving multiple versions may require more resources and careful optimization.
Responsive Images (Python Programming) | Python | XQA Learn