Using Python to crop a lot of images

This week our program of study will be holding a short course for kindergarten teachers and village officers located near our campus. As part of the event I was writing a booklet containing a short introduction to Microsoft PowerPoint. I composed a slide for the course and captured more than fifty screenshots. Some of them have slightly different size due to the use of VirtualBox to run Windows.

I realized that Windows Task Bar and Title Bar is not needed, wasting booklet spaces, and may confuse our (very beginning) audiences. So I decided to crop Task Bar and Title Bar out of all those screenshots. But how? Edit it by hand using GIMP? That would be time consuming. Imagine that you have to:

  1. Open an image file inside GIMP
  2. Carefully select an area of the image using the Rectangle Selection tool
  3. Crop the image
  4. Export the image

..And repeat these steps fifty times. How long would it take?

Thanks to Python and its superb image library, Pillow, I was able to complete the process in a matter of minutes. Just need several minutes to read the doc, a few trial and error, and it’s done. Actually the script needed was also very short:

import os
from PIL import Image
flist = os.listdir()
for f in flist:
    gambar = Image.open(f)
    gambar.crop(0, 22, gambar.size[0]-1, gambar.size[1]-31).save('../cropped/' + f)

 

Leave a Reply

%d bloggers like this: