Get started with WFL

Just pick something below to explore my work, services and more.

Latest Articles
Latest Art
Latest Photo
Latest Music

Stupid-Simple Image Optimization with PHP & GD

April 14, 2019Will Leffert

I finally broke down this weekend and wrote something (somewhat) worth sharing that can be used widely; the Stupid-Simple Image Optimization Script.

Most of the code work I do is extending legacy code, or adding minor functionality to WordPress, anymore. Sure, I've written a number of from-scratch bits of web software, including my own CMS many years ago.

Amusingly enough, my methodology is still the same as it was then: K.I.S.S.

I recently happened upon an issue with a website that wasn't readily solvable with existing code. Photos were being pulled via CSV by a niche system into WordPress, and the photos being pulled were uncompressed. They were sized fine, but even a smaller JPG can be relatively massive in file-size when uncompressed. This becomes a real issue when you're loading up to 5 of these images on the homepage, 10-15 on a listing page, and even 30 on a product page. 30 images at 100kb? That's nearly 3mb of images. Combine that with HTML, CSS, JS, and other imagery on the page, and you've got potential inventory pages pulling in at 4-5MB, depending on everything going on!

So, how do we solve it?

With a stupid-simple image optimization script.

You can grab it on GitHub above, but here's how it works:

The script, when executed, will get all the jpgs and last modified date from a specified folder. It'll then compare that to a json file that is, basically, a running log of images optimized and their last modified date. If the json file doesn't exist, it'll process all the images and create a json file. If there are matches between the images and the json file, then it'll only do the ones not in the original json log. Once it has the list of images to process, it'll go through the array and compress them according to the amount specified, and then save them in the destination folder (which can also be the same as the input folder; that's what was critical about the situation listed above).

The best way to use it is to automate it. CRON is ideal; just place the script in a folder and ensure that it is blocked from access from the outside (.htaccess is your friend if you're running Apache). Honestly, unless you're processing a HUGE load of images or have a REALLY limited server, you can potentially skip this step. Still, better safe than sorry.

I'll probably extent it further at some point. Resizing (a PITA with GD; I avoided Imagemagick due to security concerns). Support for other image types (honestly, really easy to do, but not necessary for my needs). Etc. Number one, however, is keeping it simple. I don't want to overload it with a bunch of code that'll just create additional points of failure.

Untill then, enjoy.