Working with Image Metadata in Pillow
Image metadata, including EXIF (Exchangeable Image File Format) data, contains information like camera settings, geolocation, and timestamps. Pillow provides tools to access and modify metadata.
Accessing Metadata
The getexif()
method retrieves metadata from an image.
Example: Reading EXIF Data
from PIL import Image
# Open an image
img = Image.open("example.jpg")
# Get EXIF data
exif_data = img.getexif()
# Display EXIF tags and values
for tag_id, value in exif_data.items():
tag_name = Image.ExifTags.TAGS.get(tag_id, tag_id)
print(f"{tag_name}: {value}")
Modifying Metadata
EXIF data can be modified using the getexif()
and save()
methods.
Example: Modifying Metadata
# Add or modify a metadata tag
exif_data[270] = "New Description" # 270 corresponds to the 'ImageDescription' tag
# Save the image with updated metadata
img.save("modified_example.jpg", exif=exif_data)
Saving Metadata
When saving an image, you can preserve or update its EXIF metadata.
Example: Save Image with EXIF Metadata
# Save the image while keeping its metadata
img.save("saved_with_metadata.jpg", exif=exif_data)
Practical Use Cases
Example 1: Extract Camera Info
# Extract camera-specific details
camera_make = exif_data.get(271, "Unknown") # 271 corresponds to 'Make'
camera_model = exif_data.get(272, "Unknown") # 272 corresponds to 'Model'
print(f"Camera Make: {camera_make}")
print(f"Camera Model: {camera_model}")
Example 2: Remove Metadata
# Save an image without metadata
img.save("no_metadata_example.jpg")
Try It Yourself
Problem 1: Extract Date and Time
Write a script to extract the date and time a photo was taken from its metadata.
Show Solution
from PIL import Image
# Open an image
img = Image.open("photo.jpg")
# Get EXIF data
exif_data = img.getexif()
# Extract date and time
date_time = exif_data.get(306, "Unknown") # 306 corresponds to 'DateTime'
print(f"Date and Time: {date_time}")
Problem 2: Add Custom Metadata
Write a script to add a custom description to an image’s metadata and save it.
Show Solution
from PIL import Image
# Open an image
img = Image.open("photo.jpg")
# Get EXIF data
exif_data = img.getexif()
# Add a custom description
exif_data[270] = "Vacation photo in the mountains" # 270 corresponds to 'ImageDescription'
# Save the updated image
img.save("updated_photo.jpg", exif=exif_data)
Working with image metadata enables you to access and modify valuable information stored within images. Use these tools for tasks like organizing photos, adding descriptions, or anonymizing metadata for sharing.