Pillow

Python allows us to create and edit images using the Pillow library. It allows us to open images, resize them, crop them, rotate them, draw shapes, and save files in different image formats.

Write the from PIL import Image statement at the beginning of every example.


# Opening and displaying an image
image = Image.open("photo.jpg")
image.show()
                                    

# Getting image information
image = Image.open("photo.jpg")
print(image.size) # displaying image dimensions
print(image.format) # displaying image format
print(image.mode) # displaying image color mode
                                    

# Resizing an image
image = Image.open("photo.jpg")
resized = image.resize((300, 300)) # resizing the image
resized.save("resized.jpg") # saving the resized image
                                    

# Cropping an image
image = Image.open("photo.jpg")
cropped = image.crop((50, 50, 200, 200)) # cropping the image
cropped.save("cropped.jpg")
                                    

# Rotating an image
image = Image.open("photo.jpg")
rotated = image.rotate(90) # rotating the image by 90 degrees
rotated.save("rotated.jpg")
                                    

# Converting an image format
image = Image.open("photo.png")
image.save("photo.jpg") # converting PNG to JPG
                                    

# Drawing on an image
from PIL import ImageDraw

image = Image.open("photo.jpg")
draw = ImageDraw.Draw(image) # creating a drawing object
draw.rectangle((50, 50, 200, 200), outline="red", width=3) # drawing a rectangle
image.save("drawn.jpg")