How to Automagically Create Thumbnail Images Using Python

in arduino •  7 years ago  (edited)

On my blog at Steemit I have been posting roundups of the best links I have found, either on Steemit itself, or around the web. Formatting these posts takes a bit of effort so I have been looking for ways to make the non-creative work as automated as possible. One of these tasks is creating thumbnails. Turns out it is really easy to do with Python and does not involve calling the command line ImageMagick tool.

All the examples I found talked about using Image. Unfortunately, I immediately had an issue where my version of Python could not find any Image library. You might find it outputs the same error yourself:

ModuleNotFoundError: No module named 'Image'

A solution is to instead use PIL:
pip install pil

That worked great on my dev server, but on my Mac not so much. I got the following error message:

Could not find a version that satisfies the requirement pil (from versions: )
No matching distribution found for pil

Locally I needed to use Pillow instead:
pip3 install pillow

Ta-da, it worked!

thumbnails with python Some thumbnails generated with python

Code

This code will read the JPG images in the current directory and if one does not already exist, generates a thumbnail with T_ filename.

As well as the Image class, we use Glob to make the file path easier:

The glob module finds all the pathnames matching a specified pattern according to the rules used by the Unix shell

import glob
from PIL import Image


# get all the jpg files from the current folder
for infile in glob.glob("*.jpg"):
im = Image.open(infile)
# convert to thumbnail image
im.thumbnail((128, 128), Image.ANTIALIAS)
# don't save if thumbnail already exists
if infile[0:2] != "T_":
  # prefix thumbnail file with T_
  im.save("T_" + infile, "JPEG")8.js"

Authors get paid when people like you upvote their post.
If you enjoyed what you read here, create your account today and start earning FREE STEEM!
Sort Order:  

Follow back bruh

Done :)

Thanks!

Automatically create thumbnail images,I didn't know that. Tnx for sharing.

Hey man maybe you can give me a shout out?

Yep I am following so will keep watching for your posts

Thanks dude