Python library centre
Essential Python Pillow Techniques for Image Processing and Editing
Pillow is a library for opening, editing and saving many different image file formats in Python. It is often used for working with images such as resizing,…
- CoursePython library centre
- Video18 min
- FormatJupyter notebook · 18 code cells
What you'll learn
Data
No separate download needed — the notebook creates or downloads everything it uses.
📓 Full notebook
Download .ipynbIntroduction to Pillow: The Python Imaging Library#
Pillow is a library for opening, editing and saving many different image file formats in Python.
It is often used for working with images such as resizing, cropping, rotating, and converting between formats.
Pillow is valuable in tasks like automating image edits, creating thumbnails, enhancing images, and even generating graphics for the web.
With Pillow, you can process images directly from Python scripts with just a few lines of code.
Real world uses include preparing images for websites, data science projects, game development, and automating reports with images.
import warnings; warnings.filterwarnings("ignore")
import sys
# For Windows, install Pillow using pip:
# pip install Pillow
from PIL import Image
Core Concepts in Pillow#
- The key object in Pillow is the Image object.
- You can open, create, edit, and save images using Image methods.
- Images can be loaded from files or created from scratch.
- Modes define image types: for example, 'RGB', 'L' for grayscale.
- Common workflows: open image, edit image, save image.
# Let us create a simple new RGB image and check its type
img = Image.new('RGB', (100, 100), color='red')
print(type(img))
# Show basic image information
print('Size:', img.size)
print('Mode:', img.mode)
Opening and Viewing Images#
- You can open image files from your computer.
- Pillow supports many formats like PNG, JPEG, GIF, BMP.
- You can quickly view the image using show().
- Example: Load an image from disk and display it.
# Open and view an image (replace with your own image file)
try:
img2 = Image.open('example.jpg')
img2.show()
print('Image opened and shown successfully.')
except FileNotFoundError:
print('Cannot find example.jpg. Please put an image named example.jpg in the current folder.')
Saving Images in Different Formats#
- You can save your images in different file formats.
- Just use the save() method with a filename.
- Example: Save an image as PNG and as JPEG.
# Save the red image in two formats
img.save('red_image.png')
img.save('red_image.jpg')
print('Images saved as red_image.png and red_image.jpg')
# Beginner: Resize an image
img_resized = img.resize((50, 50))
print('Original size:', img.size)
print('Resized size:', img_resized.size)
# Beginner: Rotate an image
img_rotated = img.rotate(45)
img_rotated.save('red_image_rotated.png')
print('Image rotated 45 degrees and saved.')
# Beginner: Convert an image to grayscale
img_gray = img.convert('L')
img_gray.save('red_gray.png')
print('Converted to grayscale and saved as red_gray.png.')
# Intermediate: Crop a region out of the image
left, top, right, bottom = 25, 25, 75, 75
img_cropped = img.crop((left, top, right, bottom))
img_cropped.save('red_cropped.png')
print('Cropped region saved.')
# Intermediate: Combine two images (paste one onto another)
background = Image.new('RGB', (120, 120), color='blue')
foreground = img_cropped
background.paste(foreground, (10, 10))
background.save('combined.png')
print('Combined image saved as combined.png')
# Intermediate: Draw shapes and text
from PIL import ImageDraw, ImageFont
img_draw = Image.new('RGB', (120, 60), color='white')
draw = ImageDraw.Draw(img_draw)
draw.rectangle([10, 10, 110, 50], outline='black', width=2)
draw.text((15, 20), 'Hello!', fill='blue')
img_draw.save('drawing.png')
print('Drawing image saved as drawing.png')
# Advanced: Use filters to blur an image
from PIL import ImageFilter
img_blur = img.filter(ImageFilter.BLUR)
img_blur.save('red_blur.png')
print('Blurred image saved as red_blur.png')
# Advanced: Batch process images in a folder (resize all JPGs)
import glob
for fname in glob.glob('*.jpg'):
img_temp = Image.open(fname)
img_small = img_temp.resize((64, 64))
out_name = 'small_' + fname
img_small.save(out_name)
print('Saved', out_name)
# Advanced: Automatically add a watermark to images
def add_watermark(image_path, watermark_text):
base = Image.open(image_path).convert('RGBA')
txt = Image.new('RGBA', base.size, (255,255,255,0))
d = ImageDraw.Draw(txt)
d.text((10, base.size[1]-30), watermark_text, fill=(0,0,0,100))
watermarked = Image.alpha_composite(base, txt)
return watermarked.convert('RGB')
wm_img = add_watermark('red_image.png', 'Sample Watermark')
wm_img.save('red_image_watermarked.png')
print('Watermarked image saved as red_image_watermarked.png')
Error Handling and Debugging#
- Watch for errors like FileNotFoundError when loading images.
- Check your image mode before editing.
- Always use try-except when working with files.
# Try opening a non-existent file
try:
img3 = Image.open('no_such_file.jpg')
except FileNotFoundError:
print('File not found! Check your filename.')
# Handle wrong image mode for editing
img_gray = img.convert('L')
try:
img_gray.paste(img, (0,0))
except ValueError as e:
print('Error:', str(e))
Best Practices and Common Patterns#
- Always check your file paths and image modes.
- Use with statements or try-except for file handling.
- Reuse code by writing functions.
- Clean up temporary files.
- Save processed images to new files to avoid overwriting originals.
# Use with statement to ensure files are closed
with Image.open('red_image.png') as im:
im_rot = im.rotate(90)
im_rot.save('red_image_rotated90.png')
print('Image rotated 90 degrees and saved.')
Mini Project: Make All Images Square Thumbnails#
- Load every image with .jpg extension.
- Create a square thumbnail for each and save with 'thumb_' prefix.
- Thumbnails help to make small versions of images for websites.
# Mini Project: Create square thumbnails for all JPG images
for fname in glob.glob('*.jpg'):
with Image.open(fname) as im:
size = (64, 64)
thumb = im.copy()
thumb.thumbnail(size)
outname = 'thumb_' + fname
thumb.save(outname)
print('Thumbnail saved as', outname)
Thank You and Next Steps#
- Thanks for learning Pillow! Practice and experiment with your own images.
- Subscribe for more beginner-friendly Python tutorials.
- Leave a comment if you have questions or ideas for new videos.
Found this useful?
All lessons, notebooks and datasets here are free. If they helped you, a coffee keeps new lessons coming.



