Optimize Images With Python
This little script will run image optimization and resizing on every image file in the folder you put the script into.
This is particularly useful for anyone who’s into building websites and blogging where regular images from your camera or phone are just grossly oversized and too large. For reference I used one of my images that started out as a 6MB file in 4K resolution and ended up being 100kb in 1k width which is the maximum size of my content column on the website I used that for. All without any visible difference in quality.
This little script will save you a lot of time and effort and decrease your page load speeds drastically. You can also set it to overwrite the original images, in which case you would need to check not for the file name but the size to avoid optimizing already optimized images.
It will also save you actual money over using one of the many services that offer image optimization for often egregious prices.
Here is the full script:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 from PIL import Image import PIL import os import glob from resizeimage import resizeimage for root,dirs,file in os.walk(os.getcwd()): for image in file: if image.endswith(('jpg', 'png' )) and not "optimized" in image: img = Image.open(os.path.join(root,image)) img = resizeimage.resize_width(img, 1000, validate=False) img.save(os.path.join(root,"optimized_"+image), optimize=True, quality=30)