Check Image Sizes on Production Websites
Using Python and Pytest to Catch Bloated Images Before They Slow Down Your Site
Large images can slow down page performance and negatively impact user experience. During one of my past QA roles, I created a simple Python function to detect when an image might be too large based on its content length header.
Use Case
Our QA team was tasked with verifying the size of images on the production site to ensure they met
optimization standards. While tools like Lighthouse can highlight these issues, I needed something
scriptable - and Pytest
+ requests
was a lightweight and perfect solution.
Sample Code
Here’s a simplified version of the utility function I used in our automated tests:
import requests
def check_image_size(img_url, base_url="https://www.cryan.com"):
# Construct full URL if necessary
if not img_url.startswith(('http://', 'https://')):
img_url = base_url + img_url if img_url.startswith('/') else base_url + '/' + img_url
try:
response = requests.get(img_url, stream=True)
response.raise_for_status()
# Check content length if provided in headers
content_length = response.headers.get('Content-Length')
if content_length and int(content_length) > 1000:
return f"Image at {img_url} might be too large: Header indicates {int(content_length)/1000}KB"
except Exception as e:
return f"Error checking image size: {e}"
return f"Image at {img_url} appears to be an acceptable size."
How to Use It in Pytest
Integrate this into your test suite by looping through known image paths:
def test_image_sizes():
image_paths = [
"/images/logo.png",
"/media/banner.jpg",
"/assets/hero-large.jpg"
]
for img in image_paths:
result = check_image_size(img)
assert "too large" not in result, result
Pro Tip
Content-Length
header, which isn't always accurate for dynamically
generated or CDN-compressed images. For full accuracy, you could download the stream and measure bytes.
Dependencies
This example uses the requests
library:
pip install requests