CodeGym /Courses /Python SELF EN /Working with Metadata

Working with Metadata

Python SELF EN
Level 46 , Lesson 3
Available

1. Working with EXIF Metadata

EXIF metadata stores information about an image's characteristics, like shooting parameters (ISO, exposure, aperture), creation date, orientation, and even the coordinates of the shooting location. EXIF data can be extracted and used for analyzing images or automating their processing.

Extracting EXIF Data

EXIF metadata can be extracted using the info attribute or the getexif() method. The getexif() method provides access to the full set of EXIF data, if it's present in the image.

Python

# Extracting EXIF data
exif_data = image._getexif()

# Checking for EXIF presence
if exif_data is not None:
    for tag_id, value in exif_data.items():
        tag = Image.ExifTags.TAGS.get(tag_id, tag_id)
        print(f"{tag}: {value}")
else:
    print("No EXIF data found.")

In this code, Image.ExifTags.TAGS is used to decode EXIF tag IDs into readable names, like "DateTime", "ExposureTime", "ISOSpeedRatings", etc. If an image doesn't contain EXIF data, the function will just output a message about it.

2. Extracting Key Metadata

EXIF metadata often includes shooting parameters like resolution, orientation, and geolocation. Let's see how to retrieve some of these values if they are present in the EXIF data.

Extracting Shooting Date and Time, Resolution, and Orientation

Python

from PIL.ExifTags import TAGS

# Checking for EXIF data presence
if exif_data is not None:
    # Initializing variables to store values
    date_time = None
    orientation = None
    resolution = None

    for tag_id, value in exif_data.items():
        tag = TAGS.get(tag_id, tag_id)

        # Extracting data by tags
        if tag == "DateTime":
            date_time = value
        elif tag == "Orientation":
            orientation = value
        elif tag == "XResolution" or tag == "YResolution":
            resolution = value

    print("Shooting date and time:", date_time)
    print("Orientation:", orientation)
    print("Resolution:", resolution)
else:
    print("No EXIF data found.")

In this example, values are extracted for DateTime (shooting date and time), Orientation (image orientation), and XResolution/YResolution (image resolution). Such data is often helpful when sorting photos or creating reports.

3. Adding and Editing EXIF Metadata

While Pillow has limited support for adding EXIF data, you can retain metadata during image conversion if it is already present in the source image.

Example: Retaining Metadata During Conversion

To retain EXIF data when saving an image, use the exif parameter while calling the save() method.

Python

# Checking for EXIF presence and saving with metadata
if exif_data is not None:
    exif_bytes = image.info['exif']
    image.save("converted_with_exif.jpg", exif=exif_bytes)
else:
    print("No EXIF data available.")

This code retains EXIF data when converting an image to another format, allowing you to preserve the original shooting parameters.

4. Examples:

Example of Comprehensive Work with Formats and EXIF Metadata

Finally, let's look at an example that converts an image, optimizes it, and retains EXIF data.

Python

from PIL import Image, ExifTags

# Opening the image
image = Image.open("original.jpg")

# Checking for EXIF data presence
exif_data = image._getexif()
if exif_data:
    exif_bytes = image.info['exif']  # Retaining EXIF data for future use
else:
    print("No EXIF data available.")

# Converting the image to PNG and optimizing
image_png = image.convert("RGB")
image_png.save("optimized_image.png", optimize=True)

# Converting to JPEG with EXIF retention and quality reduction
if exif_data:
    image.save("compressed_with_exif.jpg", quality=85, exif=exif_bytes)
else:
    image.save("compressed_without_exif.jpg", quality=85)

This code includes:

  • Image conversion to PNG format with optimization.
  • JPEG conversion with quality reduction for size optimization.
  • Retention of EXIF data during conversion, if present.

Practical Applications of Working with Formats and EXIF Metadata

  • Image Optimization for the Web: Converting images to optimized formats like JPEG and PNG reduces file sizes and speeds up page load times.
  • Data Extraction for Reports: EXIF metadata contains information about shooting parameters that can be useful for photo analysis and report creation.
  • Maintaining Metadata During Editing: When editing images, you can retain original shooting parameters, which is helpful for archiving and documentation purposes.
1
Task
Python SELF EN, level 46, lesson 3
Locked
Extracting EXIF data from an image
Extracting EXIF data from an image
2
Task
Python SELF EN, level 46, lesson 3
Locked
Image Saving and Optimization with EXIF Data
Image Saving and Optimization with EXIF Data
4
Task
Python SELF EN, level 46, lesson 3
Locked
Automating Image Processing Based on EXIF Data
Automating Image Processing Based on EXIF Data
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION