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.

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 🥰!

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!

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 Soft Skills for Programmers: Why They Matter and How to Develop Them

Soft Skills for Programmers: Why They Matter and How to Develop Them

Overview You need a variety of soft skills in addition to technical skills to succeed in the technology sector. Soft skills are used by software professionals to collaborate with their peers effectively and profitably. Finding out more about soft skills and how they are used in the workplace will help you get ready for the job if you are interested in a…

James Phoenix
James Phoenix
Cover Image for What Are Webhooks? And How Do They Relate to Data Engineering?

What Are Webhooks? And How Do They Relate to Data Engineering?

Webhooks are a simple and powerful method for receiving real-time notifications when certain events occur. They enable a whole host of automated and interconnected applications. Broadly speaking, your apps can communicate via two main ways: polling and webhooks.  Polling is like going to a shop and asking for pizza – you have to ask whenever you want it. Webhooks are almost the…

James Phoenix
James Phoenix