KeypressingMonkey
KeypressingMonkey Programmer by day, creative writer and 3D artist by night. I write about tech here, I hope you enjoy your stay.

Optimize Images With Python

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)

turn your Microsoft surface into a business

The Microsoft Surface line has finally reached the tipping point for me where I went out and bought one with the primary intention of using it as a productivity and...

turn your Microsoft surface into a business

Why I could not do these on an iPad (sadly) To me the tablet market is incredibly frustrating because we need something that does not exist: a Windows tablet with...

comments powered by Disqus