Feral Cat

Building because fuck it.

Resize Images Programmatically Using Python

Happen to have a ton of giant marketing materials that you need to get down to size for your website? Are you about to release an app and need to resize images down to Google/Apple’s prescribed dimensions? I mean you could always open the images individually in GIMP (my preferred image editor), go into tools, resize the image, click export, choose the quality, the file type, and export orrrrr we could automate the process starting with the following.

My Computer Setup

  • Python3 (Finally getting used to adding parentheses around my print statements )
  • macOS

Getting your Environment Setup

You can find some info on installing pip here. The article actually covers pip installation for Python2 and the Python3 pip installation slightly differs. I’ll be sure to add and link another article in the near future. So assuming you have pip for python3 installed, execute the following to get the latest pillow package up and running:

sudo pip3 install pillow

Programmatically Resizing Images Using Python3

I’ll be covering how to programmatically resize one image at first. The methodology can then be extrapolated for an array of image paths.

from PIL import Image
#This is the path to your image.  If you are in the same directory as the image then you don't need the long ass path just file name
path = 'the/path/to/your/image.jpg'
image = Image.open(path)
#This is where the magic happens.  
#I use int() around the modified heights and widths because resize can only take integers.  
#This does slightly distort image which is negligible on bigger images.
new_image = Image.resize((int(image.width*.5), int(image.height*.5)))
#Now for saving.
new_path = 'the/path/to/your/new_image.jpg'
#This determines the output quality of the image.  
quality = 100
new_image.save(fp = new_path, format = 'JPEG', quality=quality)

You should now see a second image wherever you designated the new_path variable as. If you have a list of images that need the same scaling then create an array of paths and loop through images like so.

imagePathArray = ['path/to/your/array/1', 'path/to/your/array/2', 'path/to/your/array/3']
for element in imagePathArray:
    image = Image.open(path+'.jpg')
    new_image = Image.resize((int(image.width*.5), int(image.height*.5)))
    new_image.save(fp = path + '_new.jpg', format = 'JPEG', 100)

The array lists image names without extensions so I can make new path names too. Cheers!

Leave a Reply

Your email address will not be published. Required fields are marked *