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

How to modify TIF file's EXIF data


I am trying to modify existing metadata within python 3. More specifically I have GPS coordinates and altitude in a my metadata, and I need to modify it.

I'm using piexif mudule, and I ancounter two problems. First, I managed to change Altitude, using exif_dict['GPS'][piexif.GPSIFD.GPSAltitude] = (140, 1) and it works.

But I can't understand how to change Latitude and Longtitude? as they consist of three fields, like ((53, 1), (291191, 10000), (0, 1)).

The second problem occurs when I try to save tiff file with modified metadata. If I save it as TIFF file: img.save(fname_2, 'tiff', exif=exif_bytes), the fname_2 file is created, but it's metadata isn't changed. If Isave as JPEG - img.save(fname_2, 'jpeg', exif=exif_bytes) - metadata changes, but the file is compressed from 289 MB to 15 MB, that makes it impossible to use it for my purposes.

Has anyone managed to do this? It sounds like it would be very simple, but I can't seem to work it out.

import piexif
from PIL import Image
Image.MAX_IMAGE_PIXELS = 1000000000

fname_1='D:\EZG\Codding\photo\iiq/eee.tif'
fname_2='D:\EZG\Codding\photo\iiq/eee_change.tif'
img = Image.open(fname_1)
exif_dict = piexif.load(fname_1)

latitide = exif_dict['GPS'][piexif.GPSIFD.GPSLatitude]
longtitude = exif_dict['GPS'][piexif.GPSIFD.GPSLongitude]
altitude = exif_dict['GPS'][piexif.GPSIFD.GPSAltitude]

print(latitide)
print(longtitude)
print(altitude)

exif_dict['GPS'][piexif.GPSIFD.GPSAltitude] = (140, 1)

exif_bytes = piexif.dump(exif_dict)
img.save(fname_2, 'tiff', exif=exif_bytes)

the fname_2 file is created, but it's metadata isn't changed

Solution

  • Based on other questions and answers on SO it seems that the values are encoded as fractions:

    ((53, 1), (291191, 10000), (0, 1)) 
    

    is 53 degrees 291191/10000 = 29.1191 minutes North (0 == N; 1 == S)

    You may also want to check this answer, as there is a better package to edit GPS coordinates in photo metadata.