How To Easily Resize & Compress Your Images In Python

James Phoenix
James Phoenix

As different social media platforms often require different image and width formats, resizing images automatically with python can definitely save you time.


Learning Outcomes

  • To learn how to resize a single image.
  • To learn how to resize multiple images within the current working directory.

from PIL import Image
import PIL
import os
import glob

How To Resize A Single Image With Python

As well as compressing an image, we can also re-size the image to be either:

  • A specific base width.
  • A specific base height.
base_width = 360
image = Image.open('example-image.jpg')
width_percent = (base_width / float(image.size[0]))
hsize = int((float(image.size[1]) * float(width_percent)))
image = image.resize((base_width, hsize), PIL.Image.ANTIALIAS)
image.save('resized_compressed_image.jpg')

Now let’s understand the code above line by line:

  1. We set a base width which we would like the image to be.
  2. Then we open the image with Image.open(‘image_name.jpg’)
  3. We calculate the aspect ratio for width by doing: base_width / the images existing width.
  4. This provides us with a ratio number that we can times by the height to get the correct height for producing our base_width.
  5. Then we resize the image based on the two values (base_width and hsize).
  6. The image is then saved with image.save(‘image_name.jpg’).

We can also do the exact opposite and get a specified height with the following code:

base_height = 360
image = Image.open(‘fullsized_image.jpg')
hpercent = (base_height / float(image.size[1]))
wsize = int((float(image.size[0]) * float(hpercent)))
image = image.resize((wsize, base_height), PIL.Image.ANTIALIAS)
image.save(‘resized_image.jpg')

How To Create A Thumbnail Whilst Preserving The Aspect Ratio

It is also possible for us to create a thumbnail image of an image using:

img.thumbnail(size, resample=3, reducing_gap=2.0)

Make this image into a thumbnail.  This method modifies the
image to contain a thumbnail version of itself, no larger than
the given size.  This method calculates an appropriate thumbnail
size to preserve the aspect of the image
picture = Image.open('example-image.jpg')
picture.thumbnail(size=(200,200))
print(picture.size)
# (200, 133)

How To Resize Multiple Images In The Current Working Directory

directory_files = os.listdir()
multiple_images = [file for file in directory_files if 'example' in file and file.endswith(('.jpg', '.png'))]

Firstly we list all of the files and folders inside of the current working directory. Then we find any .jpg and .png files that have the word example in their name.

Unleash Your Potential with AI-Powered Prompt Engineering!

Dive into our comprehensive Udemy course and learn to craft compelling, AI-optimized prompts. Boost your skills and open up new possibilities with ChatGPT and Prompt Engineering.

Embark on Your AI Journey Now!
print(multiple_images)
# ['example-image.jpg', 'example-image-two.jpg']

# Looping over all of the images:

for image in multiple_images:

    img = Image.open(image)
    img.thumbnail(size=(300,300))
    print(img)

    # We would run the command below to save the images:
    # img.save('resized-image_'+image, optimize=True)

Then we loop over every image, open it and then resize the image.


How To Resize & Compress Multiple Images In The Current Workng Directory

However in our scenario, we would like not only to reduce the size of the images but also to compress them, therefore we will add on the following paramter to this line:

img.save('resized-image_'+image, optimize=True, quality=30)
for image in multiple_images:
    img = Image.open(image)
    img.thumbnail(size=(300,300))
    print(img)
    img.save('resized-image_'+image, optimize=True, quality=30)

Now you can easily both resize and compress your images using Python 🥰!

In the next tutorial you’ll learn how to convert jpg and png images to next generation image formats such as .webp 🔥


More Stories

Cover Image for Why I’m Betting on AI Agents as the Future of Work

Why I’m Betting on AI Agents as the Future of Work

I’ve been spending a lot of time with Devin lately, and I’ve got to tell you – we’re thinking about AI agents all wrong. You and I are standing at the edge of a fundamental shift in how we work with AI. These aren’t just tools anymore; they’re becoming more like background workers in our digital lives. Let me share what I’ve…

James Phoenix
James Phoenix
Cover Image for Supercharging Devin + Supabase: Fixing Docker Performance on EC2 with overlay2

Supercharging Devin + Supabase: Fixing Docker Performance on EC2 with overlay2

The Problem While setting up Devin (a coding assistant) with Supabase CLI on an EC2 instance, I encountered significant performance issues. After investigation, I discovered that Docker was using the VFS storage driver, which is known for being significantly slower than other storage drivers like overlay2. The root cause was interesting: the EC2 instance was already using overlayfs for its root filesystem,…

James Phoenix
James Phoenix