Resizing Images in Python Using Python Imaging Library Without Losing Quality

A Simple Tutorial on How to Resize Images in Python with Examples

Arman Ahmed
ILLUMINATION
2 min readJun 18, 2023

--

Made in Canva

📷Images are an integral part of many applications and websites. However, sometimes we need to resize images to fit specific dimensions or reduce their file size. In this tutorial, we’ll explore how to resize images using the Python Imaging Library (PIL) — a popular library for working with images in Python. 💻🐍💡💡

PIL provides a range of functions for manipulating and processing images, including resizing, cropping, rotating, and more. In this tutorial, we’ll focus on how to resize images using PIL.

💻 Installing PIL:

To get started with PIL, you’ll need to install it using pip:

pip install Pillow

Once you’ve installed PIL, you can use it to open an image file and resize it to a new size. Here’s an example of how to resize an image to a fixed width and height using PIL:

🖼️ Resizing Images to a Fixed Size using PIL:

from PIL import Image
import PIL

width = 123
height = 123

image = Image.open('Image.png')
image = image.resize((width, height), PIL.Image.ANTIALIAS)
image.save('resize.png')

In this code, we open an input image file named Image.png using the Image.open() function. We then call the resize() method on the opened image object to resize it to a new width and height of 123 pixels. The ANTIALIAS resampling filter is used to improve the quality of the resized image. Finally, we save the resized image as resize.png using the save() method.

Note that in this example, we’re using fixed values for the width and height of the resized image. If you want to allow users to specify the dimensions of the resized image, you can modify the code to accept user input for the width and height variables.

Overall, this code provides a simple example of how to resize an image using PIL in Python. PIL is a powerful library with many other functions for manipulating and processing images, so feel free to explore other possibilities beyond resizing.

👍 Conclusion:

In conclusion, PIL provides a straightforward and flexible way to resize images in Python. Whether you need to resize images to fit specific dimensions or reduce their file size, PIL can help you achieve your goals. With the code examples provided in this tutorial, you should now be able to get started with resizing images using PIL in no time!🚀💻🐍📐🖼️

--

--

Arman Ahmed
ILLUMINATION

Freelancer, Software developer, and soon-to- be Solopreneur