def write_metadata(src_image, dest_image): meta_source = ImageMetadata(src_image) meta_dest = ImageMetadata(dest_image) meta_dest.read() meta_source.read() for k in meta_source.exif_keys[:]: try: meta_dest[k] = ExifTag(k, meta_source[k].value) except Exception as e: continue meta_dest.write(preserve_timestamps=True)
def add_tag_to_picture(filename: str, tag: str): metadata = ImageMetadata(filename) metadata.read() current_tags = [] if 'Exif.Photo.UserComment' in metadata: userdata = json.loads(metadata['Exif.Photo.UserComment'].value) if userdata["tags"] is not None: current_tags = list(userdata["tags"]) tags = [tag] + current_tags metadata = ImageMetadata(filename) metadata.read() userdata = {'tags': tags} metadata['Exif.Photo.UserComment'] = json.dumps(userdata) metadata.write() return True
def trigger_expose_bulb(camera, bulb, start_time=(monotonic_time() + 0.05), meta=[], download_timeout=3.5): end_time = start_time + bulb monotonic_alarm(start_time) gph_cmd(camera.bulb_begin) monotonic_alarm(end_time) gph_cmd(camera.bulb_end) o = gph_cmd('wait-event-and-download %is' % int(floor(download_timeout)), timeout=download_timeout) # Should download the image s = filter(lambda x: x.startswith(_saving_file_response), o) if len(s) != 1: print("Couldn't retrieve file at the end of bulb exposure.") raise IOError filename = s[0][len(_saving_file_response):] exifd = ImageMetadata(filename) exifd.read() # Add a piece of debug info to exif header meta.append(('BulbHoldTime', bulb)) meta.append(('TriggerStartTime', start_time)) for (name, value) in meta: tag = 'Xmp.xmp.GPhotolapser.' + name exifd[tag] = XmpTag(tag, value=str(value)) exifd.write() return filename
def trigger_capture(camera, shutter, start_time=(monotonic_time() + 0.05), meta=[], download_timeout=5.0): monotonic_alarm(start_time) o = gph_cmd('capture-image-and-download', timeout=shutter + download_timeout) s = filter(lambda x: x.startswith(_saving_file_response), o) if len(s) != 1: print("Couldn't retrieve file at the end of capture.") raise IOError filename = s[0][len(_saving_file_response):] exifd = ImageMetadata(filename) exifd.read() # Add a piece of debug info to exif header meta.append(('TriggerStartTime', start_time)) for (name, value) in meta: tag = 'Xmp.xmp.GPhotolapser.' + name exifd[tag] = XmpTag(tag, value=str(value)) exifd.write() return filename
def correctRotaion(fl_input): print("imageProcessing::correctRotaion(fl_input)") try: # save the result metadata = ImageMetadata(fl_input) metadata.read() # Get the thumbnail of the image from EXIF. thumb = metadata.exif_thumbnail thumb.set_from_file(fl_input) thumb.write_to_file('512_' + "a") thumb.erase() # Rewrite the thumbnail with corrected image. metadata.write() # Return the output file name. return (True) except Exception as e: print("Error occurs in imageProcessing::correctRotaion(in_file)") print(str(e)) error.ErrorMessageImageProcessing(details=str(e), show=True, language="en") return (None)
def remove_tag_from_picture(filename: str, tag: str): metadata = ImageMetadata(filename) metadata.read() if 'Exif.Photo.UserComment' not in metadata: print("Exif.Photo.UserComment does not exist in metadata") return False userdata = json.loads(metadata['Exif.Photo.UserComment'].value) current_tags = [] if userdata["tags"] is not None else list( userdata["tags"]) if len(current_tags) > 0: current_tags.remove(tag) metadata = ImageMetadata(filename) metadata.read() userdata = {'tags': current_tags} metadata['Exif.Photo.UserComment'] = json.dumps(userdata) metadata.write() return True
def get_exif_metadata3(image_path): metadata = ImageMetadata(image_path) metadata.read() for item in metadata.exif_keys: tag = metadata[item] print(tag) f = open("Exifinfo.txt", "w") f.write(str(tag) + "\n")
def getComment(self, filePath): """Function to retrieve comment from JPEG file""" """ Get comment info from the image specified filePath: full path of the image file """ metadata = ImageMetadata(filePath) metadata.read() return metadata.comment
def Extract(foto): metadata = ImageMetadata(foto) metadata.read() for item in metadata.exif_keys: tag = metadata[item] print tag f = open("Exifinfo.txt","a") f.write(str(tag) + "\n")
def exif3meta(image_path): print(GR+' [*] Reading METADATA info...') metadata = ImageMetadata(image_path) metadata.read() print(O+' [!] Found '+GR+str(len(metadata.exif_keys))+O+' keys...') for item in metadata.exif_keys: tag = metadata[item] print(C+' [+] '+str(tag).split('[')[0]+B+' ['+str(tag).split('[')[1].split(']')[0]+'] = '+GR+str(tag).split('=')[1].strip()) time.sleep(0.2)
def getExif(self, filename): """Return a dictionary of the metadata. """ ret = {} image = ImageMetadata(filename) try: image.read() except IOError: return ret for tag in image.values(): ret[tag.key] = tag.value return ret
def setComment(self, filePath, comment): """ Set comment info to the image specified filePath: full path of the image file comment: contains comment tag info """ metadata = ImageMetadata(filePath) metadata.read() try: metadata.comment = comment metadata.write() return True except Exception as e: return False
def read(self): """Load exif data from disk.""" self.exif = ImageMetadata(self.filename) self.timestamp = None self.altitude = None self.latitude = None self.longitude = None self.timezone = None self.manual = False try: self.exif.read() except TypeError: raise IOError Camera(self.exif) # Try to get a thumbnail. try: self.thumb = GdkPixbuf.Pixbuf.new_from_file_at_size( self.filename, self.thm_size, self.thm_size) except GObject.GError: if len(self.exif.previews) > 0: data = self.exif.previews[-1].data elif len(self.exif.exif_thumbnail.data) > 0: data = self.exif.exif_thumbnail.data else: raise IOError self.thumb = GdkPixbuf.Pixbuf.new_from_stream_at_scale( Gio.MemoryInputStream.new_from_data(data, None), self.thm_size, self.thm_size, True, None) self.calculate_timestamp() try: self.latitude = dms_to_decimal( *self.exif[GPS + 'Latitude'].value + [self.exif[GPS + 'LatitudeRef'].value]) self.longitude = dms_to_decimal( *self.exif[GPS + 'Longitude'].value + [self.exif[GPS + 'LongitudeRef'].value]) except KeyError: pass try: self.altitude = float(self.exif[GPS + 'Altitude'].value) if int(self.exif[GPS + 'AltitudeRef'].value) > 0: self.altitude *= -1 except KeyError: pass
def write(self, fname, instr, date, time, xaxis, yaxis, xunits, yunits, filter): metadata = ImageMetadata(fname) metadata.read() userdata = { 'File name': fname, 'Instrument': instr, 'Date': date, 'Time': time, 'X-Axis': xaxis, 'X-units': xunits, 'Y-units': yunits, 'Y-Axis': yaxis, 'Filter': filter, } metadata['Exif.Photo.UserComment'] = json.dumps(userdata) metadata.write()
def all_photos_in_dir(photo_dir: str, year: str, date: str) -> dict: today_photos = {} if os.path.isdir(photo_dir): for file in os.listdir(photo_dir): if file.lower().endswith( ('.png', '.jpg', '.jpeg', '.tiff', '.bmp', '.gif')): tags = [] try: file_name = "./static/photos/" + year + "/" + date + "/" + file metadata = ImageMetadata(file_name) metadata.read() if 'Exif.Photo.UserComment' in metadata: userdata = json.loads( metadata['Exif.Photo.UserComment'].value) if userdata["tags"] is not None: tags = list(userdata["tags"]) except Exception as e: logger.error(e) today_photos[year + "/" + date + "/" + file] = tags if file.lower().endswith('.mp4'): today_photos[year + "/" + date + "/" + file] = [] return today_photos
def index(source, destination_dir): """ @param source Source filename to copy. @param destinationDir Destination base directory to copy source to. Final directory name is determined from file. """ try: # Load EXIF information metadata = ImageMetadata(source) metadata.read() # Read the date/time at which the picture was taken tag = metadata['Exif.Image.DateTime'] mtime = tag.value.timetuple() log.debug('Successfully read EXIF from "{s}"'.format(s=source)) except Exception as e: log.debug(e) # Get the last modification time mtime = gmtime(getmtime(source)) # Destination filename destination = join(destination_dir, strftime('%Y', mtime), strftime('%Y-%m-%d', mtime)) # Directory must exist if not isdir(destination): log.debug(f'Create directory: "{destination}"') makedirs(destination, 0o755) # Append filename from source destination = join(destination, basename(source)) log.debug(f'Destination: "{destination}"') # Check if file already exists, skip if it does if exists(destination): log.info('Skipping "{d}", file already exists'.format(d=destination)) return log.info('Copying file "{s}" to directory "{d}"'.format(s=source, d=destination)) # Copy file copy(source, destination)
def test3(self, fname): metadata = ImageMetadata(fname) metadata.read() userdata = json.loads(metadata['Exif.Photo.UserComment'].value) pprint.pprint(userdata)
from pyexiv2 import ImageMetadata if __name__ == '__main__': metadata1 = ImageMetadata('IMG_TEST_001.jpg') metadata1.read() info1 = metadata1._get_comment() print 'EXIF keys:', metadata1.exif_keys #img.close()
def load_exif_data(file): """ Load EXIF data from source file """ metadata = ImageMetadata(file) metadata.read() return metadata
print 'Error determining version numbers.' sys.exit(0) if (ver_libexiv2 < ver_libexiv2_min): print 'Newer version of libexiv2 required.' sys.exit(1) if (ver_pyexiv2 < ver_pyexiv2_min): print 'Newer version of pyexiv2 required.' sys.exit(1) if (len(sys.argv) != 3): print 'Usage: ' + sys.argv[0] + ' <sourcefile> <targetfile>' sys.exit(1) # Load the image, read the metadata and extract the thumbnail data src_metadata = ImageMetadata(sys.argv[1]) src_metadata.read() tgt_metadata = ImageMetadata(sys.argv[2]) tgt_metadata.read() for groupName, tagList in copy_tags.iteritems(): # print groupName # print tagList for i, tagName in enumerate(tagList): fullkey = 'Exif.' + groupName + '.' + tagName try: tag = src_metadata[fullkey] print fullkey + ': ' + tag.raw_value except KeyError: print "WARNING: can't find EXIF key '" + fullkey + "'"
# -*- coding: utf-8 -*- from pyexiv2 import ImageMetadata, ExifTag metadata = ImageMetadata(raw_input("Foto: ")) metadata.read() for item in metadata.exif_keys: tag = metadata[item] print tag f = open("Exifinfo.txt", "a") f.write(str(tag) + "\n")
# -*- coding: utf-8 -*- from pyexiv2 import ImageMetadata, ExifTag metadata = ImageMetadata('img.jpg') metadata.read() for item in metadata.exif_keys: tag = metadata[item] print tag f = open("Exifinfo.txt","a") f.write(str(tag) + "\n")
def get_datetime_of_image(img_path: Path) -> datetime: meta = ImageMetadata(str(img_path)) meta.read() return meta.get("Exif.Image.DateTime").value
data extracted from an image. The path to the image file from which the thumbnail data should be extracted should be passed as the only argument of the script. It is of course assumed that you have pygtk installed. """ if (len(sys.argv) != 2): print 'Usage: ' + sys.argv[ 0] + ' path/to/picture/file/containing/jpeg/thumbnail' sys.exit(1) app = gtk.Window(gtk.WINDOW_TOPLEVEL) app.connect('destroy', lambda app: gtk.main_quit()) # Load the image, read the metadata and extract the thumbnail data metadata = ImageMetadata(sys.argv[1]) metadata.read() previews = metadata.previews if not previews: print "This image doesn't contain any thumbnail." sys.exit(1) # Get the largest preview available preview = previews[-1] # Create a pixbuf loader to read the thumbnail data pbloader = gtk.gdk.PixbufLoader() pbloader.write(preview.data) # Get the resulting pixbuf and build an image to be displayed pixbuf = pbloader.get_pixbuf() pbloader.close()
def post(self, img, album): if not os.path.exists(img): raise FileNotFound('Can\'t find image %s on the disk' % img) logger = logging.getLogger('YaFotki.post') opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(self.cookies), MultipartPostHandler.MultipartPostHandler) filename = os.path.split(img)[-1] tags = '' title = filename description = '' if ImageMetadata: exif = ImageMetadata(img) try: tags = ','.join([tag.decode('utf8') for tag in exif['Iptc.Application2.Keywords']]) except KeyError: pass try: title = exif['Iptc.Application2.ObjectName'].decode('utf8') except KeyError: pass try: description = exif['Exif.Image.ImageDescription'].decode('utf8') or exif['Iptc.Application2.Caption'].decode('utf8') except KeyError: pass source = open(img, 'rb') source.seek(0, 2) file_size = source.tell() piece_size = 64000 sid = str(int(time.time())) source.seek(0) hash = md5(source.read()).hexdigest() logger.debug('md5hash: %s, sid: %s, file-size: %s, piece-size: %s' % (hash, sid, file_size, piece_size)) logger.debug('title: %s, description: %s tags: %s' % (title, description, tags)) logger.debug('photo-start') # START fake_file = StringIO((u'<?xml version="1.0" encoding="utf-8"?><client-upload md5="%(md5)s" cookie="%(md5)s%(sid)s"><filename>%(filename)s</filename><title>%(title)s</title><description>%(description)s</description><albumId>%(album)s</albumId><copyright>0</copyright><tags>%(tags)s</tags></client-upload>' % { 'md5': hash, 'sid': sid, 'filename': filename, 'title': title, 'album': album, 'tags': tags, 'description': description, }).encode('utf8')) params = { 'query-type': 'photo-start', 'file-size': str(file_size), 'piece-size': str(piece_size), 'checksum': hash, 'client-xml': fake_file, } try: data = opener.open(UPLOAD_URL, params).read() logger.debug(data) response = minidom.parseString(data).firstChild a = response.attributes if a['status'].value == 'error': if a['exception'].value == '3': logger.error('Album with id %s does not exist.' % album) else: logger.error('Error during upload, with code %s' % a['exception'].value) sys.exit(1) upload_cookie = str(a['cookie'].value) except urllib2.URLError, err: logger.error(err) logger.error(err.read()) return err
# -*- coding: utf-8 -*- from pyexiv2 import ImageMetadata import sys, os from datetime import datetime, date def print_key_value(metadata, key): print key, '=', metadata[key] if __name__ == '__main__': # Read an image file's metadata image_file = sys.argv[1] metadata = ImageMetadata(image_file) metadata.read() # Print a list of all the keys of the EXIF tags in the image print 'EXIF keys:', metadata.exif_keys try: # Print the value of the Exif.Image.DateTime tag key = 'Exif.Image.DateTime' print_key_value(metadata, key) # Set the value of the Exif.Image.DateTime tag metadata[key] = datetime.now() print_key_value(metadata, key) except KeyError: print '[not set]'