Skip to Content
ModulesPillow TutorialFile Handling with Pillow

File Handling with Pillow

Pillow supports a wide range of file formats, making it versatile for reading, writing, and managing images. This guide covers handling common and large image files efficiently.


Reading Images from Different Formats

Pillow can open images in formats like JPEG, PNG, BMP, GIF, TIFF, and more using the Image.open() method.

Example: Reading an Image

from PIL import Image # Open an image file img = Image.open("example.jpg") # Display image format and size print(f"Format: {img.format}") print(f"Size: {img.size}") img.show()

Supported formats:

  • JPEG (.jpg, .jpeg)
  • PNG (.png)
  • BMP (.bmp)
  • GIF (.gif)
  • TIFF (.tiff)

Writing Images to Various Formats

The save() method allows saving images in different formats. Ensure the format is supported by Pillow.

Example: Saving an Image

# Save the image in another format img.save("example.png")

Example: Saving with Custom Options

# Save with quality and optimization img.save("example_optimized.jpg", quality=85, optimize=True)

Handling Large Image Files

Large images can consume significant memory. Pillow offers methods to handle such files efficiently.

Example: Reducing Image Size

Use the thumbnail() method to resize large images while maintaining aspect ratio.

# Create a thumbnail img.thumbnail((800, 800)) img.save("example_thumbnail.jpg")

Example: Loading Images Lazily

Open images in draft mode for lower resolution.

# Open image in draft mode img = Image.open("large_image.jpg") img.draft("RGB", (800, 800)) print(f"Draft size: {img.size}") img.show()

Example: Converting to Grayscale to Reduce Size

# Convert to grayscale img_gray = img.convert("L") img_gray.save("example_gray.jpg")

Practical Applications

Example 1: Batch Conversion of Image Formats

Convert all .png files in a folder to .jpg.

import os from PIL import Image input_folder = "images/pngs" output_folder = "images/jpgs" os.makedirs(output_folder, exist_ok=True) for filename in os.listdir(input_folder): if filename.endswith(".png"): img = Image.open(os.path.join(input_folder, filename)) output_file = os.path.join(output_folder, filename.replace(".png", ".jpg")) img.save(output_file)

Example 2: Extracting and Saving Image Metadata

# Extract metadata and save it exif_data = img.getexif() with open("metadata.txt", "w") as f: for tag, value in exif_data.items(): tag_name = Image.ExifTags.TAGS.get(tag, tag) f.write(f"{tag_name}: {value}\n")

Try It Yourself

Problem 1: Resize and Save Multiple Images

Write a script to resize all images in a folder to 600x600 pixels and save them in a new folder.

Show Solution

import os from PIL import Image input_folder = "images" output_folder = "resized_images" os.makedirs(output_folder, exist_ok=True) for filename in os.listdir(input_folder): if filename.endswith(('.jpg', '.png')): img = Image.open(os.path.join(input_folder, filename)) img.thumbnail((600, 600)) img.save(os.path.join(output_folder, filename))

Problem 2: Convert Images to Grayscale

Write a script to convert all .jpg images in a folder to grayscale and save them with a _gray suffix.

Show Solution

import os from PIL import Image input_folder = "images" os.makedirs("grayscale_images", exist_ok=True) for filename in os.listdir(input_folder): if filename.endswith(".jpg"): img = Image.open(os.path.join(input_folder, filename)).convert("L") new_filename = os.path.join("grayscale_images", filename.replace(".jpg", "_gray.jpg")) img.save(new_filename)

Pillow’s robust file handling features make it an excellent tool for managing image formats and efficiently working with large files. Start experimenting to streamline your workflows!

Last updated on