1

I'm trying to make an app which restores the original date of the picture (the time in which it was taken) by it's name as the name of the picture contains its date on Android phones but I can't save the EXIF data.
No errors etc. it just does not save. I'm using PIL and piexif.

I tried literally everything here on Stackoverflow and other forums but none of the pieces of code worked.
My code looks like this:

    def set_exif_tag(self, path, yr, m, d, hr):
        i = iter(hr)
        hr = ':'.join(a+b for a, b in zip(i, i))  # Put ":" every 2 chars

        exif_ifd = {
            piexif.ExifIFD.DateTimeOriginal: f"{yr}:{m}:{d} {hr}".encode(),
            piexif.ExifIFD.DateTimeDigitized: f"{yr}:{m}:{d} {hr}".encode()
        }

        exif_dict = {"Exif": exif_ifd}
        exif_bytes = piexif.dump(exif_dict)
        with open(path, 'r+b'):
            with Image.open(path) as img:
                img.save(path, exif=exif_bytes)
        print("EXIF DICT: " + str(exif_dict))
        print("EXIF BYTES: " + str(bytes(exif_bytes)))
Qiasm
  • 356
  • 6
  • 15
  • A couple of comments: You open `path` twice without closing it in-between. You read `exif_dict` from the original image, but then completely replace it. – SiHa Nov 03 '19 at 18:47
  • So I should close the file after writing EXIF data to it and don't read the exif_dict from the original image? – Qiasm Nov 03 '19 at 18:49
  • What result does this code display, and what is the desired result? https://stackoverflow.com/help/mcve – J_H Nov 03 '19 at 20:06
  • *"So I should close the file after writing EXIF data"* - no, that's what the `with` block does. My point was that you don't close it after the initial read, (which appears to be unnecessary, anyway), and that may cause the later save to fail. Although, I'd expect that to raise an error. – SiHa Nov 04 '19 at 08:42
  • The code does not display any errors @J_H. I've also updated my code (edited the question) but it still does not modify the EXIF data. The original date time stays the same. – Qiasm Nov 04 '19 at 19:26
  • 1
    Why not just do it with `exiftool`? – Mark Setchell Nov 04 '19 at 19:36
  • `exiftool`? Where can I find it? It seems there is no module named `exiftool` anywhere or on the PyPi website. I've only found `PyExifTool` but there is no way to save the EXIF data. – Qiasm Nov 06 '19 at 07:07

0 Answers0