Optimized Images on your Website

Yannik Schmidt
2 min readOct 15, 2020

--

This article is a indirect successor to JavaScript-lazyload. You might want to read this first. To recap: We have designed a JavaScript routine, which will load images based on the view-ports size and position. Previously we have pre-generated those images and returned specific resolutions as static content, now we want to automatically scale images according to URL arguments.

Flask location block

In this guide we assume a media URL will look like this:

image source URL, green=path, red=name of image, blue=parameters

First we need a flask route, note that if you are using the default static location, you cannot send files from outside the ‘static’-directory.

The <path:path> maps the path after picture to the path argument. In addition we evaluate the URL-arguments. The function “generateImage” will be explained in the next section.

Flask location

Re-encoding, resizing and caching

Now we create a function, which will generate an image with the requested specifications from the original and save it to a caching path, which the function then will return.

We use the python module pillow (aka PIL) to resize and re-encode the images, specifically PIL.Image.thumbnail.

Server: generate new image

If you want to add additional headers to the response, you may add this extra step before returning the response.

And that’s it, now our picture-route supports scaling and encoding! As I said in the beginning, you might want to read JavaScript-lazyload for an idea on how to deploy this to your website.

Feel free to send me a mail to share your thoughts!

--

--

Yannik Schmidt

Python programmer at heart, Linux Expert at work, GameDev on my good days, web developer on the bad days.