Search code examples
python-3.xpython-imaging-library

Replace/add Tiff image tags using Pillow from one file to another


I am new to python. I have two tiff images. One with correct tags (source.tif) while the other with incorrect ones (target.tif).

I am able to read the tags of the correct image using the following python script.

from PIL import Image
from PIL.TiffTags import TAGS
Image.MAX_IMAGE_PIXELS = None

# open image
sourceimg = Image.open('images/source.tif')

# extract exif data
exifdata = sourceimg.getexif()

# get dictionary of tags
for tag_id in exifdata:
    # get the tag name, instead of human unreadable tag id
    tag = TAGS.get(tag_id, tag_id)
    data = exifdata.get(tag_id)
    # decode bytes 
    if isinstance(data, bytes):
        data = data.decode()
    print(f"{tag:25}: {data}")

How can I take these tags from the source and overwrite/add only certain parameters in the target.tif?


Solution

  • The TiffImageFile.tag_v2 dict can be modified and used as the tiffinfo argument when saving the target image:

    from PIL import Image
    
    sourceimg = Image.open("source.tif")
    targetimg = Image.open("target.tif")
    
    # Get the TIFF tags from the source image
    tiffinfo = sourceimg.tag_v2
    
    # Add or modify any tags you want (using the tag number as key)
    # Tag number 270 is the ImageDescription tag
    tiffinfo[270] = "Example image"
    
    # Save the target image with the correct tags
    targetimg.save("target.tif", tiffinfo=tiffinfo)
    
    print(targetimg.tag_v2[270])
    >>> Example image