Writing¶
This guide demonstrates how to write EXIF metadata to image files using tagkit.
CLI¶
Writing tag values via the CLI is not yet supported.
API¶
Creating Backups Before Saving¶
A backup can be created automatically before saving changes to the image file. This helps prevent data loss in case of errors during writing.
To enable this feature, pass create_backup=True to the save() method. The backup will be saved with the same name as the original file, but with a .bak extension.
from tagkit.image.exif import ExifImage
# Create an instance
exif = ExifImage("image1.jpg")
# Write tags (in-memory)
tags_to_write = {"Artist": "Jane Doe"}
exif.write_tags(tags_to_write)
# Save changes and create a backup
exif.save(create_backup=True)
print(f"Tags written to {exif.file_path}")
print(f"Backup created at {exif.file_path}.bak")
Writing GPS Information¶
You can add GPS coordinates to an image as follows:
from tagkit.image.exif import ExifImage
# Create an instance for the image
exif = ExifImage("image1.jpg")
# GPS coordinates (latitude, longitude)
# Latitude and longitude must be provided as tuples of (degrees, minutes, seconds),
# where each value is a (numerator, denominator) tuple (i.e., rational number)
latitude = ((40, 1), (44, 1), (52, 1)) # 40° 44' 52" N
longitude = ((73, 1), (59, 1), (2, 1)) # 73° 59' 2" W
# Set GPS tags (in-memory)
exif.write_tag("GPSLatitude", latitude)
exif.write_tag("GPSLatitudeRef", "N")
exif.write_tag("GPSLongitude", longitude)
exif.write_tag("GPSLongitudeRef", "W")
exif.write_tag("GPSAltitude", (105, 10)) # Altitude in meters as rational (e.g., 10.5m)
exif.write_tag("GPSAltitudeRef", 0) # 0 = above sea level, 1 = below sea level
# Save changes
exif.save()
print("GPS information added successfully")
Error Handling¶
Tagkit defines several custom exceptions. Here is an example of handling errors when writing tags:
from tagkit.image.exif import ExifImage
from tagkit.core.exceptions import TagkitError
try:
exif = ExifImage("path/to/your/image.jpg")
exif.write_tag("Artist", "Jane Doe")
exif.save()
print("Tags written successfully")
except FileNotFoundError:
print("Error: Image file not found")
except PermissionError:
print("Error: No permission to write to the file")
except TagkitError as e:
print(f"Error writing EXIF data: {e}")
except Exception as e:
print(f"Unexpected error: {e}")