def attributes(self, node): attr = VMap() vfile = node.open() img = Image.open(vfile) info = img._getexif() vfile.close() for tag, values in info.items(): if tag in self.dateTimeTags: try: decoded = str(TAGS.get(tag, tag)) try: dt = strptime(values, "%Y:%m:%d %H:%M:%S") except ValueError: try: dt = strptime(values[:-6], "%Y-%m-%dT%H:%M:%S") except ValueError: dt = strptime(values.rstrip(' '), "%a %b %d %H:%M:%S") vt = vtime(dt.tm_year, dt.tm_mon, dt.tm_mday, dt.tm_hour, dt.tm_min, dt.tm_sec, 0) vt.thisown = False attr[decoded] = Variant(vt) except Exception as e: attr[decoded] = Variant(str(values)) else: decoded = str(TAGS.get(tag, tag)) if isinstance(values, tuple): vl = VList() for value in values: vl.push_back(Variant(value)) attr[decoded] = vl else: attr[decoded] = Variant(values) return attr
def rotate_upright(img): ret = {} info = img._getexif() for tag, value in info.items(): decoded = TAGS.get(tag, tag) if decoded == "Orientation": orientation = value #print "before:" + str(value) if orientation is 6: img = img.rotate(-90) elif orientation is 8: img = img.rotate(90) print type(img) print orientation elif orientation is 3: img = img.rotate(180) elif orientation is 2: img = img.transpose(Image.FLIP_LEFT_RIGHT) elif orientation is 5: img = img.rotate(-90).transpose(Image.FLIP_LEFT_RIGHT) elif orientation is 7: img = img.rotate(90).transpose(Image.FLIP_LEFT_RIGHT) elif orientation is 4: img = img.rotate(180).transpose(Image.FLIP_LEFT_RIGHT) print type(img) ret = {} info = img._getexif() for tag, value in info.items(): decoded = TAGS.get(tag, tag) if decoded == "Orientation": orientation = value print "before:" + str(value) return img
def get_exif_data(image_path, exif_include_keys=EXIF_INCLUDE_KEYS): """ Returns all the image's exif data as a dict. """ image_file = pil.open(image_path) try: raw_exif_data = image_file._getexif() except AttributeError: raw_exif_data = None if not raw_exif_data: return None exif_data = {} for key, value in raw_exif_data.items(): decoded_key = TAGS.get(key, key) if decoded_key in exif_include_keys: if decoded_key == "DateTimeOriginal": try: value = datetime.strptime(value, "%Y:%m:%d %H:%M:%S") except ValueError: value = datetime.now() exif_data[decoded_key] = value return exif_data [{TAGS.get(key, key): value}for key, value in raw_exif_data.items()]
def get_exif(file,field): img = Image.open(file) exif = img._getexif() exif_data = [] for id, value in exif.items(): if TAGS.get(id) == field: tag = TAGS.get(id, id),value exif_data.extend(tag) return exif_data
def read_one_exif_tag(pil_image, tag): try: exif_key = TAGS.keys()[TAGS.values().index(tag)] except ValueError: return 'Invalid EXIF Tag' info_ = pil_image._getexif() if info_ is None: return None else: invalid_str = 'Invalid EXIF Key: exif_key=%r, tag=%r' % (exif_key, tag) exif_val = info_.get(exif_key, invalid_str) return exif_val
def __init__(self, imageName, crs): QDialog.__init__(self) self.ui_exif_info = Ui_Exif2() self.ui_exif_info.setupUi(self) self.FocalLength = None img = Image.open(imageName) if hasattr(img,'_getexif'): raw = img._getexif() else: QMessageBox.warning(QMainWindow(),"Error","Image has no EXIF") return sizePicture = img.size self.diag = sqrt(sizePicture[0]**2+sizePicture[1]**2) if raw != None and any(raw): dict = None for (k,v) in raw.iteritems(): if TAGS.get(k) == 'GPSInfo': dict = v if TAGS.get(k) == 'FocalLength': self.FocalLength = v text = '' if dict != None: Nord = dict[2][0][0]+dict[2][1][0]/float(dict[2][1][1])/60.0 Est = dict[4][0][0]+dict[4][1][0]/float(dict[4][1][1])/60.0 crsTarget = QgsCoordinateReferenceSystem(crs.postgisSrid()) crsSource = QgsCoordinateReferenceSystem(4326) xform = QgsCoordinateTransform(crsSource, crsTarget) LocalPos = xform.transform(QgsPoint(Est,Nord)) text += 'Nord: ' + str(LocalPos[0]) text += '\nEst: ' +str(LocalPos[1]) text += '\n\n' text += '============================\n' text += 'Raw EXIF data:' for (k,v) in raw.iteritems(): test = True if isinstance(v, (int, long, float, complex, bool)): text += "\n " + str(TAGS.get(k)) + ": " + str(v) else: for c in str(v): if isinstance(c, str) and c not in string.ascii_letters and c not in string.digits and c not in string.whitespace and c not in('.',',','(',')',':'): test = False if test: text += "\n " + str(TAGS.get(k)) + ": " + str(v) self.ui_exif_info.textBrowser.setText(text) else: raise IOError self.ui_exif_info.pushButton.clicked.connect(self.getFocal)
def get_exif_data(filename): fileinfo = {} try: img = Image.open(filename) if hasattr( img, '_getexif' ): exifinfo = img._getexif() print exifinfo if exifinfo != None: fileinfo = dict([(TAGS.get(key,key), str(value).decode('utf-8', 'ignore')) for key, value in exifinfo.items() if type(TAGS.get(key,key)) is str]) except IOError: logging.error(filename) return fileinfo
def get_exif(file): img = Image.open(file) df=np.array(Image.open(file)) exif = img._getexif() exif_data = [] for id, value in exif.items(): #print 'ID',TAGS.get(id),'\n' ID = TAGS.get(id) tag = TAGS.get(id, id),value #print 'Tag',tag,'\n' if ID == 'GPSInfo': exif_data.extend(tag) return exif_data
def get_exif_data(fname): """Get embedded EXIF data from image file.""" fileinfo = {} try: img = Image.open(fname) if hasattr( img, '_getexif' ): exifinfo = img._getexif() print exifinfo if exifinfo != None: fileinfo = dict([(TAGS.get(key,key),value) for key, value in exifinfo.items() if type(TAGS.get(key,key)) is str]) except IOError: logging.error(fname) return fileinfo
def get_exif_header(image): """Returns a dictionary from the exif header of an PIL Image. Also converts the GPS Tags. Args: image: """ try: info = image._getexif() except: raise gserror.EmptyExifHeaderError('could not found the exif header') if not info: raise gserror.EmptyExifHeaderError('empty exif header') exif_header = {} for tag, value in info.items(): tag_id = TAGS.get(tag, tag) if tag_id == __EXIF_GPS_INFO: gps_info = {} for t in value: gps_tag_id = GPSTAGS.get(t, t) gps_info[gps_tag_id] = value[t] exif_header[tag_id] = gps_info else: exif_header[tag_id] = value return exif_header
def testForExif(imgFileName): try: print "[+] Testing for exif Metadata" exifData = {} imgFile = Image.open(imgFileName) info = imgFile._getexif() if info: for (tag, value) in info.items(): decoded = TAGS.get(tag, tag) exifData[decoded] = value exifGPS = exifData['GPSInfo'] if exifGPS: print '[*] ' + str(imgFileName) + ' contains GPS MetaData' else: print '[-] NO GPS data found' else: print '[-] NO data found' except Exception, e: print "[-] Error : " + str(e)
def get_exif(self): """ Get EXIF tags for JPEG images. Fails for non-JPEG images. :returns: EXIF tags. :rtype: dict(str -> str) :raise ValueError: Not a JPEG image. """ # Check that it's really an image. if self.mime_subtype != "jpeg": raise ValueError("Not a JPEG image") # Lazy import. global PIL_TAGS if PIL_TAGS is None: from PIL.ExifTags import TAGS as PIL_TAGS # Load in PIL. img = self.to_pil() # Extract the EXIF tags. exif = {} try: info = img.tag.tags except AttributeError: info = img._getexif() if info: for tag, value in info.items(): decoded = PIL_TAGS.get(tag, tag) exif[decoded] = value # Return the EXIF tags. return exif
def show_geodata_for_image(imageSrc, imageFilePath): """ Searches for GPS data in the image and shows it if found and valid. """ exitData = {} try: imageFile = Image.open(imageFilePath) info = imageFile._getexif() except: return if info: for (tag, value) in info.items(): decoded = TAGS.get(tag, tag) if decoded == 'GPSInfo': gpsData = {} for t in value: decodedGps = GPSTAGS.get(t, t) gpsData[decodedGps] = value[t] if 'GPSLatitude' in gpsData and 'GPSLatitudeRef' in gpsData and 'GPSLongitude' in gpsData and 'GPSLongitudeRef' in gpsData: latitude = convert_to_degrees(gpsData['GPSLatitude']) if gpsData['GPSLatitudeRef'] != 'N': latitude = 0 - latitude longitude = convert_to_degrees(gpsData['GPSLongitude']) if gpsData['GPSLongitude'] != 'E': longitude = 0 - longitude if latitude !=0 and longitude != 0: print 'GPS data for %s: latitude=%f%s, longitude=%f%s' % (imageSrc, latitude, gpsData['GPSLatitudeRef'], longitude, gpsData['GPSLongitudeRef']) break
def extract(self, filepath): fd = Image.open(filepath) exif = fd._getexif() # raw exif gps = {} # raw undecoded gps results = {} if exif: for (k, v) in exif.items(): results[TAGS.get(k, k)] = v if exif and ExifExtract.GPSINFO in exif: for t in exif[ExifExtract.GPSINFO]: sub_decoded = GPSTAGS.get(t, t) gps[sub_decoded] = exif[ExifExtract.GPSINFO][t] if 'GPSLatitude' in gps and 'GPSLatitudeRef' in gps and 'GPSLongitude' in gps and 'GPSLongitudeRef' in gps: lat_deg = self._to_degrees(gps['GPSLatitude']) if 'N' is not gps['GPSLatitudeRef']: lat_deg *= -1 lng_deg = self._to_degrees(gps['GPSLongitude']) if 'E' is not gps['GPSLongitudeRef']: lng_deg *= -1 results['GPS'] = { 'longitude': lng_deg, 'latitude': lat_deg } return results
def rotate(img): try: exif = img._getexif() except: return img if not exif or not exif.items: return img for tag, value in exif.items(): decoded = TAGS.get(tag, tag) if decoded == 'Orientation': if value == 1: return img elif value == 2: return img.transpose(Image.FLIP_LEFT_RIGHT) elif value == 3: return img.transpose(Image.ROTATE_180) elif value == 4: return img.transpose(Image.FLIP_TOP_BOTTOM) elif value == 5: return img.transpose(Image.ROTATE_90).transpose(Image.FLIP_LEFT_RIGHT) elif value == 6: return img.transpose(Image.ROTATE_270) elif value == 7: return img.transpose(Image.ROTATE_270).transpose(Image.FLIP_LEFT_RIGHT) elif value == 8: return img.transpose(Image.ROTATE_90) else: return img return img
def getExif(filename): """Returns EXIF data from a file -- currently, creation date and orientation Args: filename""" exif = {} i = Image.open(filename) info = i._getexif() if info: for tag, value in info.items(): decoded = TAGS.get(tag, tag) exif[decoded] = value try: exif['DateTimeOriginal'] dtime = exif['DateTimeOriginal'] except KeyError: print "Caution: No EXIF datetime data" dtime = None except: #Any other error print "Error in reading EXIF date stamp" dtime = None try: exif['Orientation'] orient = exif['Orientation'] except KeyError: print "Caution: No EXIF orientation data" orient = 1 except: #Any other error print "Error in reading EXIF orientation information" orient = 1 return dtime, orient else: return None, None
def handle(self, *args, **options): for photo_id in options['photo_id']: try: img=PhotoImages.objects.get(id=photo_id) except PhotoAlbums.DoesNotExist: self.stdout.write('Not find PhotoImage for ID:"%s"'%photo_id) else: self.stdout.write('Get EXIF data (%s) for photo( album:%s, path:%s, filename:%s)'%(options['tags'],img.album.tag, img.path, img.filename)) full_path=os.path.join(img.album.base_path, img.path, img.filename) if os.path.exists(full_path): photo=Image.open(full_path) # Получаем Exif try: exif = photo._getexif() except: exif = None self.stdout.write('Error getting EXIF Data') if exif != None: for tag, value in exif.items(): decoded = TAGS.get(tag, tag) if options['taglist']: self.stdout.write('%s'%decoded) else: if isinstance(decoded,str): if ('all' in options['tags']) or (decoded.lower() in options['tags']) or (decoded in options['tags']): self.stdout.write('%s = %s'%(decoded,value)) else: self.stdout.write('Image file not found!')
def get_exif_data(filename): """Return a dict with the raw EXIF data.""" logger = logging.getLogger(__name__) if PIL.PILLOW_VERSION == '3.0.0': warnings.warn('Pillow 3.0.0 is broken with EXIF data, consider using ' 'another version if you want to use EXIF data.') img = PILImage.open(filename) try: exif = img._getexif() or {} except ZeroDivisionError: logger.warning('Failed to read EXIF data.') return None data = {TAGS.get(tag, tag): value for tag, value in exif.items()} if 'GPSInfo' in data: try: data['GPSInfo'] = {GPSTAGS.get(tag, tag): value for tag, value in data['GPSInfo'].items()} except AttributeError: logger = logging.getLogger(__name__) logger.info('Failed to get GPS Info') del data['GPSInfo'] return data
def _get_exifgps(i): ret = {} info = i._getexif() if info: for tag, values in info.items(): decoded = TAGS.get(tag, tag) if decoded == "GPSInfo": lat, lon, altitude, gps_data = _extract_gpsinfo(values) # try: # iptc = IptcImagePlugin.getiptcinfo(i) # ret['caption'] = iptc[(2,120)] # ret['copyright'] = iptc[(2,116)] # ret['keywords'] = iptc[(2,25)] # except: # ret['headline'] = None # ret['caption'] = None # ret['copyright'] = None # ret['keywords'] = [] ret['latitude'] = lat ret['longitude'] = lon ret['altitude'] = altitude ret[decoded] = gps_data return ret
def remove_exif_orientation(file_path): ext = os.path.splitext(file_path)[1].lower() if ext == '.jpg' or ext == '.jpeg': img = Image.open(file_path) exif = img._getexif() if not exif: return orientation = 1 for (k, v) in exif.items(): if TAGS.get(k) == 'Orientation': orientation = v if orientation is 6: img = img.rotate(-90) elif orientation is 8: img = img.rotate(90) elif orientation is 3: img = img.rotate(180) elif orientation is 2: img = img.transpose(Image.FLIP_LEFT_RIGHT) elif orientation is 5: img = img.rotate(-90).transpose(Image.FLIP_LEFT_RIGHT) elif orientation is 7: img = img.rotate(90).transpose(Image.FLIP_LEFT_RIGHT) elif orientation is 4: img = img.rotate(180).transpose(Image.FLIP_LEFT_RIGHT) img.save(file_path)
def _get_exif_data(self, image): """Returns a dictionary from the exif data of an PIL Image item. Also converts the GPS Tags""" exif_data = {} try: info = image._getexif() except AttributeError: return exif_data except IndexError: return exif_data if info: for tag, value in info.items(): decoded = TAGS.get(tag, tag) if decoded == "GPSInfo": gps_data = {} for t in value: sub_decoded = GPSTAGS.get(t, t) gps_data[sub_decoded] = value[t] exif_data[decoded] = gps_data else: exif_data[decoded] = value return exif_data
def testForExif(imgFileName): try: exifData = {} imgFile = Image.open(imgFileName) info = imgFile._getexif() if info: for (tag,value) in info.items(): decoded = TAGS.get(tag,tag) exifData[decoded] = value exifGPS = exifData["GPSInfo"] if exifGPS: print("[*] {0} contains GPS MetaData".format(imgFileName)) return exifGPS else: return None except Exception,e: print("ERROR: ",e) return None
def printExif(image): exifAttrs = set(["Model", "Make", "ExifImageWidth", "ExifImageHeight", "FocalLength"]) exif = {} info = image._getexif() if info: for attr, value in info.items(): decodedAttr = TAGS.get(attr, attr) if decodedAttr in exifAttrs: exif[decodedAttr] = value if 'FocalLength' in exif: exif['FocalLength'] = float(exif['FocalLength'][0])/float(exif['FocalLength'][1]) outputString = "" if ('Make' in exif): outputString += exif['Make'] outputString += "," if ('Model' in exif): outputString += exif['Model'] outputString += "," if ('FocalLength' in exif): outputString += str(exif['FocalLength']) outputString += "," outputString += str(exif['ExifImageWidth']) + "," + str(exif['ExifImageHeight']) print(outputString)
def __call__(self, hdrs, content, limit): try: img = Image.open(cStringIO.StringIO(content)) except IOError: return None parts = [ ("Format", str(img.format_description)), ("Size", "%s x %s px"%img.size), ("Mode", str(img.mode)), ] for i in sorted(img.info.keys()): if i != "exif": parts.append( (str(i), str(img.info[i])) ) if hasattr(img, "_getexif"): ex = img._getexif() if ex: for i in sorted(ex.keys()): tag = TAGS.get(i, i) parts.append( (str(tag), str(ex[i])) ) clean = [] for i in parts: clean.append([utils.cleanBin(i[0]), utils.cleanBin(i[1])]) fmt = common.format_keyvals( clean, key = "header", val = "text" ) return "%s image"%img.format, fmt
def get_tiff_tags(self): tifftags = self.image.tag.tags decoded = {} for a, b in tifftags.items(): val = TAGS.get(a,b) decoded[val] = b return decoded
def __call__(self, data, **metadata): try: img = Image.open(cStringIO.StringIO(data)) except IOError: return None parts = [ ("Format", str(img.format_description)), ("Size", "%s x %s px" % img.size), ("Mode", str(img.mode)), ] for i in sorted(img.info.keys()): if i != "exif": parts.append( (str(i), str(img.info[i])) ) if hasattr(img, "_getexif"): ex = img._getexif() if ex: for i in sorted(ex.keys()): tag = TAGS.get(i, i) parts.append( (str(tag), str(ex[i])) ) fmt = format_dict(ODict(parts)) return "%s image" % img.format, fmt
def get_exif(i): ret = {} info = i._getexif() for tag, value in info.items(): decoded = TAGS.get(tag, tag) ret[decoded] = value return ret
def ImageToPixmap(fn): try: im = Image.open(fn) except: return None exif = {} try: info = im._getexif() except: info = None if info: for tag, value in info.items(): decoded = TAGS.get(tag, tag) exif[decoded] = value date = '' if 'DateTimeOriginal' in exif: # Date example: 2011:02:26 16:29:49 try: date2 = exif['DateTimeOriginal'] t = time.strptime(date2,"%Y:%m:%d %H:%M:%S") date = time2str(t) except: pass if 'Orientation' in exif: if exif['Orientation'] == 6: im = im.rotate(-90) elif exif['Orientation'] == 3: im = im.rotate(180) elif exif['Orientation'] == 8: im = im.rotate(90) data = im.convert('RGBA').tostring('raw', 'BGRA') image = QtGui.QImage(data, im.size[0], im.size[1], QtGui.QImage.Format_ARGB32) w,h = im.size size = str(w) + 'x' + str(h) return ((data, QtGui.QPixmap(image)), date+' '+size)
def get_exif_data(image): """Return a dict from the exif data of a PIL Image and convert the GPS tags. """ exif_data = {} info = image._getexif() if info: for tag, value in info.items(): decoded = TAGS.get(tag, tag) if decoded == "GPSInfo": gps_data = {} for gps_tag in value: sub_decoded = GPSTAGS.get(gps_tag, gps_tag) gps_data[sub_decoded] = value[gps_tag] exif_data[decoded] = gps_data else: exif_data[decoded] = value return exif_data
def get_exif_data(image): """Returns a dictionary from the exif data of an PIL Image item. Also converts the GPS Tags""" exif_data = {} info = image._getexif() if info: for tag, value in info.items(): decoded = TAGS.get(tag, tag) if decoded == "GPSInfo": gps_data = {} for gps_tag in value: sub_decoded = GPSTAGS.get(gps_tag, gps_tag) gps_data[sub_decoded] = value[gps_tag] exif_data[decoded] = gps_data else: exif_data[decoded] = value return exif_data
def extract_gpsinfo_from_image(image): ''' Helper function to extract the exif GPSInfo from a file ''' exif = {} if hasattr(image, '_getexif'): exifinfo = image._getexif() if exifinfo != None: for tag, value in exifinfo.items(): decoded = TAGS.get(tag, tag) if decoded == 'GPSInfo': gps = {} for t in value: sub_decoded = GPSTAGS.get(t, t) gps[sub_decoded] = value[t] exif[decoded] = gps return exif
def _get_latlng_exif(self, img_fh): logging.info("Getting exif lat lng in _get_latlng_exif") from PIL import Image from PIL.ExifTags import TAGS, GPSTAGS gps_data = {} image = Image.open(img_fh) info = image._getexif() img_fh.seek(0) # reset file handle if info: for tag, value in info.items(): decoded = TAGS.get(tag, tag) if decoded == "GPSInfo": for gps_tag in value: gps_tag_decoded = GPSTAGS.get(gps_tag, gps_tag) gps_data[gps_tag_decoded] = value[gps_tag] try: gps_lat = gps_data['GPSLatitude'] gps_lng = gps_data['GPSLongitude'] except KeyError: pass # TODO: is this right? gps_lat_angles = ( float(gps_lat[0][0]) / float(gps_lat[0][1]), # degrees float(gps_lat[1][0]) / float(gps_lat[1][1]), # hours float(gps_lat[2][0]) / float(gps_lat[2][1]), # minutes ) gps_lng_angles = ( float(gps_lng[0][0]) / float(gps_lng[0][1]), # degrees float(gps_lng[1][0]) / float(gps_lng[1][1]), # hours float(gps_lng[2][0]) / float(gps_lng[2][1]), # minutes ) gps_lat_ref = gps_data['GPSLatitudeRef'] # N/S gps_lng_ref = gps_data['GPSLongitudeRef'] # E/W lat = latlng_angles_to_dec(gps_lat_ref, gps_lat_angles) lng = latlng_angles_to_dec(gps_lng_ref, gps_lng_angles) logging.info('Converting "%s %s, %s %s" to "%s %s"' % (gps_lat_ref, gps_lat_angles, gps_lng_ref, gps_lng_angles, lat, lng)) return lat, lng
def analisis_imagen(nombre_imagen): metadatos_exif = {} #Abrimos la imagen archivo_imagen = Image.open(nombre_imagen) #Extraemos la información necesaria de ella, los EXIF info = archivo_imagen._getexif() print("\n") print( "###############################################################################" ) print(" Información general") print( "###############################################################################" ) print("\n") print(info) if (info): for (tag, value) in info.items(): decoded = TAGS.get(tag, tag) metadatos_exif[decoded] = value if metadatos_exif: print("\n") print( "###############################################################################" ) print( " Información metadatos" ) print( "###############################################################################" ) print("\n") for meta_info in metadatos_exif: print("[+] " + str(nombre_imagen) + " Datos: " + str(metadatos_exif[meta_info]))
def get_exif_all_images(row): images = row['photo_files'] tags = [get_exif_single_image(x) for x in images] # exifread version # for tag in tags: # for key in tag.keys(): # row[key] = tag[key] # PIL version for tag in tags: if tag: try: for (k, v) in tag.iteritems(): row[TAGS.get(k)] = v except: pass return row
def extractor(): # path to the image imagename = image_set # read the image data using PIL image = Image.open(imagename) # extract EXIF data exifdata = image.getexif() # iterating over all EXIF data fields for tag_id in exifdata: # get the tag name, instead of human unreadable tag id tag = TAGS.get(tag_id, tag_id) data = exifdata.get(tag_id) # decode bytes if isinstance(data, bytes): data = data.decode() print(f"{tag:25}: {data}")
def get_exif(fn): '''This get the EXIF data...''' ret = {} i = Image.open(fn) try: info = i._getexif() for t, v in info.items(): try: decoded = TAGS.get(t, t) ret[decoded] = v except: pass if "GPSInfo" in ret: return ret["GPSInfo"] else: return {} except: return {}
def get_exif_datetime(fname): try: img = Image.open(fname) except: print('error',fname) return exif = img._getexif() try: for id,val in exif.items(): tg = TAGS.get(id,id) if tg == "DateTimeOriginal": img.close() dt=val.split(' ') return datetime.datetime(*(list(map(int,dt[0].split(':') + dt[1].split(':'))))) except AttributeError: img.close() return None img.close() return None
def read_exif_data(img): """ Read out pertinent image exif data - in this case datetime Exif time is in YYYY:MM:DD HH:MM:SS format. The formats from the form are YYYY-MM-DD and HH:MM The easiest way to convert is to go through datetime """ try: exif = img._getexif() # pylint: disable=W0212 except AttributeError: return if not exif: return for tag, value in exif.items(): decoded = TAGS.get(tag, hex(tag)) if decoded.startswith('DateTime'): dt_object = datetime.strptime(value, "%Y:%m:%d %H:%M:%S") return dt_object.strftime("%Y-%m-%d"), dt_object.strftime("%H:%M")
def get_exif_data(image): """ This function gets the exit data off of an image. Please pass it an image file with associated EXIF data. """ exif_data = {} info = image._getexif() if info: for tag, value in info.items(): decoded = TAGS.get(tag, tag) if decoded == "GPSInfo": gps_data = {} for t in value: sub_decoded = GPSTAGS.get(t, t) gps_data[sub_decoded] = value[t] #hehe exif_data[decoded] = gps_data else: exif_data[decoded] = value return exif_data
def listTags(imgObj): """ Extact ExIf tags from image to text file with help from: https://developer.here.com/blog/getting-started-with-geocoding-exif-image-metadata-in-python3""" # open image file im = Image.open(imgObj.fileLOC) # Get raw ExIf data exif_data = im._getexif() # used to store a dictionary of the ExIf data labeled = {} # Catch any images that do not have any metadata tags try: for (key, val) in exif_data.items(): labeled[TAGS.get(key)] = val except AttributeError: print("AttributeError: This image has no readable ExIf Tags") # Write ExIf tags into text files, # ExIf-data-dump.txt: used for all ExIf data # ExIf-data-parsed.txt: used for specific useful ExIf data f = open("ExIf-data-dump.txt", "a+") f2 = open("ExIf-data-parsed.txt", "a+") f.write("------------------------------------------------------------ \n") f.write(imgObj.fileName + " \n") f.write("------------------------------------------------------------ \n") f2.write("------------------------------------------------------------ \n") f2.write(imgObj.fileName + " \n") f2.write("------------------------------------------------------------ \n") # List of all the useful ExIf data tags keyList = [ "DateTimeOriginal", "DateTimeDigitized", "ExifImageWidth", "ExifImageHeight", "Make", "Model", "XResolution", "YResolution", "ISOSpeedRatings", "ResolutionUnit", "WhiteBalance" ] for key in labeled: # Filter out keys that contain un-usable binary data dumps if key == "MeteringMode" or key == "UserComment" or key == "MakerNote" or key == "PrintImageMatching": continue # Write to ExIf dump f.write(f"key:{key}, val:{labeled.get(key)} \n") if key in keyList: # If the label is useful write to ExIf parsed f2.write(f"key:{key}, val:{labeled.get(key)} \n") f.close() f2.close()
def _get_exif_data(self): if self._image._getexif(): for tag in self._image._getexif(): try: decoded = TAGS.get(tag, tag) self._pil_tags[decoded] = self._image._getexif().get(tag) except AttributeError as e: # print("AttributeError" + str(e)) pass try: exif = exifread.process_file(self._image, details=True) self._exif_read_tags = exif except AttributeError as e: # print("AttributeError" + str(e)) pass except MemoryError as e: # print("MemoryError" + str(e)) pass
def testForExif(imgFileName): try: print("imgFileName: " + imgFileName) exifData = {} imgFile = Image.open(imgFileName) info = imgFile._getexif() if info: for (tag, value) in info.items(): #print("tag: " + tag + " value: " + value) decoded = TAGS.get(tag, tag) exifData[decoded] = value exifGPS = exifData['GPSInfo'] if exifGPS: print('[*] ' + imgFileName +\ ' contains GPS MetaData') except: #print('testForExif error') pass
def get_coordinates(directory, filename, exiftool): #extract only the gps data from exif mov_time = datetime.datetime.now() if filename.lower().endswith( ".mov"): #we got a movie on our hands, can't use pillow print("using exiftool on ", filename) # result = subprocess.run(['exiftool', '-GPSLatitude#', os.path.join(directory,filename)], stdout=subprocess.PIPE) result = exiftool.get_metadata(os.path.join(directory, filename)) latitude = result.get('Composite:GPSLatitude', 0) longitude = result.get('Composite:GPSLongitude', 0) date = result.get('QuickTime:CreateDate', '') mov_time1 = datetime.datetime.now() print("movie processing: ", (mov_time1 - mov_time).total_seconds()) return {'coords': (latitude, longitude), 'date': date} else: #get exif image = Image.open(os.path.join(directory, filename)) image.verify() exif = image._getexif() if not exif: print("No EXIF metadata found found. Skipping ", filename) return {'coords': (0, 0), 'date': ''} #get geotagging geotagging = {} for (idx, tag) in TAGS.items(): if tag == 'GPSInfo': if idx not in exif: print("No EXIF geotagging found. Skipping ", filename) return {'coords': (0, 0), 'date': ''} for (key, val) in GPSTAGS.items(): if key in exif[idx]: geotagging[val] = exif[idx][key] if tag == 'DateTimeOriginal': if idx not in exif: print("No EXIF Date found.") date = '' else: date = exif[idx] img_time = datetime.datetime.now() print("image processing: ", (img_time - mov_time).total_seconds()) return {'coords': get_coords_from_geotag(geotagging), 'date': date}
def getexptime(filename): im = Image.open(filename) try: exif = im._getexif() except AttributeError: return 1.0 exif_table = {} for tag_id, value in exif.items(): tag = TAGS.get(tag_id, tag_id) exif_table[tag] = value expo_str = 'ExposureTime' expo_time = 1.0 if expo_str in exif_table: expo_tubple = exif_table[expo_str] expo_time = expo_tuple[0] / expo_tuble[1] return expo_time
def main(): img_file = arg_parser() with Image.open(img_file) as img: # extract EXIF data exifdata = img.getexif() #Save tags names tags_names = [] for x in exifdata: tag = TAGS.get(x, x) tags_names.append((x, tag)) try: while True: menu(exifdata, tags_names) except KeyboardInterrupt: exit(0)
def getExifData( image): # pass image path --> turns image to a php-ish standard exif_data = {} img = image dataExif = img._getexif() if dataExif: for tag, value in dataExif.items(): decoded = TAGS.get(tag, tag) if decoded == "GPSInfo": gpsData = {} for each in value: subDecoded = GPSTAGS.get(each, each) gpsData[subDecoded] = value[each] exif_data[decoded] = gpsData else: exif_data[decoded] = value return exif_data
def fix_orientation(self, pImg): """ `lImg` can be an Image instance or a path to an image file. `save_over` indicates if the original image file should be replaced by the new image. * Note: `save_over` is only valid if `lImg` is a file path. """ path = pImg lImg = Image.open(pImg) lExif = lImg._getexif() if lExif != None: for tag, value in lExif.items(): decoded = TAGS.get(tag, tag) if decoded == 'Orientation': if value == 3: lImg = lImg.rotate(180) if value == 6: lImg = lImg.rotate(270) if value == 8: lImg = lImg.rotate(90) break lImg.save(path, quality = 95)
def get_exif_data(fname): """ 获取EXIF信息 :param fname: 影像文件路径 :return: 字典类型的EXIF信息 """ ret = {} try: img = Image.open(fname) if hasattr(img, '_getexif'): exifinfo = img._getexif() if exifinfo != None: for tag, value in exifinfo.items(): decoded = TAGS.get(tag, tag) ret[decoded] = value except IOError: print 'IOERROR ' + fname return ret
def adjust_image_orientation(cls, image): """Since the iPhone will store an image on its side but with EXIF data stating that it should be rotated, we need to find that EXIF data and correctly rotate the image before storage.""" if hasattr(image, '_getexif'): exif = image._getexif() if exif: for tag, value in exif.items(): decoded = TAGS.get(tag, tag) if decoded == 'Orientation': if value == 6: image = image.rotate(-90) if value == 8: image = image.rotate(90) if value == 3: image = image.rotate(180) break return image
def get_image_info(image_tmp): images = [ f for f in os.listdir(image_dir) if os.path.isfile(os.path.join(image_dir, f)) ] for image in images: dict_image = {} dict_image["Image_Name"] = image img = image_dir + "/" + image open_image = Image.open(img) exifdata = open_image.getexif() for tag_id in exifdata: # get the tag name, instead of human unreadable tag id tag = TAGS.get(tag_id, tag_id) data = exifdata.get(tag_id) # decode bytes if isinstance(data, bytes): data = data.decode() if tag == "ApertureValue": stop_value = float(f"{data}") f_stop = math.ceil(math.sqrt(pow(2, stop_value))) dict_image["Aperture"] = f_stop if tag == "ISOSpeedRatings": dict_image["ISO"] = f"{data}" if tag == "DateTime": dict_image["Date_Time"] = f"{data}" if tag == "ShutterSpeedValue": shutter_val = float(f"{data}") prod = math.ceil(pow(2, shutter_val)) rounded = round(prod / 10) * 10 dict_image["Shutter_Speed"] = rounded # info = shutter_val.split(", ") # num = info[0].replace("(","") # den = info[1].replace("(","") # div = float(num)/float(den) # prod = math.ceil(pow(2,div)) # dict_image["Shutter_Speed"] = prod image_tmp.append(dict_image)
def testForExif(imgFileName): """to get the exif information""" try: exifData = {} imgFile = Image.open(imgFileName) info = imgFile._getexif() if info: #la = info[34853][2][0][0] + info[34853][2][1][0] / 60.0 + info[34853][2][2][0] / 360000.0 # lo = info[34853][4][0][0] + info[34853][4][1][0] / 60.0 + info[34853][4][2][0] / 360000.0 for (tag, value) in info.items(): decoded = TAGS.get(tag, tag) exifData[decoded] = value exifGPS = exifData['GPSInfo'] if exifGPS: print "[+] " + imgFileName + Fore.RED + " has GPS location " #+ Getlocation(la,lo) except: pass
def lat_lon(file): """ returns a dict of lat, lon, alt, filename values, given an input file path as string example: latlong("path/to/file") or latlon(variable) """ img = Image.open(file) # info = img._getexif() filename = path_leaf(file) # build a dict of decoded exif keys and values decoded = dict((TAGS.get(key, key), value) for key, value in info.items()) info: Dict[str, Union[Union[None, float, str], Any]] = { "filename": filename, "lat": None, "lon": None, "timestamp": None, "altitude": None, } # ensure that this photo contains GPS data, or return an empty dict: if not decoded.get('GPSInfo'): return info lat = [float(x) / float(y) for x, y in decoded['GPSInfo'][2]] lon = [float(x) / float(y) for x, y in decoded['GPSInfo'][4]] alt = float(decoded['GPSInfo'][6][0]) / float(decoded['GPSInfo'][6][1]) timestamp = decoded['DateTimeOriginal'] # assign values to dict info['filename'] = filename info['lat'] = (lat[0] + lat[1] / 60) info['lon'] = (lon[0] + lon[1] / 60) info['timestamp'] = dt.strptime( timestamp, "%Y:%m:%d %H:%M:%S").strftime("%Y/%m/%d %H:%M:%S") info['altitude'] = alt # corrections if necessary if decoded['GPSInfo'][1] == "S": info['lat'] *= -1 if decoded['GPSInfo'][3] == "W": info['lon'] *= -1 # if we're below sea level, the value's negative if decoded['GPSInfo'][5] == 1: info['altitude'] *= -1 return info
def get_image_meta(file: Path): meta = {} try: with Image.open(file) as image: metadata = image.getexif() for tag_id in metadata: # get the tag name, instead of human unreadable tag id tag = TAGS.get(tag_id, tag_id) data = metadata.get(tag_id) if tag_id == 59932: continue meta[str(tag)] = parse_tag_data(data) except UnidentifiedImageError as e: print(e) return None else: return meta
def print_exiftool_data(img_filename): data = {} try: img_file = Image.open(img_filename) info = img_file._getexif() if not info: return for (tag, value) in info.items(): decoded = TAGS.get(tag, tag) data[decoded] = value exifGPS = data["GPSInfo"] if not exifGPS: return print("[*] {} contains GPS MetaData".format(img_filename)) except Exception: pass
def get_exif_data(image): """ Returns a dictionary from the exif data of an PIL Image item. Also converts the GPS Tags https://gist.github.com/valgur/2fbed04680864fab1bfc """ info = image._getexif() if not info: return {} exif_data = {TAGS.get(tag, tag): value for tag, value in info.items()} def is_fraction(val): return isinstance(val, tuple) and len(val) == 2 and isinstance( val[0], int) and isinstance(val[1], int) def frac_to_dec(frac): return float(frac[0]) / float(frac[1]) if 'GPSInfo' in exif_data: gpsinfo = {GPSTAGS.get(t, t): v for t, v in exif_data['GPSInfo'].items()} for tag, value in gpsinfo.items(): if is_fraction(value): gpsinfo[tag] = frac_to_dec(value) elif all(is_fraction(x) for x in value): gpsinfo[tag] = tuple(map(frac_to_dec, value)) exif_data['GPSInfo'] = gpsinfo return exif_data