Using Python to Reduce JPEG and PNG Image File Sizes Without Loss of Quality

If you run a website, you’ll want to keep the size of image files down to reduce page load times and to reduce bandwidth consumption.

This example shows how to automatically reduce PNG and JPEG image sizes without loss of quality using the Python Imaging Library (PIL).

This example needs Python 2.7 or later to run.

The script has 3 modes (specified with the –mode option):

  • compress: attempt to reduce size of supported JPEG and PNG images
  • restorebackup: restore the backup of modified image files
  • deletebackup: delete the backup copies of modified image files

The compression is quite conservative as a quick way to reasonably safely reduce the size of a large number of images, but if you are looking to get the best possible reduction in file size, or you have image types not supported by this script, you might want to have a look at Google’s page on image optimization.

Files are renamed to a backup (filename.compressimages-backup) before processing. The restorebackup and deletebackup modes can then be used to either undo the change, or to delete the backup files once you’ve confirmed everything has worked OK.

If the file PIL creates turns out to be larger or the same size as the original, the backup will be restored automatically in compress mode and a message to that effect will be printed. Read-only files will also be warned about and skipped.

In spite of the backup feature built into the script, it would still be advisable to backup your image directory before running it.

If you pass a directory instead of a file name, all .png, .jpg and .jpeg images (regardless of case) will be processed, including in all subdirectories.

You might want to adjust the image compression part of the script to make use of another Python image library or external tool that will get better results for your scenario, and just use the surrounding scaffolding to automate it.

The script can be downloaded from the Softwariness site on Github.

Share on FacebookTweet about this on TwitterShare on Google+Share on LinkedInEmail this to someonePrint this page

Comments are closed