DEV Community

mary kariuki
mary kariuki

Posted on

How to Resize an Image in Python Using PIL (Pillow)

Resizing images is a common task in data processing, web development, and automation. In Python, this can be done easily using the PIL (Pillow) library.

This guide will walk you through the process step by step using real examples.

This guide will walk you through the process step by step using real examples.


📦 Prerequisites

Before you begin, ensure that Pillow is installed:

pip install pillow
Enter fullscreen mode Exit fullscreen mode

Step 1: Import the Library

Start by importing the Image module from PIL:

>>> from PIL import Image
Enter fullscreen mode Exit fullscreen mode

Step 2: Open an Image

You need to specify the full path to your image:

>>> img =Image.open(r"C:\Users\User\OneDrive\Documents\Stocktaking in a busy pharmacy (1).png")
Enter fullscreen mode Exit fullscreen mode

Step 3: Resize the Image

You can resize the image by specifying the width and height (in pixels).

Resize to 200x200

>>> image_resize =img.resize((200,200))
>>> image_resize.save(r"C:\Users\User\OneDrive\Documents\Stocktaking in a busy pharmacy (2).png")
>>> image_resize.show()
Enter fullscreen mode Exit fullscreen mode

Resize to 100x100

>>> image_resize =img.resize((100,100))
>>> image_resize.save(r"C:\Users\User\OneDrive\Documents\Stocktaking in a busy pharmacy (3).png")
>>> image_resize.show()
Enter fullscreen mode Exit fullscreen mode

Working with Another Image

You can repeat the same process with a different image:

>>> from PIL import Image
>>> img =Image.open(r"C:\Users\User\OneDrive\Documents\Gemini_Generated_Image_yd8egyd8egyd8egy.png")
>>> image_resize =img.resize((100,100))
>>> image_resize.save(r"C:\Users\User\OneDrive\Documents\Gemini_Generated_Image_yd8egyd8egyd8egy(1).png")
>>> image_resize.show()
Enter fullscreen mode Exit fullscreen mode

Important Notes

  • Always include the full file path and file extension (.png, .jpg, etc.).
  • Ensure the file exists in the specified location.
  • Python is case-sensitive, so Image must be written with a capital I.
  • Use r"" before the file path to avoid issues with backslashes.

Conclusion

Resizing images in Python using PIL is simple and efficient. With just a few lines of code, you can automate image processing tasks and handle multiple image sizes for different use cases.


Top comments (0)