Python Library Spotlight: Pillow

For example, let’s say we have an image called “cat_picture.jpg” in our working directory. We can use the `open()` function from the `PIL` module to load this image into a variable called `image`. Here’s what that code might look like:

# Import the Image module from the PIL library
from PIL import Image

# Use the open() function from the Image module to load an image into a variable called "image"
# The image file name and extension are passed as arguments to the open() function
image = Image.open("cat_picture.jpg")

Once we have our image loaded, we can use various functions to manipulate it however we like! For example, let’s say we want to resize the cat picture so that it’s only 50% of its original size:

# Load the image
image = Image.open("cat.jpg") # Opens the image file and assigns it to the variable "image"

# Resize the image by half (i.e., width and height are both divided by 2)
resized_image = image.resize((int(image.size[0] / 2), int(image.size[1] / 2))) # Uses the resize function to create a new image with dimensions half the size of the original image. The size of the new image is calculated by dividing the original image's width and height by 2. The result is then converted to an integer using the int() function. The new image is assigned to the variable "resized_image".

Or maybe we want to crop out a specific section of the cat picture:

# This script crops out a specific section of an image, in this case, the top-left corner of a cat picture.

# Import the necessary library for image manipulation
import PIL

# Open the cat picture
image = PIL.Image.open("cat_picture.jpg")

# Define the coordinates for the top-left corner of the image
# The first two values represent the starting point (x=0, y=0)
# The last two values represent the ending point (x=50, y=50)
top_left_corner = (0, 0, 50, 50)

# Crop out the top-left corner of the image using the defined coordinates
cropped_image = image.crop(top_left_corner)

# Display the cropped image
cropped_image.show()

And if we want to save our modified cat picture as a new file called “cat_picture_resized.jpg”, we can use the `save()` function:

# Save the resized image using its filename and extension (e.g., "cat_picture_resized.jpg")
# The following code uses the `save()` function to save the modified cat picture as a new file called "cat_picture_resized.jpg"
cropped_image.save("cat_picture_resized.jpg")

Pretty cool, right? And that’s just scratching the surface of what Pillow can do! If you want to learn more about this library and its various functions, I highly recommend checking out their official documentation at https://pypi.org/project/Pillow/.

SICORPS