def EXIF(self): try: return EXIF.process_file(open(self.image.path, 'rb')) except: try: return EXIF.process_file(open(self.image.path, 'rb'), details=False) except: return {}
def processEXIF(self): if hasattr(self, 'photoBody'): input = self.photoBody.getInputStream() else: input = file(self.file, 'r') data = input.read() input.close() stream = cStringIO.StringIO(data) try: exif = EXIF.process_file(stream) # First try DateTimeOriginal, falling back to DateTime takenString = str( exif.get('EXIF DateTimeOriginal', exif['Image DateTime'])) timestamp = time.mktime( time.strptime(takenString, "%Y:%m:%d %H:%M:%S")) self.dateTaken = datetime.fromtimestamp(timestamp) if self.dateTaken.tzinfo is None: self.dateTaken = self.dateTaken.replace( tzinfo=self.itsView.tzinfo.default) self.exif = {} for (key, value) in exif.iteritems(): if isinstance(value, EXIF.IFD_Tag): self.exif[key] = unicode(value.printable) else: self.exif[key] = unicode(value) except Exception, e: logger.debug("Couldn't process EXIF of Photo %s (%s)" % \ (self.itsPath, e))
def _parse_and_add_exif(self): import EXIF tags = EXIF.process_file(open(self.image.path,'rb')) self.make = smart_unicode(tags.get('Image Make', '')).strip() self.model = smart_unicode(tags.get('Image Model', '')).strip() self.date_raw = smart_unicode(tags.get('EXIF DateTimeOriginal', '')).strip() self.width = smart_unicode(tags.get('EXIF ExifImageWidth', '')).strip() self.height = smart_unicode(tags.get('EXIF ExifImageHeight', '')).strip() self.orientation = smart_unicode(tags.get('Image Orientation', '')).strip() self.resolution_unit = smart_unicode(tags.get('Image ResolutionUnit', '')).strip() self.x_resolution = smart_unicode(tags.get('Image XResolution', '')).strip() self.y_resolution = smart_unicode(tags.get('Image YResolution', '')).strip() self.software = smart_unicode(tags.get('Image Software', '')).strip() self.exposure_time = smart_unicode(tags.get('EXIF ExposureTime', '')).strip() self.exposure_bias = smart_unicode(tags.get('EXIF ExposureBiasValue', '')).strip() self.exposure_program = smart_unicode(tags.get('EXIF ExposureProgram', '')).strip() self.flash = smart_unicode(tags.get('EXIF Flash', '')).strip() self.f_number = smart_unicode(tags.get('EXIF FNumber', '')).strip() self.aperture = smart_unicode(tags.get('EXIF MaxApertureValue', '')).strip() self.metering_mode = smart_unicode(tags.get('EXIF MeteringMode', '')).strip() self.focal_length = smart_unicode(tags.get('EXIF FocalLength', '')).strip() self.color_space = smart_unicode(tags.get('EXIF ColorSpace', '')).strip() self.focal_length = smart_unicode(tags.get('EXIF FocalLength', '')).strip() self.ycbcr_positioning = smart_unicode(tags.get('Image YCbCrPositioning', '')).strip() self.sensing_method = smart_unicode(tags.get('EXIF SensingMethod', '')).strip() if not self.date_created: if self.date_raw: self.date_created = self.date_raw
def rename_file(self, filename, media_type): if media_type == "photo": with open(filename, "rb") as file_stream: try: tags = EXIF.process_file(file_stream) datestr = str(tags["EXIF DateTimeDigitized"]) date_object = datetime.datetime.strptime(datestr, "%Y:%m:%d %H:%M:%S") formatted_date = datetime.datetime.strftime(date_object, "%Y-%m-%d_%I-%M-%S_%p") self.year = str(datetime.datetime.strftime(date_object, "%Y")) self.month = str(datetime.datetime.strftime(date_object, "%m")) self.day = str(datetime.datetime.strftime(date_object, "%d")) camera_model = str(tags["Image Model"]).replace(" ", "_") image_filename = os.path.split(filename)[1] if image_filename.startswith("DSC"): image_filename_base = os.path.splitext(image_filename)[0] self.new_name = (camera_model + "_" + image_filename_base[4:] + "_" + formatted_date + ".jpg") else: self.new_name = camera_model + "_" + formatted_date + ".jpg" except KeyError: sys.stderr.write("Key error reading EXIF tags") self.log.error("Key error reading EXIF tags") pass else: video_filename = self.get_video_date(filename) video_root, video_ext = os.path.splitext(filename) self.new_name = video_filename + video_ext.lower() return self.new_name
def _load_fdl_one(self, filename, file_data_list, movies): fn = fs_enc(filename) basename, extension = os.path.splitext(filename) with open(filename) as file: tags = EXIF.process_file(file, stop_tag="Image DateTime", details=False) if "Image DateTime" in tags: dt = datetime.datetime.strptime(str(tags["Image DateTime"]), "%Y:%m:%d %H:%M:%S") else: dt = modification_date(fn) # Set album time to the time of the oldest photo in the album if dt < self.album_datetime: self.album_datetime = dt print u"%s: %s" % (filename, dt) file_size = os.path.getsize(fn) if file_size < MAX_SIZE: checksum = md5_for_file(file) else: checksum = md5_for_string(fn + str(file_size)) file_data = {"filename": filename, "datetime": dt, "checksum": checksum} file_data_list.append(file_data) # Maintain a set of all movies to filter out thumbnail # images below. if extension.lower() in (".mov", ".mpg", ".mpeg"): movies.add(basename)
def Retrieve(folder): for f in os.listdir(folder): fullPath = os.path.join(folder, f) try: with open(fullPath, 'rb') as fileObject: #this is the 'date taken' attribute of the image tag = "EXIF DateTimeOriginal" # get the tags and stop processing the file after reaching a tag (faster processing) data = EXIF.process_file(fileObject, details=False, stop_tag=tag) #if file has EXIT data, than it is a picture if data: #not all pictures have the 'date taken' attribute try: #2012:12:18 15:40:52 -> 2012-12-18 15:40:52 d, t = str(data[tag]).split() d = d.replace(':', '-') ts = '%s %s' % (d, t) yield dateutil.parser.parse(ts), fullPath except KeyError: pass else: pass except IOError as e: print "I/O error({0}): {1}".format(e.errno, e.strerror)
def main(): dom = xml.dom.minidom.parse(sys.argv[1]) out = open(sys.argv[2], "wt") mismatched = None if len(sys.argv) > 3: mismatched = open(sys.argv[3], "wt") min_time, max_time = get_time_span(dom) images = {} for wpt in dom.getElementsByTagName("wpt"): name = text(wpt.getElementsByTagName("name")[0]) images[name] = True print "Start time:", min_time print "End time :", max_time print "Total deduplicated input A/V waypoints:", len(images.keys()) for fname in images.keys(): # print "Processing " + fname fullname = "../avnotes/" + fname if os.path.exists(fullname): f = open(fullname) tags = exifread.process_file(f) if len(tags) == 0: # Non-JPEG file, like mp3 or mp4 st = os.stat(fullname) d = datetime.fromtimestamp(st[stat.ST_MTIME]) else: d = tags["Image DateTime"] d = datetime.strptime(str(d), "%Y:%m:%d %H:%M:%S") d = local2utc(d) # print d if d < min_time or d > max_time: del images[fname] else: print "Warning: %s doesn't exists, so removing its waypoint either" % fullname del images[fname] print "Total A/V waypoints belonging to the track:", len(images.keys()) out.write(GPX_HEADER) for n in dom.getElementsByTagName("trk"): print >>out, " ", n.toxml() seen = {} for wpt in dom.getElementsByTagName("wpt"): name = text(wpt.getElementsByTagName("name")[0]) if name in images: if name not in seen: print >>out, " ", wpt.toxml() seen[name] = True else: if mismatched and name not in seen: print >>mismatched, " ", wpt.toxml() seen[name] = True print >>out, "</gpx>"
def processEXIF(self): if hasattr(self, 'photoBody'): input = self.photoBody.getInputStream() else: input = file(self.file, 'r') data = input.read() input.close() stream = cStringIO.StringIO(data) try: exif = EXIF.process_file(stream) # First try DateTimeOriginal, falling back to DateTime takenString = str(exif.get('EXIF DateTimeOriginal', exif['Image DateTime'])) timestamp = time.mktime(time.strptime(takenString, "%Y:%m:%d %H:%M:%S")) self.dateTaken = datetime.fromtimestamp(timestamp) if self.dateTaken.tzinfo is None: self.dateTaken = self.dateTaken.replace(tzinfo=self.itsView.tzinfo.default) self.exif = {} for (key, value) in exif.iteritems(): if isinstance(value, EXIF.IFD_Tag): self.exif[key] = unicode(value.printable) else: self.exif[key] = unicode(value) except Exception, e: logger.debug("Couldn't process EXIF of Photo %s (%s)" % \ (self.itsPath, e))
def exif_to_human(image): fields = ( ('Image Make', _('Camera manifacture')), ('Image Model', _('Camera model')), ('EXIF DateTimeDigitized', _('Digitized time')), ('EXIF DateTimeOriginal', _('Taken time')), ('Image Software', _('Image software')), ('EXIF ColorSpace', _('Color space')), ('EXIF FocalLength', _('Focal length')), ('EXIF FocalLengthIn35mmFilm', _('Forcal length(in 35mm)')), ('EXIF ISOSpeedRatings', _('ISO speed')), ('EXIF MaxApertureValue', _('Max aperture')), ('EXIF ExposureMode', _('Exposure mode')), ('EXIF ExposureProgram', _('Exposure program')), ('EXIF ExposureTime', _('Exposure time')), ('EXIF Flash', _('Flash')), ('EXIF LightSource', _('Light source')), ('EXIF DigitalZoomRatio', _('Digital zoom ratio')), ('EXIF ExifImageLength', _('Image length')), ('EXIF ExifImageWidth', _('Image width')), ('EXIF WhiteBalance', _('White balance')), ('EXIF Sharpness', _('Sharpness')), ('EXIF Contrast', _('Contrast')), ) exif = [] tags = EXIF.process_file(image, strict=True, stop_tag='JPEGThumbnail') for f in fields: if tags.has_key(f[0]): exif.append((f[1], str(tags[f[0]]))) image.close() return exif
def buildDateFolders(path = "", destination='', copy = True): files = fetchFiles(path) print("Processing files into dated folders for {0}".format(path)) for eachFile in files: with open(eachFile.path, 'rb') as fh: tags = EXIF.process_file(fh, stop_tag="EXIF DateTimeOriginal") try: dateTaken = tags["EXIF DateTimeOriginal"].values except: dateTaken = None if dateTaken: try: destYearDir = "{0}\\{1}".format(destination, dateTaken.split(":")[0]) destMonthDir = '{0}\\{1}'.format(destYearDir, dateTaken.split(":")[1]) destMonthDay = '{0}\\{1}'.format(destMonthDir, dateTaken.split(":")[2].split(" ")[0]) if not os.path.isdir(destYearDir): os.mkdir(destYearDir) if not os.path.isdir(destMonthDir): os.mkdir(destMonthDir) if not os.path.isdir(destMonthDay): os.mkdir(destMonthDay) if copy: if not os.path.isfile(os.path.join(eachFile.name, destMonthDay)): print("Copying %s" % eachFile.name) shutil.copy(eachFile.path, destMonthDay) else: if not os.path.isfile(os.path.join(eachFile.name, destMonthDay)): print("Moving %s from %s to %s" % (eachFile.name, eachFile.path, destMonthDay)) shutil.move(eachFile.path, destMonthDay) except: pass print('FINISHED MOVING FILES TO DATE FOLDERS')
def get_file_items(self, window, files): """Called when the user selects a file in Nautilus. We want to check whether those are supported files or directories with supported files.""" supported = [] for f in files: if f.get_mime_type() in FORMATS: name = urllib.unquote(f.get_uri()[7:]) supported.append(name) elif f.is_directory(): supported = process(urllib.unquote(f.get_uri()[7:]), supported) if not supported: return have_exif = False for path in supported: img_file = open(path, "rb") tags = EXIF.process_file(img_file) if tags.has_key("EXIF DateTimeOriginal"): have_exif = True break if not have_exif: return item = nautilus.MenuItem("NautilusPython::rename_exif_date_item", "Rename to EXIF date" , "Rename to EXIF date", "nautilus-rename-exif-date") item.connect("activate", self.menu_activate_cb, supported) return item,
def post(self): # 画像データの取得 image = self.request.get("image") # EXIFの解析 sio = StringIO.StringIO(image) tags = EXIF.process_file(sio) # 画像の日付 if tags.get('Image DateTime') != None: st = time.strptime(tags['Image DateTime'].values, '%Y:%m:%d %H:%M:%S') imgDateTime = datetime.datetime(*st[0:6]) else: imgDateTime = None # 緯度 if tags.get('GPS GPSLatitude') != None: lat = self.__getDegree(tags['GPS GPSLatitude'].values) else: lat = 0.0 # 軽度 if tags.get('GPS GPSLongitude') != None: lon = self.__getDegree(tags['GPS GPSLongitude'].values) else: lon = 0.0 # データの保存 pictData = PictureData(picture = image, geo = "%f, %f" % (lat, lon), imgdatetime = imgDateTime) PictureCtrls.set(pictData) self.redirect('/')
def rename_file(self, filename, media_type): if media_type == "photo": with open(filename, "rb") as file_stream: try: tags = EXIF.process_file(file_stream) datestr = str(tags["EXIF DateTimeDigitized"]) date_object = datetime.datetime.strptime(datestr, "%Y:%m:%d %H:%M:%S") formatted_date = datetime.datetime.strftime(date_object, "%Y-%m-%d_%I-%M-%S_%p") self.year = str(date_object.year) self.month = str(date_object.month) self.day = str(date_object.day) camera_model = str(tags["Image Model"]).replace(" ", "_") self.new_name = camera_model + "_" + formatted_date + ".jpg" except KeyError: sys.stderr.write("Key error reading EXIF tags") self.log.error("Key error reading EXIF tags") pass else: video_filename = self.get_video_date(filename) video_root, video_ext = os.path.splitext(filename) self.new_name = video_filename + video_ext.lower() return self.new_name
def get_exif_data(filename): """Returns a dict of EXIF data for the given image file.""" assert os.path.exists(filename), 'File not found: %s' % filename infile = open(filename, 'rb') exifdata = EXIF.process_file(infile) infile.close() return exifdata
def exim_fetch(filename): f = open(filename, 'rb') tags = EXIF.process_file(f) timelist = [ item.split(':') for item in str(tags['EXIF DateTimeOriginal']).split(' ') ] timelist = list(itertools.chain(*timelist)) timelist = [ int(item) for item in timelist ] return tags
def main(): dom = xml.dom.minidom.parse(sys.argv[1]) out = open(sys.argv[2], "wt") mismatched = None if len(sys.argv) > 3: mismatched = open(sys.argv[3], "wt") min_time, max_time = get_time_span(dom) images = {} for wpt in dom.getElementsByTagName("wpt"): name = text(wpt.getElementsByTagName("name")[0]) images[name] = True print "Start time:", min_time print "End time :", max_time print "Total deduplicated input A/V waypoints:", len(images.keys()) for fname in images.keys(): # print "Processing " + fname fullname = "../avnotes/" + fname if os.path.exists(fullname): f = open(fullname) tags = exifread.process_file(f) if len(tags) == 0: # Non-JPEG file, like mp3 or mp4 st = os.stat(fullname) d = datetime.fromtimestamp(st[stat.ST_MTIME]) else: d = tags["Image DateTime"] d = datetime.strptime(str(d), "%Y:%m:%d %H:%M:%S") d = local2utc(d) # print d if d < min_time or d > max_time: del images[fname] else: print "Warning: %s doesn't exists, so removing its waypoint either" % fullname del images[fname] print "Total A/V waypoints belonging to the track:", len(images.keys()) out.write(GPX_HEADER) for n in dom.getElementsByTagName("trk"): print >> out, " ", n.toxml() seen = {} for wpt in dom.getElementsByTagName("wpt"): name = text(wpt.getElementsByTagName("name")[0]) if name in images: if name not in seen: print >> out, " ", wpt.toxml() seen[name] = True else: if mismatched and name not in seen: print >> mismatched, " ", wpt.toxml() seen[name] = True print >> out, "</gpx>"
def read_EXIF_data(self): tags = EXIF.process_file_from_path(self.pathin) for key, attr in EXIF_map.iteritems(): if tags.has_key(key): val = str(tags[key]) else: val = "" setattr(self, attr, val)
def exif_test(ifile): try: im = open(ifile, 'rb') tags = EXIF.process_file(im) tag_count = len(tags) return (True, tag_count) except: return (False, None)
def exim_fetch(filename): f = open(filename, 'rb') tags = EXIF.process_file(f) test = [ item.split(':') for item in str(tags['EXIF DateTimeOriginal']).split(' ') ] test = list(itertools.chain(*test)) test = [ int(item) for item in test ] when = datetime(test[0], test[1], test[2], test[3], test[4], test[5]) return when
def exif_data(self): if not hasattr(self, "_exif"): media_path = settings.GALLERY_SETTINGS.get('media_path') ex = self.get_exported() f = open(os.path.join(media_path, ex.normal_relpath.decode('string_escape'))) self._exif = EXIF.process_file(f) f.close() return self._exif
def ParseHYPACK(self): jpegfolder = self.entryLabel2.get() parsefile = self.outLabel2.get() tempfolder = "c:/temp/" if os.path.exists(tempfolder): usetmpfolder = tempfolder else: usetmpfolder = tkFileDialog.askdirectory( initialdir="C:/", title='Pick temporary folder') tmpfile = "exifjunk.txt" #the normpath makes it look right for windows. tempfile = os.path.normpath(os.path.join(usetmpfolder, tmpfile)) print tempfile output = open(tempfile, "w") for infile in glob.glob(os.path.join(jpegfolder, '*.JPG')): # in navfolder: dir_name, file_name = os.path.split(infile) photo_name, photo_ext = os.path.splitext(file_name) f = open(infile, "rb") tags = EXIF.process_file(f) tags['Filename'] = file_name tags['Dirname'] = dir_name imgtime = tags['EXIF DateTimeOriginal'] #taking the image time, parsing it and creating the epoch time to use for sorting imgstring = str(imgtime) datetimestuff = string.split(imgstring, " ") datestr = (datetimestuff[0]) timestr = (datetimestuff[1]) datestuff = string.split(datestr, ":") yearid = string.atoi(datestuff[0]) month = string.atoi(datestuff[1]) day = string.atoi(datestuff[2]) timestuff = string.split(timestr, ":") timehr = string.atoi(timestuff[0]) timemin = string.atoi(timestuff[1]) timesec = string.atoi(timestuff[2]) timeepoch = (time.mktime( (yearid, month, day, timehr, timemin, timesec, 0, 0, 0))) #this next line takes the path name and normalizes the case of a pathname #on Windows, it converts forward slashes to backward slashes. tags['Pathname'] = os.path.normpath(infile) #print info using template #add epoch time to the output so I can use it in the sort #this output actually writes to the temporary file - should overwrite if it exists output.write(template % PrintMap(tags) + ', ' + str(timeepoch) + '\n') output.close() unsorted_data = open(tempfile, 'r') data_list = [] data_list = [line.strip() for line in open(tempfile)] data_list.sort(key=lambda line: float(line.split(",")[8])) outputsort = open(parsefile, "w") outputsort.writelines("%s\n" % item for item in data_list) outputsort.close() unsorted_data.close() tkMessageBox.showinfo("JPEG Parse", "Done")
def getJpegDate(theFileName): theFile = open(theFileName, 'r') DTG = EXIF.process_file(theFile)["Image DateTime"].printable year = DTG[0:4] month = DTG[5:7] day = DTG[8:10] hour = DTG[11:13] return int(year), int(month), int(day), int(hour)
def __init__(self, file_path): """ EXIFReader 클래스 생성자 """ self.file_path = file_path # Open image file for reading (binary mode) f = open(file_path, 'rb') # Return Exif tags self.tags = EXIF.process_file(f)
def __init__(self, file_path): """ EXIFReader 클래스 생성자 """ self.file_path = file_path # Open image file for reading (binary mode) f = open(file_path, "rb") # Return Exif tags self.tags = EXIF.process_file(f)
def listFiles(pathOrigin, pathDest): i = 0 listError = [] for (path, dirs, files) in os.walk(pathOrigin): print "*** START Processing the following files in path:" + path print files #print dirs newFileName = "" for fileNameOrigin in files: i = i + 1 fileInfo = getInfo(path, fileNameOrigin) fileExtension = str.split(fileNameOrigin, ".") index = len(fileExtension) if (("JPG" in str(fileNameOrigin))): p = open(path + "/" + fileNameOrigin, "rb") tags = EXIF.process_file(p) p.close() for key in tags.keys(): if "datetimeoriginal" in str(key).lower(): dateTaken = str(tags[key]).split(' ') dateTakenNew = str(dateTaken[0]).replace( ':', '-') # 2009-12-13 dateTakenTimeNew = str(dateTaken[1]).replace(':', '-') newFileName = createName( (dateTakenNew + "_" + dateTakenTimeNew), path, pathDest, " ", 0) else: newFileName = createName(fileInfo[0], path, pathDest, " ", 0) newFileName = newFileName + "." + fileExtension[index - 1] newFileName.replace(" ", "") print "Path: " + path + " -> Processing " + str(i) + " files OK" fileSource = open(path + "/" + fileNameOrigin, 'r') fileDest = open(newFileName, "w") # print "Convert FROM " + path+"/"+fileNameOrigin + " TO " + newFileName try: shutil.copyfileobj(fileSource, fileDest) shutil.copystat(path + "/" + fileNameOrigin, newFileName) fileSource.close() fileDest.close() except IOError as err: fileSource.close() fileDest.close() listError.append(path + "/" + fileNameOrigin) print err pass print "FOUND " + str(len(listError)) + " ERRORS" print "Error List" print listError fileError = open("Fotos_List_Errors.log", "a") fileError.write(time.strftime("%a, %d %b %Y %H:%M:%S ", time.gmtime())) pickle.dump(listError, fileError) fileError.close() return
def getDigTime(filename): with open(filename,'rb') as f: tags = EXIF.process_file(f) try: digitized = datetime.strptime(str(tags['EXIF DateTimeOriginal']),"%Y:%m:%d %H:%M:%S") except KeyError: return None # Get frame number as first elt print "processed",filename return digitized
def getExifDate(path): try: f = open(path, 'rb') data = EXIF.process_file(f, details=False) f.close() if 'EXIF DateTimeOriginal' in data: year, month, day = data['EXIF DateTimeOriginal'].printable.split(' ')[0].split(':') return year, month, day except Exception, err: sys.stderr.write('ERROR in getExifDate: %s\n' % str(err))
def getdate(self,filename): imagefile = file(filename,"rb") imagetags = EXIF.process_file(imagefile) imagefile.close() # print dir(imagetags['EXIF DateTimeOriginal']) # return imagetags['EXIF DateTimeOriginal'] datestr = imagetags['EXIF DateTimeOriginal'] datelist = re.search(r'(....):(..):(..) (..):(..):(..).*',datestr.printable).group date = datetime.datetime(int(datelist(1)),int(datelist(2)), int(datelist(3)), int(datelist(4)), int(datelist(5)), int(datelist(6))) return date
def ParseHYPACK(self): jpegfolder = self.entryLabel2.get() parsefile = self.outLabel2.get() tempfolder = "c:/temp/" if os.path.exists(tempfolder): usetmpfolder = tempfolder else: usetmpfolder = tkFileDialog.askdirectory(initialdir="C:/", title='Pick temporary folder') tmpfile = "exifjunk.txt" #the normpath makes it look right for windows. tempfile = os.path.normpath(os.path.join(usetmpfolder, tmpfile)) print tempfile output = open(tempfile,"w") for infile in glob.glob(os.path.join(jpegfolder,'*.JPG')): # in navfolder: dir_name, file_name=os.path.split(infile) photo_name, photo_ext=os.path.splitext(file_name) f=open(infile,"rb") tags=EXIF.process_file(f) tags['Filename']=file_name tags['Dirname']=dir_name imgtime=tags['EXIF DateTimeOriginal'] #taking the image time, parsing it and creating the epoch time to use for sorting imgstring = str(imgtime) datetimestuff = string.split(imgstring, " ") datestr = (datetimestuff[0]) timestr = (datetimestuff[1]) datestuff = string.split(datestr,":") yearid = string.atoi(datestuff[0]) month = string.atoi(datestuff[1]) day = string.atoi(datestuff[2]) timestuff = string.split(timestr,":") timehr = string.atoi(timestuff[0]) timemin = string.atoi(timestuff[1]) timesec = string.atoi(timestuff[2]) timeepoch = (time.mktime((yearid,month,day,timehr,timemin,timesec,0,0,0))) #this next line takes the path name and normalizes the case of a pathname #on Windows, it converts forward slashes to backward slashes. tags['Pathname']=os.path.normpath(infile) #print info using template #add epoch time to the output so I can use it in the sort #this output actually writes to the temporary file - should overwrite if it exists output.write( template % PrintMap(tags) + ', ' + str(timeepoch) + '\n') output.close() unsorted_data = open(tempfile,'r') data_list = [] data_list = [line.strip() for line in open(tempfile)] data_list.sort(key=lambda line: float(line.split(",")[8])) outputsort=open(parsefile,"w") outputsort.writelines( "%s\n" % item for item in data_list ) outputsort.close() unsorted_data.close() tkMessageBox.showinfo("JPEG Parse", "Done")
def get_exif(picfile): """ get EXIF fields in the picture and return datas as key:value dictionnary """ #définition des champs EXIF que nous souhaitons utiliser EXIF_fields =["Image DateTime", "Image Model", "Image Orientation", #"Image ResolutionUnit", #"Image XResolution", #"Image YResolution", #"Image Make", "EXIF DateTimeOriginal", "EXIF ExifImageWidth", #"EXIF FileSource", #"EXIF Flash", "EXIF SceneCaptureType", #"EXIF DigitalZoomRatio", "EXIF DateTimeDigitized", "GPS GPSLatitude", "GPS GPSLongitude", #"EXIF ExifVersion"] ] #ouverture du fichier f=open(picfile,"rb") # et lecture des tags EXIF (on ne prend pas les makernotes, données constructeurs) tags = EXIF.process_file(f,details=False) #fermeture du fichier f.close() #pré-initialisation des champs à mettre en base picentry={} #on parcours les infos EXIF qu'on souhaite récupérer for tag in EXIF_fields: #for tag in tags: #mais on ne traite que les tags présents dans la photo if tag in tags.keys(): if tag in ["EXIF DateTimeOriginal","EXIF DateTimeDigitized","Image DateTime"]: tagvalue = time.strftime("%Y-%m-%d %H:%M:%S",time.strptime(tags[tag].__str__(),"%Y:%m:%d %H:%M:%S")) #tagvalue = time.mktime(time.strptime(tags[tag].__str__(),"%Y:%m:%d %H:%M:%S")) #tagvalue = tags[tag].__str__() else: tagvalue = tags[tag].__str__() try: #on créé un champ dans la base pour une info exif if tag in ["EXIF DateTimeOriginal","EXIF DateTimeDigitized","Image DateTime"]: addColumn("files",tag,"DATETIME") else: addColumn("files",tag) picentry[tag]=tagvalue except Exception, msg: log(">> get_exif %s"%picfile ) log( "%s - %s"%(Exception,msg) ) log( "~~~~" ) log( "" )
def __init__(self, filename): self.filename = filename self.datetime = None self.tags = {} with open(filename, 'rb') as f: self.exif_data = EXIF.process_file(f) self.set_file_tags() self.set_exif_tags() self.set_datetime_tags()
def getExifDate(fileName): import EXIF file = open(fileName,"rb") data = EXIF.process_file(file) if not data: return "No EXIF Information available." timestamp = data['EXIF DateTimeDigitized'] data = str(timestamp) out = data[0:10].replace(':','_') return out
def getExifDate(fileName): import EXIF file = open(fileName, "rb") data = EXIF.process_file(file) if not data: return "No EXIF Information available." timestamp = data['EXIF DateTimeDigitized'] data = str(timestamp) out = data[0:10].replace(':', '_') return out
def get_timestamp_from_exif(imagePath): # from file path to time stamp imageFile = open(imagePath, "rb") tags = exif.process_file(imageFile, stop_tag="DateTimeOriginal") if "EXIF DateTimeOriginal" not in tags: return None else: # you need to convert timestamp to string object timestamp = str(tags["EXIF DateTimeOriginal"]) dateAndTime = datetime.datetime.strptime(timestamp, "%Y:%m:%d %H:%M:%S") return dateAndTime.strftime("%Y%m%d_%H%M%S")
def exim_fetch(filename): output = "None" try: f = open(filename, 'rb') tags = EXIF.process_file(f) output = str(tags['Image Orientation']) except: otuput = "Exception" finally: f.close() return output
def listFiles(pathOrigin, pathDest): i = 0 listError = [] for (path, dirs, files) in os.walk(pathOrigin): print "*** START Processing the following files in path:" + path print files #print dirs newFileName="" for fileNameOrigin in files: i = i+1 fileInfo = getInfo(path, fileNameOrigin) fileExtension = str.split(fileNameOrigin,".") index = len(fileExtension) if ( ("JPG" in str(fileNameOrigin)) ): p = open(path+"/"+fileNameOrigin,"rb") tags = EXIF.process_file(p) p.close() for key in tags.keys(): if "datetimeoriginal" in str(key).lower(): dateTaken = str(tags[key]).split(' ') dateTakenNew = str(dateTaken[0]).replace(':','-') # 2009-12-13 dateTakenTimeNew = str(dateTaken[1]).replace(':','-') newFileName = createName((dateTakenNew+"_"+dateTakenTimeNew), path, pathDest, " ",0) else: newFileName = createName(fileInfo[0], path, pathDest, " ",0) newFileName = newFileName + "." + fileExtension[index-1] newFileName.replace(" ","") print "Path: " + path + " -> Processing " + str(i) + " files OK" fileSource = open(path+"/"+fileNameOrigin, 'r') fileDest = open(newFileName,"w") # print "Convert FROM " + path+"/"+fileNameOrigin + " TO " + newFileName try: shutil.copyfileobj(fileSource, fileDest) shutil.copystat(path+"/"+fileNameOrigin, newFileName) fileSource.close() fileDest.close() except IOError as err: fileSource.close() fileDest.close() listError.append(path+"/"+fileNameOrigin) print err pass print "FOUND "+ str(len(listError)) +" ERRORS" print "Error List" print listError fileError = open("Fotos_List_Errors.log","a") fileError.write(time.strftime("%a, %d %b %Y %H:%M:%S ", time.gmtime())) pickle.dump(listError, fileError) fileError.close() return
def getthumbnail(imagename): imagedata = None if hasPyExif2: try: exif = pyexiv2.ImageMetadata(imagename) exif.read() except: logging.error("Can not read EXIF info from file %s, no preview." % imagename) return imagetype = "" if exif.mime_type == 'image/jpeg' or exif.mime_type == 'image/png': try: filereader = open(imagename,"rb") data = filereader.read() filereader.close() except: logging.error("Can not read file %s, no preview." % imagename) return imagetype = exif.mime_type else: try: data = exif.previews[-1].data except: logging.error("Can not read EXIF preview from file %s, no preview." % imagename) return imagetype = 'image/jpeg' elif hasEXIF: try: f = open(imagename,'rb') exif = EXIF.process_file(f, details=False) data = exif['JPEGThumbnail'] imagetype = 'image/jpeg' except: logging.error("Can not read file %s, no preview." % imagename) return elif hasExifTool: try: data = subprocess.Popen([exiftool_path,"-b","-ThumbnailImage",imagename],stdout=subprocess.PIPE).communicate()[0] imagetype = 'image/jpeg' except: pass try: if imagetype == 'image/jpeg': imagedata = wx.ImageFromStream(io.BytesIO(data), wx.BITMAP_TYPE_JPEG) elif imagetype == 'image/png': imagedata = wx.ImageFromStream(io.BytesIO(data), wx.BITMAP_TYPE_PNG) except: logging.error("Can not convert image %s with type %s, no preview." % (imagename, imagetype)) return imagedata
def getDateTaken(filePath): try: with open(filePath, 'rb') as fh: tags = EXIF.process_file(fh, stop_tag="EXIF DateTimeOriginal") try: dateTaken = tags["EXIF DateTimeOriginal"].values except: dateTaken = None except: print("WARNING cannot process %s" % filePath) dateTaken = None return dateTaken
def GetHeaders(the_file): """Handles getting the EXIF headers and returns them as a dict. Args: the_file: A file object Returns: a dict mapping keys corresponding to the EXIF headers of a file. """ data = EXIF.process_file(the_file, 'UNDEF', False, False, False) return data
def do(path): for root, dirs, files in os.walk(path): for filename in files: if not '.jpg' in filename.lower(): continue try: e = EXIF.process_file(open(os.path.join(root, filename),"rb")) img_number = str(e['MakerNote ImageNumber']) real_img_number = 10000*(int(img_number[0])-1) + int(img_number[3:]) print img_number, "\t", e['Image DateTime'], '\t', os.path.join(root, filename), '\t', real_img_number, '\t', e['Image Model'] except: pass
def get_exif_data(fname): """Get embedded EXIF data from image file.""" global log tags = {} try: img = open(fname, 'rb') tags = EXIF.process_file(img) img.close() except IOError: log.critical('IOERROR ' + fname) except: tags = get_pil_exif_data(fname) return tags
def create(self,contents): #extract exif and calculate readable coords from complicated exif e=EXIF.process_file(contents) try: (lat,lon,alt) = GetGps(e) except: print "couldn't do it?" #save it! self.coords = ('%s, %s' % (lon,lat)) self.image = contents self.save()
def GetDate(self): """ Retrieve the Date from EXIF Data """ f = open(self.path, 'rb') try: rawDate = EXIF.process_file(f) rawDate = str(rawDate['Image DateTime']) rawDate = rawDate[:10] rawDate = rawDate.split(':') except: rawDate = time.localtime()[0:3] return rawDate
def addPictures(self): """ Add already taken pictures to recording. If no recording is ongoing, ask user what data directory he wants to put the photos into. """ dir = self.dataDirectory #append self.name, if requiredself. s = dir.rstrip('/').split('/') if len(s) and s[-1] != self.name: dir += self.name + "/" if dir[-1] != '/': dir += "/" if not os.path.exists(dir): os.makedirs(dir) files = [ str(s) for s in QFileDialog.getOpenFileNames( self, self.tr("Choose images to be added to the photo directory"), os.path.expanduser("~"), self.tr("Photos (*.jpg *.jpeg)")) ] if files == []: return errorFiles = "" for f in files: fh = open(f, "rb") exif = EXIF.process_file(fh) fh.close() try: newfn = dir + str(exif["Image DateTime"]).replace( ":", "-").replace(" ", "_") + f[f.rfind("."):] shutil.copy2(f, newfn) except: errorFiles = errorFiles + f + "\n" if errorFiles != "": QMessageBox.warning( self, self.tr("Unprocessed files"), self. tr("The following files were not added (exif info/unsupported format): \n" ) + errorFiles) self.reloadThumbnailsCache()
def print_all(self, file_path): """모든 EXIF 정보를 STDOUT에 출력한다. """ # Open image file for reading (binary mode) f = open(file_path, 'rb') # Return Exif tags tags = EXIF.process_file(f) print "All Information of EXIF in " + file_path for tag in tags.keys(): if tag not in ('JPEGThumbnail', 'TIFFThumbnail', 'Filename', 'EXIF MakerNote'): print "Key: %s, value %s" % (tag, tags[tag])
def GetFileDate(file): """ Returns the date associated with a file. For JPEG files, it will use the EXIF data, if available """ try: import EXIF # EXIF.py from http://home.cfl.rr.com/genecash/digital_camera.html f = open(file, "rb") tags = EXIF.process_file(f) f.close() return str(tags['Image DateTime']) except (KeyError, ImportError): # EXIF not installed or no EXIF date available import os.path, time return time.ctime(os.path.getmtime(file))
def _extract_gps(self, image): """ Extracts the GPS coordinates (if present) from the given photo @param image: Raw image data @type image: String @return: GPS coordinates from the exif @rtype: Tuple (float, float, float) """ try: image = StringIO(image) exif = EXIF.process_file(image) return (self._extract_coord(exif, 'latitude'), self._extract_coord(exif, 'longitude'), self._extract_coord(exif, 'altitude')) except: return (0, 0, 0)
def menu_activate_cb(self, menu, names): """Called when the user selects the menu. Rename the selected files.""" for path in names: img_file = open(path, "rb") tags = EXIF.process_file(img_file) date = str(tags["EXIF DateTimeOriginal"]).replace(":", "-", 2) date = date.replace(":", "h", 1) date = date.replace(":", "m", 1) date = date.replace(":", "s", 1) dir_name = os.path.split(path)[0] file_name = os.path.split(path)[1] parts = file_name.split(".") if len(parts) == 1: extension = "" else: extension = "." + parts[-1] os.rename(path, dir_name + "/" + date + extension)
def exif_orient(image_file, pil_image): """\ Rotates pil_image according to the exif Orientation tag (if present) """ image_file.seek(0) tags = EXIF.process_file(image_file) keys = list(tags.keys()) if not keys: return pil_image try: orientation = int(str(tags['Image Orientation'])) if orientation in _orientations: pil_image = pil_image.transpose(_orientations[orientation]) elif orientation != 1: print('Unsupported EXIF Image Orientation:', orientation) except Exception as e: import traceback; traceback.print_exc() return pil_image
def get_exif_data(path): """ Get EXIF data from file. """ date = None width = None height = None cameramaker = None cameramodel = None try: file = open(path, 'rb') except: print "ERROR: Opening image file", path return date, width, height, cameramaker, cameramodel try: tags = EXIF.process_file(file) if not tags: print "ERROR: No EXIF tags on", path return date, width, height, cameramaker, cameramodel except: print "ERROR: proccesing EXIF tags on", path return date, width, height, cameramaker, cameramodel # tags['EXIF DateTimeOriginal'] = "2001:03:31 12:27:36" if tags.has_key('EXIF DateTimeOriginal'): data = str(tags['EXIF DateTimeOriginal']) try: date = time.strptime(data, "%Y:%m:%d %H:%M:%S") except: date = None if tags.has_key('EXIF ExifImageWidth'): width = str(tags['EXIF ExifImageWidth']) if tags.has_key('EXIF ExifImageLength'): height = str(tags['EXIF ExifImageLength']) if tags.has_key('Image Make'): cameramaker = str(tags['Image Make']) if tags.has_key('Image Model'): cameramodel = str(tags['Image Model']) return date, width, height, cameramaker, cameramodel
def findexif(self, image): try: f = open(image, 'rb') except Exception as e: print(e) return False tags = EXIF.process_file(f) clef = list(tags.keys()) if not clef: return False clef.sort() text = "" self.Freeze() #self.DeleteAllItems() self.DeleteChildren(self.root) item = -1 i = 1 old = "root" parent = self.root for name in clef: if name in ('JPEGThumbnail', 'TIFFThumbnail'): continue path = tags[name] n1, n2 = name.split(" ", 1) if n1 != old: old = n1 parent = self.AppendItem(self.root, common.wxstr(n1)) ## item = self.InsertStringItem(item+1, common.wxstr(name)) ## self.SetStringItem(item, 1, common.wxstr(path)) item = self.AppendItem(parent, common.wxstr(n2)) self.SetItemText(item, common.wxstr(path), 1) i += 1 #self.SetColumnWidth(0, -1) ## self._doResize() self.Thaw() c, cookie = self.GetFirstChild(self.root) self.Expand(c) while True: c, cookie = self.GetNextChild(self.root, cookie) if not c.IsOk(): break self.Expand(c) self.adjust_size() return True
def addPictures(self): """ Add already taken pictures to recording. If no recording is ongoing, ask user what data directory he wants to put the photos into. """ if self.recording == 1: dir = self.dataDirectory else: dir = self.controller.getLastDataSubdirectory( self.controller.output_directory) dir = str( QFileDialog.getExistingDirectory( self, self.tr("Choose recording session directory"), dir, QFileDialog.ShowDirsOnly)) if dir == "": return #append self.name, if required s = dir.rstrip('/').split('/') if len(s) and s[-1] != self.name: dir += self.name + "/" if dir[-1] != '/': dir += "/" if not os.path.exists(dir): os.makedirs(dir) files = [ str(s) for s in QFileDialog.getOpenFileNames( self, self.tr("Choose images to be added to the photo directory"), os.path.expanduser("~"), self.tr("Photos (*.jpg *.jpeg)")) ] for f in files: fh = open(f, "rb") exif = EXIF.process_file(fh) fh.close() newfn = dir + str(exif["Image DateTime"]).replace( ":", "-").replace(" ", "_") + f[f.rfind("."):] shutil.copy2(f, newfn)
def getEXIFDate(filename): if haveEXIF: try: f = open(filename, 'rb') tags = EXIF.process_file(f, details=False, stop_tag='EXIF DateTimeOriginal') f.close() if 'EXIF DateTimeOriginal' in tags: tag = str(tags['EXIF DateTimeOriginal']) return datetime.date(int(tag[0:4]), int(tag[5:7]), int(tag[8:10])) except IOError: pass except ValueError: pass return None
def main(*args): global image_dir conn = DBAPI.connect(host='1.2.3.4', port=12345, database='wikiloves', user='******', password='******') cursor = conn.cursor() i = 0 for row in db_gen(cursor): i = i + 1 img = image_dir + row['id'] + '.jpg' f = open(img, 'rb') try: exif = EXIF.process_file(f) for key in exif.keys(): if 'exif datetime' in key.lower(): try: row['date'] = datetime.strptime( str(exif[key]), '%Y:%m:%d %H:%M:%S').date() break except ValueError: pass except Exception: print 'exif processing for %s skipped because of errors' % img f.close() try: if process(img, row): # cursor.execute('UPDATE inda SET status = 2 WHERE id = %s', (row['id'],)) # conn.commit() pass except upload.UploadException as e: # dupe - needs patched upload.py if e.type != 'duplicate': raise pywikibot.output('%s is duplicate of %s' % (row['id'], e.param)) # cursor.execute('UPDATE inda SET status = -2 WHERE id = %s', (row['id'],)) # conn.commit() except Exception as e: raise # if i >= 3: # break conn.commit() conn.close()
def get_thumb(self, filepath): if not have_pil: raise Exception("Install PIL to use this method") if not have_exif: raise Exception("Install EXIF to use this method") with open(filepath, 'rb') as in_f: try: d = EXIF.process_file(in_f) except Exception as e: return None if 'JPEGThumbnail' in d: buf = d['JPEGThumbnail'] # TODO: other possible encodings? else: return None image = PILimage.open(BytesIO.BytesIO(buf)) data_np = numpy.array(image) return data_np
def get_image_metadata(path): """ Returns Image Data Using PIL """ file_extension = path.split('.')[-1].lower() metadata_dictionary = {} if file_extension in IMAGE_FILE_EXTENSIONS and PIL_AVAILABLE: im = Image.open(path) for key, value in im.info.items(): metadata_dictionary[key] = value del (im) if EXIF_AVAILABLE: try: f = open(path, 'rb') EXIF_dictionary = EXIF.process_file(f) for key, value in EXIF_dictionary.items(): metadata_dictionary[key.replace(' ', '_')] = value except: pass return metadata_dictionary else: return None