Pillow Getting Started Examples
Using Pillow, you can import Pillow's main modules in the following way:
from PIL import Image, ImageFilter, ImageDraw, ImageFont
Pillow maintains API compatibility with PIL, which means most code written for PIL can be used directly with Pillow by simply changing the import statement from import PIL to from PIL import ....
Basic Image Operations
Loading and Displaying Images
Test image (download to local for testing):
Example
from PIL import Image
# Open image (supports JPEG, PNG, GIF, etc.)
img = Image.open("tiger.jpeg")
# Display image (system default image viewer)
img.show()
# Get image information
print("Format:", img.format) # JPEG/PNG
print("Size:", img.size) # (width, height)
print("Mode:", img.mode) # RGB/L/CMYK
Output example:
Format: JPEG Size: (987, 987) Mode: RGB
Analysis:
Image.open()reads an image file and returns anImageobject.show()calls the system default image viewer to display the image (for debugging only, not recommended for production environments).format,size, andmodeare metadata attributes of the image.
Saving Images
The following code saves an image in different formats: one as "example.png" converted to PNG format, and another as "example_quality.jpg" with JPEG quality set to 95.
Example
from PIL import Image
# Open image (supports JPEG, PNG, GIF, etc.)
img = Image.open("tiger.jpeg")
# Display image (system default image viewer)
img.show()
# Get image information
print("Format:", img.format) # JPEG/PNG
print("Size:", img.size) # (width, height)
print("Mode:", img.mode) # RGB/L/CMYK
# Save in different formats
img.save('example.png') # Convert to PNG format
img.save('example_quality.jpg', quality=95) # Specify JPEG quality
Image Format Conversion
Example
from PIL import Image
img = Image.open("tiger.jpeg")
# Convert to grayscale
gray_img = img.convert("L")
gray_img.save("tiger_gray.png") # Save as PNG
# Convert to RGB (even if original is RGBA)
rgb_img = img.convert("RGB")
rgb_img.save("tiger_rgb.jpg", quality=95) # Quality parameter (1-100)
convert("L")converts the image to grayscale mode (8-bit black and white).save()can specify format (via extension or format parameter),qualitycontrols JPEG compression quality.
Image Processing Operations
Resizing Images
Set fixed width and height:
Example
from PIL import Image
img = Image.open("tiger.jpg")
# Resize dimensions
resized_img = img.resize((400, 300))
resized_img.save("cat_small.jpg")
# Generate thumbnail (maintains aspect ratio)
img.thumbnail((200, 200)) # Modifies in place
img.save("cat_thumbnail.jpg")
Scaling by Ratio
Set scaling ratio:
Example
from PIL import Image
# Open image (supports JPEG, PNG, GIF, etc.)
img = Image.open("tiger.jpeg")
# Scale proportionally
width, height = img.size
scaled_image = img.resize((width//2, height//2))
scaled_image.show()
Cropping and Rotating Images
Example
from PIL import Image
img = Image.open("tiger.jpeg")
# Crop (left, top, right, bottom)
cropped_img = img.crop((100, 100, 500, 400))
cropped_img.save("tiger_cropped.jpg")
# Rotate (90 degrees counter-clockwise)
rotated_img = img.rotate(90, expand=True) # expand prevents cropping
rotated_img.save("tiger_rotated.jpg")
Cropped result:
Rotated result:
crop()parameter is rectangular region coordinates (top-left + bottom-right).rotate(angle)will crop corners by default,expand=Trueautomatically adjusts canvas size.
Image Enhancement and Filters
Applying Filters
Example
from PIL import Image, ImageFilter
img = Image.open("tiger.jpeg")
# Blur filter
blurred_image = img.filter(ImageFilter.BLUR)
blurred_image.show()
# Edge enhancement
edge_enhanced = img.filter(ImageFilter.EDGE_ENHANCE)
edge_enhanced.show()
Adjusting Brightness and Contrast
Example
from PIL import Image, ImageEnhance
img = Image.open("tiger.jpeg")
# Enhance brightness
enhancer = ImageEnhance.Brightness(img)
bright_image = enhancer.enhance(1.5) # 1.5x brightness
bright_image.show()
# Enhance contrast
enhancer = ImageEnhance.Contrast(img)
contrast_image = enhancer.enhance(2.0) # 2x contrast
contrast_image.show()
Drawing on Images
Drawing Basic Shapes
Example
from PIL import Image, ImageDraw
img = Image.open("tiger.jpeg")
# Create drawing object
draw = ImageDraw.Draw(img)
# Draw rectangle
draw.rectangle([(100, 100), (300, 300)], outline="red", width=5)
# Draw line
draw.line([(0, 0), (500, 500)], fill="blue", width=3)
# Draw circle
draw.ellipse([(200, 200), (400, 400)], outline="green", width=4)
img.show()
Generated image:
Adding Text
You can add text to images, requiring either a font path to be set or using the system default:
Example
from PIL import Image, ImageDraw, ImageFont
img = Image.open("tiger.jpeg")
# Create drawing object
draw = ImageDraw.Draw(img)
# Load font (must exist on system)
font_size = 80 # Set font size
try:
font = ImageFont.truetype("arial.ttf", font_size)
except:
font = ImageFont.load_default(font_size)
draw.text((150, 150), "Hello Tutorial!", fill="red", font=font)
img.show()
Generated image:
Comprehensive Example: Creating Thumbnails and Adding Watermarks
Example
from PIL import Image, ImageDraw, ImageFont
def create_thumbnail_with_watermark(input_path, output_path, size=(200, 200)):
# Open original image
original = Image.open(input_path)
# Create thumbnail
thumbnail = original.copy()
thumbnail.thumbnail(size)
# Add watermark
draw = ImageDraw.Draw(thumbnail)
try:
font = ImageFont.truetype("arial.ttf", 20)
except:
font = ImageFont.load_default()
# Calculate text position (bottom-right), Chinese requires font setting or it will be garbled
text = "WWW."
# Get text dimensions
bbox = draw.textbbox((0, 0), text, font=font)
text_width = bbox - bbox
text_height = bbox - bbox
x = thumbnail.width - text_width - 10
y = thumbnail.height - text_height - 10
# Draw semi-transparent background
draw.rectangle([x-5, y-5, x+text_width+5, y+text_height+5], fill=(0, 0, 0, 128))
# Draw text
draw.text((x, y), text, fill="white", font=font)
# Save result
thumbnail.save(output_path)
print(f"Thumbnail saved to {output_path}")
# Usage example
create_thumbnail_with_watermark("tiger.jpeg", "thumbnail.jpg")
Generated thumbnail:
FAQ
Q1: How to handle image formats that Pillow cannot recognize?
A1: Pillow supports most common image formats. If you encounter an unsupported format, try installing additional decoders or convert the image to a supported format (such as PNG or JPEG) first.
Q2: How to batch process multiple image files?
A2: You can use Python's glob module with a loop for batch processing:
Example
import glob
from PIL import Image
for file in glob.glob("images/*.jpg"):
img = Image.open(file)
# Process image...
img.save(f"processed_{file}")
Q3: How to handle large images without running out of memory?
A3: For very large images, you can use the Image object's load() method to process block by block, or use ImageOps.fit() to limit the processing area.
Through the above examples and explanations, you should now have mastered the basic usage of Pillow. Pillow is powerful, so practice and explore more of its advanced features!
YouTip