Image resize/cache routing via .htaccess
14/02/2018
This post is about how to resize, watermark and efficiently serve images on Apache / PHP web server.
The issue
I’ve been posting loads of pictures to my other blog for the last few years, however the thumbnails resize script that I used for generating different size images was passing file request through PHP all the time (I have used TimThumb previously), therefore I thought it was not very efficient and required more computing power than it really should. Finally I got to the point to rethink the approach and implement image size handling in a different way.
Note: approach works on Apache + PHP stack web hosting.
Request handling via .htaccess
Just to give an Idea I’ve added my .htaccess code. The requests handling logic works in the following way:
- Listen to requests that contains i.e. public-images/large/150/150_1518648782_0.jpg
- Checks if the file does not exist
- In case the file does not exist, it passes the image size and path to generate.php
[gist]https://gist.github.com/g86/ede77b9a24760446f982adb986c625a3.js[/gist]
Image resize and watermarking
You may found image resize and watermarking solutions out there on the internet, however as part of the learning process and some fun I wrote a script of my own.
Solution works as follows:
- Non-resized images are stored in the private-images folder, while watermarked images of different sizes are generated into public-images dir.
- File path and size is passed onto generate.php where it is handled
- Depending on a size requested, different image dimensions are picked and the image is resized
- Image brightness average is calculated to decide a brighter or darker watermark is better
- Watermark is placed on the bottom right corner
- New image is written to public-images/large dir
[gist]https://gist.github.com/g86/7a1adf8238f99b914f32af275eb73ceb.js[/gist]