In previous articles on this website, you learned how to extract EXIF data from JPG image files. This week, you will learn how to get similar data from the TIFF image format.

The TIFF format also has its metadata. Pillow provides a similar dictionary for TIFF images in its TiffTags module. If you need a TIFF image, you can use this one, which is a cover from one of the author’s other books on ReportLab:

ReportLab cover

You can create your own TIFF metadata extractor utility by making a new file named tiff_metadata.py and adding this code to it:

# tiff_metadata.py

from PIL import Image
from PIL.TiffTags import TAGS


def get_metadata(image_file_path):
    image = Image.open(image_file_path)
    metadata = {}
    for tag in image.tag.items():
        metadata[TAGS.get(tag[0])] = tag[1]
    return metadata


if __name__ == "__main__":
    metadata = get_metadata("reportlab_cover.tiff")
    print(metadata)

Here you import the TAGS dictionary from the PIL.TiffTags submodule. Then in get_metadata(), you access the tag elements in the image by iterating over the contents of tag.items(). To make that information more readable, you use the TAGS dictionary that you imported.

Here is a sample of the output you will get when you run this code:

{'ImageWidth': (400,),
 'ImageLength': (562,),
 'BitsPerSample': (8, 8, 8),
 'Compression': (1,),
 'PhotometricInterpretation': (2,),
 'FillOrder': (1,),
 'StripOffsets': (82, 130882, 261682, 392482, 523282, 654082),
 'Orientation': (1,),
 'SampleFormat': (1, 1, 1),
 'SamplesPerPixel': (3,),
 'RowsPerStrip': (109,),
 'StripByteCounts': (130800, 130800, 130800, 130800, 130800, 20400),
 'XResolution': ((300, 1),),
 'YResolution': ((300, 1),),
 'PlanarConfiguration': (1,),
 'ResolutionUnit': (2,),
 'ExifIFD': (8,),
 'Software': ('Pixelmator 3.9',),
 'DateTime': ('2020:10:27 12:10:37',),
}

You can see that the value entries above are all tuples. This is because of how the data is returned from the tag data. If you would like a challenge, you can attempt to clean up this data a bit in your version of the metadata extraction utility.

Wrapping Up

EXIF and TIFF metadata are really useful for encoding lots of information in your images. However, most people don’t even know that data is there! Knowing how to access your photo’s metadata allows you to do all kinds of programmatic tasks, such as resizing, sorting files by various parameters, and much more.

You can use Pillow and Python to do all kinds of other image processing, so this is just scratching the surface. Download Pillow today and start learning!

Want to Learn More?

You can learn more about what you can do with Python and Pillow in Mike’s book, Pillow: Image Processing with Python

Purchase at GumroadLeanpub, or Amazon

The post How to Get TIFF MetaData with Python appeared first on Mouse Vs Python.

Categories: Python