Fundamentals 5 min read

Resizing Images with Python Pillow (PIL): A Step-by-Step Tutorial

This tutorial explains how to install the Pillow library, open an image file, resize it to desired dimensions, save the result, and encapsulate the process in a reusable Python function, providing complete code examples for practical image‑processing practice.

Python Programming Learning Circle
Python Programming Learning Circle
Python Programming Learning Circle
Resizing Images with Python Pillow (PIL): A Step-by-Step Tutorial

This article demonstrates how to use Python's Pillow (PIL) library to adjust image dimensions, offering a practical exercise for beginners to improve their coding skills.

Installing Pillow

Run pip install Pillow in the terminal, then verify the installation with from PIL import Image .

Opening an Image

Import the library and open an image file:

<code>from PIL import Image
img = Image.open('0.jpg')
print(img.size)  # prints original size</code>

Resizing the Image

Use the resize() method with the target width and height:

<code>new_img = img.resize((250, 250))
print(new_img.size)  # prints new size
new_img.save('0_new.jpg')  # saves the resized image</code>

Creating a Reusable Function

The following function resizes any image by a scaling factor and saves the result:

<code>def resize_img(input_path, output_path, scale):
    if scale > 0:
        img = Image.open(input_path)
        x, y = img.size
        print('修改前:', img.size)
        new_x, new_y = int(scale * x), int(scale * y)
        new_img = img.resize((new_x, new_y))
        new_img.save(output_path)
        print('修改后', new_img.size)
    else:
        print('缩放比例scale应大于0!!')

# Example usage
resize_img('0.jpg', '0_new.jpg', 0.2)</code>

By following these steps, readers can easily perform image resizing tasks in Python and integrate the logic into larger projects.

image processingCode ExampleTutorialpillowResize
Python Programming Learning Circle
Written by

Python Programming Learning Circle

A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.