There are some clients who will inadvertently upload png files to their site. Although they are fantastic quality, they’re also fantastically large in file size. When you own an online shop and all your products are .png, you’re going to have additional loading for no reason.

I recently had the pleasure of having 5000 transparent product images being upload by a client. This meant that durin the busy hours of the day, the bandwidth of the site was starting to get out of hand. I knew we needed to do something drastic.

Luckily, if you can install Imagemagick, then you’re just a few commands away from being able to convert everything into jpg and flatten transparent images with a white background.

Here are the steps to get things optimised

Note: Do this locally before running this on your server – although I have included a backup of your images, you can still accidentally delete everything! Make sure you’ve tested this out before going near your live server

  1. Navigate your way into your uploads folder

    cd wp-content/uploads

  2. Start by removing all images that wordpress has generated, otherwise the conversion process takes forever.

    find -E . -type f -iregex '.*[0-9]{2,3}x[0-9]{2,3}.*\.(jpg|jpeg|png|eps|gif)' -exec rm {} \;

  3. Backup time: Compress all original images incase things go wrong on this next bit

    find . -type f | egrep -vi '.*[0-9]{2,3}x[0-9]{2,3}.*\.(jpg|jpeg|png|eps|gif)' | zip -@

  4. Convert everything left from png to jpg, replacing transparent areas with white

    find . -name "*.png" -exec mogrify -background white -flatten -format jpg {} \;

  5. Remove all remaining pngs to leave only jpg, this helps free up server space

    find -E . -type f -iregex '.*\.(png)' -exec rm {} \;

  6. Run this SQL Query to rename all png to jpg. Remember to get that database prefix correct before running this wp_postmeta will be different if you change your wp-config.php

    UPDATE wp_postmeta SET meta_value = REPLACE(meta_value, ".png", ".jpg") WHERE meta_key = '_wp_attached_file' AND meta_value like '%.png'

  7. Regenerate all your media. If you use wpcli, you can simply run wp media regenerate. If you don’t, install a plugin like Force Regenerate Thumbnails and regenerate all your media.

Everything has now been converted from png to jpg & regenerated by wordpress. That should have optimised the load of your site & saved you a headache during those rush hours.

Any problems, tweet me @yratof