Bulk resizing images with Pillow
One of my customers contacted me and asked if I do have a way to resize images for the thumbails of the eCommerce I've created for her.
Of course there's tons of different apps that may do it for her but I've used the chance to build something that may be usefull and potentially be reused as an API or at least a function to create the thumbnails automatically on upload.
After a quick research I've found that python has a pretty nice library for this purpose called Pillow. I've checked the documentation and that was what I needed.
Project started with settling up the structure:
Quick explanation: thumbnails is the output folder, app is the script itself, and 2 jpegs are source photos that we will soon magically turn into the thumbnails.
Let's start with the script. Before writing any code we need to install the Pillow library:
pip install pillow
Then import it and write a standard boilderplate:
from PIL import Image
from os import walk
if __name__ == "__main__":
Then in the main function let's find all images, (for me the file type is jpg) and loop through all of them excluding background image as it shouldn't be edited:
files = next(walk("."), (None, None, ))
i = 1
for f in files:
if 'jpg' in f and f != "bg.jpg":
image = Image.open(f)
bg_img = Image.open("bg.jpg")
The next step is to calculate the image dimensions based on our own value of the fixed height and actually resize the base image:
fixed_height = 280
height_percent = (fixed_height / float(image.size))
width_size = int((float(image.size) * float(height_percent)))
image = image.resize((width_size, fixed_height), Image.NEAREST)
Technically we couls just go and paste the image on the white background with the code below. It will also add a name which will be a number of the photo and increment the i variable at the bottom to name the next file with the next number:
However, if we would save it the image now, it would be off the center like the example below:
All we need to do is center the image with this line of code then pass the center_pos to the image.paste function:
center_pos = (round((image1_size - 500) / 2)) * -1
Now you can run the code and your thumbnails will be saved in the images directory.
My whole career and life is orbiting the technology. Fan of automation and everything that's making your life and job easier.
I was working in different roles, from a stereotypical IT guy in the company, through IT Support, web development.