Python piexif.insert() Examples

The following are 12 code examples of piexif.insert(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module piexif , or try the search function .
Example #1
Source File: exif_processing.py    From upload-scripts with MIT License 5 votes vote down vote up
def add_gps_tags(path: str, gps_tags: {str: any}):
    """This method will add gps tags to the photo found at path"""
    exif_dict = piexif.load(path)
    for tag, tag_value in gps_tags.items():
        exif_dict["GPS"][tag] = tag_value
    exif_bytes = piexif.dump(exif_dict)
    piexif.insert(exif_bytes, path) 
Example #2
Source File: exif_datetime.py    From icloud_photos_downloader with MIT License 5 votes vote down vote up
def set_photo_exif(path, date):
    """Set EXIF date on a photo, do nothing if there is an error"""
    try:
        exif_dict = piexif.load(path)
        exif_dict.get("1st")[306] = date
        exif_dict.get("Exif")[36867] = date
        exif_dict.get("Exif")[36868] = date
        exif_bytes = piexif.dump(exif_dict)
        piexif.insert(exif_bytes, path)
    except (ValueError, InvalidImageDataError):
        logger = setup_logger()
        logger.debug("Error setting EXIF data for %s", path)
        return 
Example #3
Source File: exif_write.py    From mapillary_tools with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def write(self, filename=None):
        """Save exif data to file."""
        if filename is None:
            filename = self._filename

        exif_bytes = piexif.dump(self._ef)

        with open(self._filename, "rb") as fin:
            img = fin.read()
        try:
            piexif.insert(exif_bytes, img, filename)

        except IOError:
            type, value, traceback = sys.exc_info()
            print >> sys.stderr, "Error saving file:", value 
Example #4
Source File: s_test.py    From Piexif with MIT License 5 votes vote down vote up
def test_roundtrip_files(self):
        files = glob.glob(os.path.join("tests", "images", "r_*.jpg"))
        for input_file in files:
            print(input_file)
            exif = piexif.load(input_file)
            exif_bytes = piexif.dump(exif)
            o = io.BytesIO()
            piexif.insert(exif_bytes, input_file, o)
            e = piexif.load(o.getvalue())

            t = e.pop("thumbnail")
            thumbnail = exif.pop("thumbnail")
            if t is not None:
                if not (b"\xe0" <= thumbnail[3:4] <= b"\xef"):
                    self.assertEqual(t, thumbnail)
                else:
                    print("Given JPEG doesn't follow exif thumbnail standard. "
                            "APPn segments in thumbnail should be removed, "
                            "whereas thumbnail JPEG has it. \n: " +
                            input_file)
                exif["1st"].pop(513)
                e["1st"].pop(513)
                exif["1st"].pop(514)
                e["1st"].pop(514)
            for ifd in e:
                if ifd == "0th":
                    if ImageIFD.ExifTag in exif["0th"]:
                        exif["0th"].pop(ImageIFD.ExifTag)
                        e["0th"].pop(ImageIFD.ExifTag)
                    if ImageIFD.GPSTag in exif["0th"]:
                        exif["0th"].pop(ImageIFD.GPSTag)
                        e["0th"].pop(ImageIFD.GPSTag)
                elif ifd == "Exif":
                    if ExifIFD.InteroperabilityTag in exif["Exif"]:
                        exif["Exif"].pop(ExifIFD.InteroperabilityTag)
                        e["Exif"].pop(ExifIFD.InteroperabilityTag)
                for key in exif[ifd]:
                    self.assertEqual(exif[ifd][key], e[ifd][key])
            print(" - pass")

# transplant ------ 
Example #5
Source File: s_test.py    From Piexif with MIT License 5 votes vote down vote up
def test_remove_m(self):
        """'remove' on memory.
        """
        o = io.BytesIO()
        with  self.assertRaises(ValueError):
            piexif.remove(I1)
        piexif.remove(I1, o)
        exif_dict = piexif.load(o.getvalue())
        none_dict = {"0th":{},
                     "Exif":{},
                     "GPS":{},
                     "Interop":{},
                     "1st":{},
                     "thumbnail":None}
        self.assertEqual(exif_dict, none_dict)
        Image.open(o).close()

# insert ------ 
Example #6
Source File: s_test.py    From Piexif with MIT License 5 votes vote down vote up
def test_insert(self):
        exif_dict = {"0th":ZEROTH_IFD, "Exif":EXIF_IFD, "GPS":GPS_IFD}
        exif_bytes = piexif.dump(exif_dict)
        piexif.insert(exif_bytes, INPUT_FILE1, "insert.jpg")
        exif = load_exif_by_PIL("insert.jpg")

        piexif.insert(exif_bytes, NOEXIF_FILE, "insert.jpg")

        with self.assertRaises(ValueError):
            piexif.insert(b"dummy", io.BytesIO())

        piexif.insert(exif_bytes, "insert.jpg")
        os.remove("insert.jpg") 
Example #7
Source File: s_test.py    From Piexif with MIT License 5 votes vote down vote up
def test_insert_m(self):
        """'insert' on memory.
        """
        exif_dict = {"0th":ZEROTH_IFD, "Exif":EXIF_IFD, "GPS":GPS_IFD}
        exif_bytes = piexif.dump(exif_dict)
        o = io.BytesIO()
        piexif.insert(exif_bytes, I1, o)
        self.assertEqual(o.getvalue()[0:2], b"\xff\xd8")
        exif = load_exif_by_PIL(o) 
Example #8
Source File: s_test.py    From Piexif with MIT License 5 votes vote down vote up
def test_insert_fail1(self):
        with open(INPUT_FILE1, "rb") as f:
            data = f.read()
        with open("insert.jpg", "wb+") as f:
            f.write(data)
        exif_dict = {"0th":ZEROTH_IFD, "Exif":EXIF_IFD, "GPS":GPS_IFD}
        exif_bytes = piexif.dump(exif_dict)
        with  self.assertRaises(ValueError):
            piexif.insert(exif_bytes, INPUT_FILE_TIF)
        os.remove("insert.jpg") 
Example #9
Source File: s_test.py    From Piexif with MIT License 5 votes vote down vote up
def test_insert_exif(self):
        """Can PIL open WebP that is inserted exif?"""
        IMAGE_DIR = "tests/images/"
        OUT_DIR = "tests/images/out/"
        files = [
            "tool1.webp",
            "pil1.webp",
            "pil2.webp",
            "pil3.webp",
            "pil_rgb.webp",
            "pil_rgba.webp",
        ]

        exif_dict = {
            "0th":{
                piexif.ImageIFD.Software: b"PIL",
                piexif.ImageIFD.Make: b"Make",
            }
        }

        for filename in files:
            try:
                Image.open(IMAGE_DIR + filename)
            except:
                print("Pillow can't read {}".format(filename))
                continue

            with open(IMAGE_DIR + filename, "rb") as f:
                data = f.read()
            exif_bytes = piexif.dump(exif_dict)
            exif_inserted = _webp.insert(data, exif_bytes)
            with open(OUT_DIR + "i_" + filename, "wb") as f:
                f.write(exif_inserted)
            Image.open(OUT_DIR + "i_" + filename) 
Example #10
Source File: s_test.py    From Piexif with MIT License 5 votes vote down vote up
def test_insert(self):
        """Can PIL open WebP that is inserted exif?"""
        IMAGE_DIR = "tests/images/"
        OUT_DIR = "tests/images/out/"
        files = [
            "tool1.webp",
            "pil1.webp",
            "pil2.webp",
            "pil3.webp",
            "pil_rgb.webp",
            "pil_rgba.webp",
        ]

        exif_dict = {
            "0th":{
                piexif.ImageIFD.Software: b"PIL",
                piexif.ImageIFD.Make: b"Make",
            }
        }
        exif_bytes = piexif.dump(exif_dict)
        
        for filename in files:
            try:
                Image.open(IMAGE_DIR + filename)
            except:
                print("Pillow can't read {}".format(filename))
                continue
            piexif.insert(exif_bytes, IMAGE_DIR + filename, OUT_DIR + "ii_" + filename)
            Image.open(OUT_DIR + "ii_" + filename) 
Example #11
Source File: get-tagged-photos.py    From facebook-photos-download with MIT License 4 votes vote down vote up
def download_photos():
    ssl._create_default_https_context = ssl._create_unverified_context
    #Prep the download folder
    folder = 'photos/'
    if not os.path.exists(folder):
        os.makedirs(folder)
    print("Saving photos to " + folder)
    #Download the photos
    with open('tagged.json') as json_file:
        data = json.load(json_file)
        for i,d in enumerate(data['tagged']):
            if d['media_type'] == 'image':
                #Save new file
                if d['fb_date'] == "Today":
                    filename_date = datetime.today().strftime('%Y-%m-%d')
                elif d['fb_date'] == "Yesterday":
                    filename_date = datetime.today() - timedelta(days=1)
                    filename_date = filename_date.strftime('%Y-%m-%d')
                else:
                    filename_date = parse(d['fb_date']).strftime("%Y-%m-%d")
                img_id = d['media_url'].split('_')[1]
                new_filename = folder + filename_date + '_' + img_id + '.jpg'
                if os.path.exists(new_filename):
                    print("Already Exists (Skipping): %s" % (new_filename))
                else:
                    delay = 1

                    while True:
                        try:
                            print("Downloading " + d['media_url'])
                            img_file = wget.download(d['media_url'], new_filename, False)
                            break
                        except (TimeoutError, urllib.error.URLError) as e:
                            print("Sleeping for {} seconds".format(delay))
                            time.sleep(delay)
                            delay *= 2
                    #Update EXIF Date Created
                    exif_dict = piexif.load(img_file)
                    if d['fb_date'] == "Today":
                        exif_date = datetime.today().strftime("%Y:%m:%d %H:%M:%S")
                    elif d['fb_date'] == "Yesterday":
                        exif_date = datetime.today() - timedelta(days=1)
                        exif_date = exif_date.strftime("%Y:%m:%d %H:%M:%S")
                    else:
                        exif_date = parse(d['fb_date']).strftime("%Y:%m:%d %H:%M:%S")
                    img_desc = d['fb_caption'] + '\n' + d['fb_tags'] + '\n' + d['fb_url'].split("&")[0]
                    exif_dict['Exif'][piexif.ExifIFD.DateTimeOriginal] = exif_date
                    exif_dict['0th'][piexif.ImageIFD.Copyright] = (d['user_name'] + ' (' + d['user_url']) + ')'
                    exif_dict['0th'][piexif.ImageIFD.ImageDescription] = img_desc.encode('utf-8')

                    piexif.insert(piexif.dump(exif_dict), img_file)
                    print(str(i+1) + ') Added '+ new_filename) 
Example #12
Source File: photo_exif_recover.py    From QzoneExporter with GNU General Public License v3.0 4 votes vote down vote up
def recover(self):
        print("recovering:", self.file_dir)

        # 0th #
        self.copy_exif("0th", piexif.ImageIFD.Make,
                       self.raw_info, "exif", "make", piexif.TYPES.Ascii)
        self.copy_exif("0th", piexif.ImageIFD.Model,
                       self.raw_info, "exif", "model", piexif.TYPES.Ascii)

        # Exif #
        self.copy_exif("Exif", piexif.ExifIFD.ExposureBiasValue,
                       self.raw_info, "exif", "exposureCompensation", piexif.TYPES.SRational)
        self.copy_exif("Exif", piexif.ExifIFD.ExposureMode,
                       self.raw_info, "exif", "exposureMode", piexif.TYPES.Short)
        self.copy_exif("Exif", piexif.ExifIFD.ExposureProgram,
                       self.raw_info, "exif", "exposureProgram", piexif.TYPES.Short)
        self.copy_exif("Exif", piexif.ExifIFD.ExposureTime,
                       self.raw_info, "exif", "exposureTime", piexif.TYPES.SRational)
        self.copy_exif("Exif", piexif.ExifIFD.Flash,
                       self.raw_info, "exif", "flash", piexif.TYPES.Short)
        self.copy_exif("Exif", piexif.ExifIFD.FNumber,
                       self.raw_info, "exif", "fnumber", piexif.TYPES.Rational)
        self.copy_exif("Exif", piexif.ExifIFD.FocalLength,
                       self.raw_info, "exif", "focalLength", piexif.TYPES.Rational)
        self.copy_exif("Exif", piexif.ExifIFD.ISOSpeed,
                       self.raw_info, "exif", "iso", piexif.TYPES.Long)
        self.copy_exif("Exif", piexif.ExifIFD.LensModel,
                       self.raw_info, "exif", "lensModel", piexif.TYPES.Ascii)
        self.copy_exif("Exif", piexif.ExifIFD.MeteringMode,
                       self.raw_info, "exif", "meteringMode", piexif.TYPES.Short)

        # Exif: OriginalTime #
        if not self.copy_exif("Exif", piexif.ExifIFD.DateTimeOriginal,
                              self.raw_info, "exif", "originalTime", piexif.TYPES.Ascii):
            self.coyp_DateTimeOriginal_from_uploadtime()  # if originalTime is missing

        # GPS #
        if self.copy_exif("GPS", piexif.GPSIFD.GPSLongitude,
                          self.floatview_info, "shootGeo", "pos_x", "GPSPos"):
            # 拍摄地点在东半球是参考东经的;在西半球如参考东经则经度是负数
            self.add_exif("GPS", piexif.GPSIFD.GPSLongitudeRef, "E")
        if self.copy_exif("GPS", piexif.GPSIFD.GPSLatitude,
                          self.floatview_info, "shootGeo", "pos_y", "GPSPos"):
            # 拍摄地点在北半球是参考北纬的;在南半球如参考北纬则维度是负数
            self.add_exif("GPS", piexif.GPSIFD.GPSLatitudeRef, "N")

        if self.is_dirty:
            exif_bytes = piexif.dump(self.exif_dict)
            piexif.insert(exif_bytes, self.file_dir)