Search code examples
python-3.ximagejpegexif

Changing exif data without re-compressing JPEG image


I write a python 3 CLI tool to fix creation dates of photos in a library (see here.

I use Pillow to load and save the image and piexif to handle exif data retrieval/modification.

The problem I have is that I only want to change the EXIF data in the pictures and not recompress the whole image. It seems that Pillow save can't do that.

My question is:

  1. Any better exif library I could use to only play with the exif data (so far I tried py3exiv2, pexif and piexif) ?
  2. If not, is there a way to indicate to Pillow to only change the exif of the image without recompressing when saving ?

Thanks !

Here is the code I use to change the creation date so far:

# Get original exif data
try:
    exif_dict = piexif.load(obj.path)
except (KeyError, piexif._exceptions.InvalidImageDataError):
    logger.debug('No exif data for {}'.format(obj.path))
    return

# Change creation date in exif_dict
date = obj.decided_stamp.strftime('%Y:%m:%d %H:%M:%S').encode('ascii')
try:
    exif_dict['Exif'][EXIF_TAKE_TIME_ORIG] = date
except (KeyError, piexif._exceptions.InvalidImageDataError):
    return
exif_bytes = piexif.dump(exif_dict)
# Save new exif
im = Image.open(obj.path)
im.save(obj.path, 'jpeg', exif=exif_bytes)

Solution

  • In your case, I think that no need to use Pillow.

    exif_bytes = piexif.dump(exif_dict)
    piexif.insert(exif_bytes, obj.path)