3 min read
Quick Image Editing with Pillow

The other night I had to modify images in bulk to get the graphics right for OpenTun.ing. I guess sometimes we need to process 10-20 images to make sure they are in the same sizes and quality and stuff, you know.

I don’t usually go beyond the operating system provided tools for image manipulation because my image manipulations are super occasional. Simple GUI with a bunch of buttons and controls usually does the job pretty well, not when you have to do it 20 times though.

Instead of looking up another tool for mass image manipulation I’ve fired up a python docker container and mounted the image directory:

docker run --rm -it -v `pwd`:/data -w /data python:3-alpine sh

and installed Pillow right away to jump into the console:

pip install Pillow

After this you can either run python interactively or put your scripts in the same folder as images. Now here’s an example of a short script that resizes the guitar.jpg to 500x500 pixels and saves it in PNG:

from PIL import Image

guitar = Image.open("guitar.jpg")
new_guitar = guitar.resize((500, 500))
new_guitar.save("guitar_500.png")

Guitar in question:

The Guitar

I guess it takes more clicks than typing to resize the image and save it with a new name. Also you have full power of Python on stand-by, so my work was done when:

import os
from PIL import Image

for filename in os.listdir('.'):
    if filename.endswith('.png'):
        with Image.open(filename) as img:
            resized = img.resize((500, 500))
            # and many more manipulations here
            new_filename = filename.rsplit('.', 1)[0] + '_500.png'
            resized.save(new_filename)

I would like to highlight a couple forementioned manipulations here before I wrap up:

It requires minimal use of the graphical utilities or pointer movements, substituting it for comforting key strokes on your keyboard.

Pro tip: you’ll probably end up writing a bunch of disposable scripts, so using AI assistant for is a cherry on top and is actually okay. I didn’t pillage the entire documentation from the module to get things done as I wanted them to.