WordPress: How to create image sizes dynamically on the fly

WordPress is awesome. But like any system, it’s not great at everything. One of those things is media image size management, where it just doesn’t work well.

The Problems:

WordPress uses something called “Thumbnail Image Sizes” to maintain different versions of your images in different image sizes. You define these image sizes under Settings -> Media and some custom ones in your theme, as needed.

When you upload an image in your WordPress admin, WordPress automatically generates the thumbnails as soon as the image is uploaded. This causes the following issues:

The image sizes are created forever when you upload an image. In your development process, if you realize that you want to change an image size after thousands of images have been uploaded, the default way is to upload all those images all over again. Fortunately, there are plugins which automatically regenerate thumbnails, but it’s still a hassle.

If you have 20 custom image sizes (maybe 2x, 3x for responsive images), and upload an image in the WordPress admin, it creates 20 thumbnail versions based on the sizes you defined in add_image_size(), even though you might only need one. That means 19 thumbnails in this example would go for a waste. Imagine if you have thousands of images where 19 image thumbnails are created as a waste! This increases the size of the media library unnecessarily.

Solutions:

The solution for changing image sizes as mentioned above, would be to use a plugin to automatically regenerate thumbnails either individually or for all your images. The Regenerate Thumbnails plugin does a great job of this. But this has to be manually done, and isn’t the optimal solution.

Unfortunately, there is no solution for the fact that there will be additional unnecessary images created with the add_image_size() method.

Using the Fly Dynamic Image Resizer:

I was so frustrated with this problem, that I decided to build my own plugin. Introducing: Fly Dynamic Image Resizer for WordPress! If you want to contribute to this plugin, you can do so on Github.

How this plugin works:

You can define image sizes in your theme, or just directly add the image sizes in your code

When a user visits a page for the first time and comes across a dynamic image, the dynamic image thumbnail is created and stored under /wp-content/uploads/fly-images/{image_id}/{image_size}

When users visit the page the next time onwards, they are served the newly created image

If you want to delete all the cached / stored image sizes, you can do so under Tools -> Fly Images

If you want to delete only a single image’s cached / stored image sizes, you can do so in the media library

Defining dynamic image sizes in your theme

You can add as many image sizes in your theme’s functions.php file like so: