Thumbnail generator
Let us start our discussion of multi-threading in Python with the example of a program used to generate thumbnails of image URLs.
In the example, we are using Pillow, a fork of the Python Imaging Library (PIL) to perform this operation:
# thumbnail_converter.py
from PIL import Image
import urllib.request
def thumbnail_image(url, size=(64, 64), format='.png'):
""" Save thumbnail of an image URL """
im = Image.open(urllib.request.urlopen(url))
# filename is last part of the URL minus extension + '.format'
pieces = url.split('/')
filename = ''.join((pieces[-2],'_',pieces[-1].split('.')[0],'_thumb',format))
im.thumbnail(size, Image.ANTIALIAS)
im.save(filename)
print('Saved',filename)The preceding code works very well for single URLs.
Let us say we want to convert five image URLs to their thumbnails:
img_urls = ['https://dummyimage.com/256x256/000/fff.jpg', 'https://dummyimage.com/320x240/fff/00.jpg', 'https://dummyimage...