def read_exif(path): """Return the EXIF metadata from the file at path.""" file = open(path, 'rb') data = exif.process_file(file) return data
def test_broken_exif(self): # This test fails even with the 2005.05.12 exif version from # http://home.cfl.rr.com/genecash/ f = StringIO(TEST_EXIF_ERROR) exif_data = exif.process_file(f, debug=False) # probably want to add some tests on returned data. Currently gives # ValueError in process_file. Actually, no it does not. self.assertEqual(exif_data.get('EXIF ColorSpace'), '1')
def uploadImage( self, image ): folderTag = image[len(IMAGE_DIR):] #print folderTag #return if ( not self.uploaded.has_key( folderTag ) ): try: logging.debug( "Getting EXIF for %s" % image) f = open(image, 'rb') exiftags = exif.process_file(f) f.close() #print exiftags[XPKEYWORDS] #print folderTag #make one tag equal to original file path with spaces replaced by # and start it with # (for easier recognition) since space is used as TAG separator by flickr # this is needed for later syncing flickr with folders realTags = folderTag.replace('\\',' ') # look for / or \ or _ or . and replace them with SPACE to make real Tags realTags = realTags.replace('/',' ') # these will be the real tags ripped from folders realTags = realTags.replace('_',' ') realTags = realTags.replace('.',' ') picTags = '#' + folderTag.replace(' ','#') + ' ' + realTags if exiftags == {}: logging.debug( 'NO_EXIF_HEADER for %s' % image) else: if XPKEYWORDS in exiftags: #look for additional tags in EXIF to tag picture with if len(exiftags[XPKEYWORDS].printable) > 4: picTags += exif.make_string( eval(exiftags[XPKEYWORDS].printable)).replace(';',' ') #print picTags logging.debug( "Uploading image %s" % image) photo = ('photo', image, open(image,'rb').read()) d = { api.token : str(self.token), api.perms : str(self.perms), "tags" : str(picTags), "is_public" : str( FLICKR["is_public"] ), "is_friend" : str( FLICKR["is_friend"] ), "is_family" : str( FLICKR["is_family"] ) } sig = self.signCall( d ) d[ api.sig ] = sig d[ api.key ] = FLICKR[ api.key ] url = self.build_request(api.upload, d, (photo,)) xml = urllib2.urlopen( url ).read() res = xmltramp.parse(xml) if ( self.isGood( res ) ): logging.debug( "successful.") self.logUpload( res.photoid, folderTag ) else : print "problem.." self.reportError( res ) except: logging.error(sys.exc_info())
def extract_exif_from_jpg(path, tags=EXIF_TAGS_SHOWN): try: #open image in binary reading mode with open(path, 'rb') as image: tags_all = exif.process_file(image) tags_shown = {tag.split(" ")[-1:][0]: str(tags_all[tag]) for tag in tags} return tags_shown except IOError: return {}
def exif_data(self, filen): paint_screen(gl.BLACK) close_button(self.screen) if not self.show_exif: gl.SHOW_EXIFBUTTON = 0 return exif_info = [] filename = gl.files[filen] try: file = open(filename, "rb") except: exif_info.append("%s unreadable" % filename) gl.SHOW_EXIFBUTTON = 0 return data = exif.process_file(file) if not data: font_size = 13 font = pygame.font.Font(gl.FONT_NAME, font_size) no_exif_msg = "No Exif information found" show_message( no_exif_msg, ((self.screen.get_width() / 2) - (font.size(no_exif_msg)[0] / 2), self.screen.get_height() / 2), font_size, ("bold", "transparent"), ) gl.SHOW_EXIFBUTTON = 0 return x = data.keys() x.sort() for i in x: if i in ("JPEGThumbnail", "TIFFThumbnail"): continue try: exif_info.append("%s: %s" % (i, data[i].printable)) except: exif_info.append("error", i, '"', data[i], '"') gl.SHOW_EXIFBUTTON = 0 pos = 25 show_message("Exif Information", "top", 13, ("underline", "bold", "transparent")) try: for line in exif_info: if type(line) is StringType and len(line) <= 250: # parachutes on long lines without this exif_font = pygame.font.Font(gl.FONT_NAME, 9) ren = exif_font.render(line, 1, gl.MENU_COLOR) ren_rect = ren.get_rect() ren_rect[0] = 14 ren_rect[1] = pos self.screen.blit(ren, ren_rect) pos = pos + 9 except: print "Couldn't exif" # pass flip()
def extract_exif_from_jpg(path, tags=EXIF_TAGS_SHOWN): try: #open image in binary reading mode with open(path, 'rb') as image: tags_all = exif.process_file(image) tags_shown = { tag.split(" ")[-1:][0]: str(tags_all[tag]) for tag in tags } return tags_shown except IOError: return {}
def EXIF_tags(fn): # FIXME: strip some keys for speed-up instead of # returning the whole list of tags # see EXIF notes # if tag not in ('JPEGThumbnail', 'TIFFThumbnail', 'Filename', # 'EXIF MakerNote'): # after some timing test there's no speedup ... kept for reference # it may be faster to hook a new method in EXIF to just lookup some values # # We should do a better timing with the timeit module (in EXIFTest.py # logger.info('calling exif api function') f = open(fn, 'rb') tags = process_file(f) for t in ['JPEGThumbnail', 'TIFFThumbnail', 'Filename', 'EXIF MakerNote']: if t in tags: del tags[t] f.close() return tags
def picture_taken(self, filen): filename = gl.files[filen] try: file = open(filename, "rb") except: return data = exif.process_file(file) if not data: return x = data.keys() x.sort() for i in x: if i in ("JPEGThumbnail", "TIFFThumbnail"): continue try: if i == "EXIF DateTimeOriginal": date_str = strftime("%a %b %d %H:%M:%S %Y", strptime(data[i].printable, "%Y:%m:%d %H:%M:%S")) self.print_info("Created with digital camera: %s" % convert_times(date_str, 1), 28) except: self.print_info("Created with digital camera: %s" % data[i].printable, 28)
def get_original_datetime_N80(filename): """ Extracted the date time when the picture is taken. Keyword arguments: filename -- The full file name toward the image file to be processed. Returns: status -- True if everything is fine; othewise, False detail -- Datetime information from exif tag if status is true; otherwise, the detail of exception. """ try: with open(filename, "r") as f: exif_data = exif.process_file(f, stop_tag="DateTimeOriginal") # stop after finding this tag str_original_datetime = exif_data.get("EXIF DateTimeOriginal").values # N80 okay except: return (False, str(sys.exc_info())) # Example in N80, 2010:08:24 17:02:58 return (True, datetime.strptime(str_original_datetime, "%Y:%m:%d %H:%M:%S"))
def getEXIF(self, img=None, refresh=False): """Get the exif informations of the file The information is cached in _v_image_exif """ cache = '_image_exif' if refresh: setattr(self, cache, None) exif_data = getattr(self, cache, None) if exif_data is None or not isinstance(exif_data, dict): io = self.getImageAsFile(img, scale=None) if io is not None: # some cameras are naughty :( try: io.seek(0) exif_data = exif.process_file(io, debug=False) except: LOG.error('Failed to process EXIF information', exc_info=True) exif_data = {} # seek to 0 and do NOT close because we might work # on a file upload which is required later io.seek(0) # remove some unwanted elements lik thumb nails for key in ('JPEGThumbnail', 'TIFFThumbnail', 'MakerNote JPEGThumbnail'): if key in exif_data: del exif_data[key] if not exif_data: # alawys return a dict exif_data = {} # set the EXIF cache even if the image has returned an empty # dict. This prevents regenerating the exif every time if an # image doesn't have exif information. setattr(self, cache, exif_data) return exif_data
def get_nikon_exif(path_name): f = open(path_name, 'rb') tags = exif.process_file(f) f.close() return tags
def uploadImage( self, image ): folderTag = image[len(IMAGE_DIR):] if self.uploaded.has_key(folderTag): return None try: logging.debug( "Getting EXIF for %s" % image) f = open(image, 'rb') exiftags = exif.process_file(f) f.close() #print exiftags[XPKEYWORDS] #print folderTag # make one tag equal to original file path with spaces replaced by # # and start it with # (for easier recognition) since space is # used as TAG separator by flickr # this is needed for later syncing flickr with folders realTags = os.path.dirname(folderTag).replace('\\',' ') # look for / or \ or _ or . and replace them with SPACE to make real Tags realTags = realTags.replace('/',' ') # these will be the real tags ripped from folders realTags = realTags.replace('_',' ') realTags = realTags.replace('.',' ') realTags = realTags.strip() if configdict.get('full_folder_tags', 'false').startswith('true'): realTags = os.path.dirname(folderTag).split(os.sep) realTags = (' '.join('"' + item + '"' for item in realTags)) picTags = '#' + folderTag.replace(' ','#') + ' ' + realTags if exiftags == {}: logging.debug( 'NO_EXIF_HEADER for %s' % image) else: if XPKEYWORDS in exiftags: #look for additional tags in EXIF to tag picture with if len(exiftags[XPKEYWORDS].printable) > 4: picTags += exif.make_string( eval(exiftags[XPKEYWORDS].printable)).replace(';',' ') picTags = picTags.strip() msg = "Uploading image %s with tags %s" % (image, picTags) timestamp = time.strftime('[%F %H:%M:%S]', time.localtime()) logging.debug(msg) print timestamp, msg photo = ('photo', image, open(image,'rb').read()) d = { api.token : str(self.token), api.perms : str(self.perms), "tags" : str(picTags), "hidden" : str( FLICKR["hidden"] ), "is_public" : str( FLICKR["is_public"] ), "is_friend" : str( FLICKR["is_friend"] ), "is_family" : str( FLICKR["is_family"] ) } sig = self.signCall( d ) d[ api.sig ] = sig d[ api.key ] = FLICKR[ api.key ] url = self.build_request(api.upload, d, (photo,)) xml = urllib2.urlopen( url ).read() res = xmltramp.parse(xml) if ( self.isGood( res ) ): logging.debug( "successful.") self.logUpload( res.photoid, folderTag ) return res.photoid else : print "problem.." self.reportError( res ) except KeyboardInterrupt, ex: logging.debug("Keyboard interrupt seen, abandon uploads") print "Stopping uploads..." self.abandonUploads = True return None
def test_broken_exif(self): # This test fails even with the 2005.05.12 exif version from # http://home.cfl.rr.com/genecash/ f = StringIO(TEST_EXIF_ERROR) exif_data = exif.process_file(f, debug=False)
def sortPhotos(src_dir, dest_dir, extensions, sort_type, move_files, removeDuplicates): # some error checking if not os.path.exists(src_dir): raise Exception('Source directory does not exist') if not os.path.exists(dest_dir): raise Exception('Destination directory does not exist') # find files that have the specified extensions matched_files = [] # check if file system is case sensitive case_sensitive_os = True if os.path.normcase('A') == os.path.normcase('a'): case_sensitive_os = False # recurvsively search directory for root, dirnames, filenames in os.walk(src_dir): # search for all files that match the extension for ext in extensions: # grab both upper and lower case matches if necessary matches = fnmatch.filter(filenames, '*.' + ext.lower()) if case_sensitive_os: matches += fnmatch.filter(filenames, '*.' + ext.upper()) # add file root and save the matched file in list for match in matches: matched_files.append(os.path.join(root, match)) # setup a progress bar num_files = len(matched_files) idx = 0 for src_file in matched_files: # update progress bar numdots = int(20.0 * (idx + 1) / num_files) sys.stdout.write('\r') sys.stdout.write('[%-20s] %d of %d ' % ('=' * numdots, idx + 1, num_files)) sys.stdout.flush() idx += 1 # open file f = open(src_file, 'rb') # get extension for types that may have EXIF data root, ext = os.path.splitext(src_file) if ext.lower() in ['.jpg', '.tiff']: tags = exif.process_file(f, details=False) # look for date in EXIF data if 'EXIF DateTimeDigitized' in tags: year, month, day = parse_date_exif( tags['EXIF DateTimeDigitized']) elif 'EXIF DateTimeOriginald' in tags: year, month, day = parse_date_exif( tags['EXIF DateTimeOriginal']) elif 'Image DateTimed' in tags: year, month, day = parse_date_exif(tags['Image DateTime']) else: # use file time stamp year, month, day = parse_date_tstamp(src_file) # if no EXIF data use file timestamp else: year, month, day = parse_date_tstamp(src_file) # create year directory if necessary dest_file = os.path.join(dest_dir, year) if not os.path.exists(dest_file): os.makedirs(dest_file) # create month directory if necessary if sort_type in [SortType.YearMonth, SortType.YearMonthDay]: dest_file = os.path.join(dest_file, month) if not os.path.exists(dest_file): os.makedirs(dest_file) # create day directory if necessary if sort_type == SortType.YearMonthDay: dest_file = os.path.join(dest_file, day) if not os.path.exists(dest_file): os.makedirs(dest_file) # setup destination file dest_file = os.path.join(dest_file, os.path.basename(src_file)) root, ext = os.path.splitext(dest_file) # check for collisions append = 1 fileIsIdentical = False while True: if os.path.isfile(dest_file): # check for existing name if removeDuplicates and filecmp.cmp( src_file, dest_file): # check for identical files fileIsIdentical = True break else: # name is same, but file is different dest_file = root + '_' + str(append) + ext append += 1 else: break # finally move or copy the file if move_files: os.rename(src_file, dest_file) else: if fileIsIdentical: continue # if file is same, we just ignore it (for copy option) else: shutil.copy2(src_file, dest_file) print
if len(sys.argv) == 2: filename=sys.argv[1] file=open(filename, "r"); else: filename=sys.argv[2] mod=sys.argv[1] fd = os.open(filename, os.O_RDWR) file=os.fdopen(fd,'r') # check file exists and is readable file.read(1) file.seek(0,0) except: print 'Cannot open', filename sys.exit(1) tags=exif.process_file(file,0,1) if not tags: print 'no EXIF information in', filename sys.exit(1) if not tags.has_key('Exif Offset') \ or not tags.has_key('Image Orientation'): print 'cannot get orientation info in', filename sys.exit(1) exifp = tags['Exif Offset'] endian = tags['Exif Endian'] tagp = tags['Image Orientation'].field_offset orientp = exifp + tagp if endian == 'M': # MM byte order
def uploadImage(self, image): folderTag = image[len(IMAGE_DIR):] if (not self.upl.has_key(folderTag)): try: logging.debug("UploadThread %d Getting EXIF for %s" % (self.threadID, image)) f = open(image, 'rb') exiftags = exif.process_file(f) f.close() #print exiftags[XPKEYWORDS] #print folderTag #make one tag equal to original file path with spaces replaced by # and start it with # (for easier recognition) since space is used as TAG separator by flickr # this is needed for later syncing flickr with folders realTags = folderTag.replace( '\\', ' ' ) # look for / or \ or _ or . and replace them with SPACE to make real Tags realTags = realTags.replace( '/', ' ') # these will be the real tags ripped from folders realTags = realTags.replace('_', ' ') realTags = realTags.replace('.', ' ') picTags = '#' + folderTag.replace(' ', '#') + ' ' + realTags if exiftags == {}: logging.debug('UploadThread %d NO_EXIF_HEADER for %s' % (self.threadID, image)) else: if XPKEYWORDS in exiftags: #look for additional tags in EXIF to tag picture with if len(exiftags[XPKEYWORDS].printable) > 4: picTags += exif.make_string( eval(exiftags[XPKEYWORDS].printable)).replace( ';', ' ') #print picTags logging.debug("UploadThread %d Uploading image %s" % (self.threadID, image)) photo = ('photo', image, open(image, 'rb').read()) d = { api.token: str(self.upl.token), api.perms: str(self.upl.perms), "tags": str(picTags), "is_public": str(FLICKR["is_public"]), "is_friend": str(FLICKR["is_friend"]), "is_family": str(FLICKR["is_family"]) } sig = self.upl.signCall(d) d[api.sig] = sig d[api.key] = FLICKR[api.key] url = self.upl.build_request(api.upload, d, (photo, )) xml = urllib2.urlopen(url).read() res = xmltramp.parse(xml) if (self.upl.isGood(res)): logging.debug("successful.") self.upl.logUpload(res.photoid, folderTag) else: print "problem.." self.upl.reportError(res) except: logging.error(sys.exc_info())
def exif_data(screen, filename): exif_data1 = [] exif_data2 = [] font_size = 9 font = pygame.font.Font(gl.FONT_NAME, font_size) try: file = open(filename, "rb") except: return data = exif.process_file(file) if not data: return x = data.keys() x.sort() for i in x: if i in ("JPEGThumbnail", "TIFFThumbnail"): continue try: if i == "EXIF DateTimeOriginal": # convert date/time to same format used on status bar splitdate, splittime = data[i].printable.split() spl = data[i].printable.split()[0].split(":") exif_data1.append("/".join(spl[1:] + [spl[0]]) + " / " + splittime) if i == "EXIF FocalLength": mm = data[i].printable.split("/") mm = float(mm[0]) / float(mm[1]) exif_data1.append("Focal Length: %smm" % mm) if i == "EXIF ExposureTime": # shutter speed exif_data1.append("Shutter Speed: " + data[i].printable + "sec") if i == "EXIF FNumber": aperture = data[i].printable.split("/") aperture = float(aperture[0]) / float(aperture[1]) exif_data1.append("Aperture: %s" % aperture) if i == "EXIF ExposureProgram": exif_data2.append("Exposure Mode: %s" % data[i].printable) if i == "EXIF ExposureBiasValue": exif_data2.append("Exposure Bias: %s" % data[i].printable) if i == "EXIF ISOSpeedRatings": exif_data1.append("ISO: %s" % data[i].printable) if i == "EXIF LightSource": exif_data1.append("White Balance: %s" % data[i].printable) if i == "EXIF Flash": exif_data1.append("Flash: %s" % data[i].printable) if i == "EXIF MeteringMode": if data[i].printable == "5": exif_data2.append("Metering Mode: Multi-segment") else: exif_data2.append("Metering Mode: %s" % data[i].printable) if i == "Image Make": exif_data2.append("Make: %s" % data[i].printable) if i == "Image Model": exif_data2.append("Model: %s" % data[i].printable) except: pass try: divider = ", " exif_data1 = [x + divider for x in exif_data1[:-1]] + [exif_data1[-1]] # add a divider exif_data2 = [x + divider for x in exif_data2[:-1]] + [exif_data2[-1]] exif_data1_msg = " " + " ".join(exif_data1) + " " exif_data2_msg = " " + " ".join(exif_data2) + " " # round the shutter speed: if exif_data1_msg.find("Shutter") != -1: shutspd_text = exif_data1_msg.split(divider)[1].split()[-1] shutspd_vals = shutspd_text.split("/") shutspd_vals = shutspd_vals[0][0] + "/" + shutspd_vals[1][:2].replace("s", "").replace("sec", "") if shutspd_vals == "3/10": shutspd_vals = "1/3" # some kodak's exif_data1_msg = exif_data1_msg.replace(shutspd_text, shutspd_vals + " sec") # round the apeture value: if exif_data1_msg.find("Aperture") != -1: aperture_text = exif_data1_msg.split(divider)[2].split()[-1] exif_data1_msg = exif_data1_msg.replace(aperture_text, "f/" + str(round(float(aperture_text), 1))) # round the focal length: if exif_data1_msg.find("Focal") != -1: focal_text = exif_data1_msg.split(divider)[4].split()[-1] exif_data1_msg = exif_data1_msg.replace(focal_text, str(round(float(focal_text.replace("mm", "")), 1))) show_message(exif_data1_msg, (1, 0), 9) if font.size(exif_data2_msg)[0] > screen.get_width(): exif_data2_wrap = " " + exif_data2.pop() exif_data2_msg = " " + " ".join(exif_data2)[:-3] show_message(exif_data2_wrap, (1, 20), font_size) show_message(exif_data2_msg, (1, 10), font_size) except: pass
if len(sys.argv) == 2: filename = sys.argv[1] file = open(filename, "r") else: filename = sys.argv[2] mod = sys.argv[1] fd = os.open(filename, os.O_RDWR) file = os.fdopen(fd, 'r') # check file exists and is readable file.read(1) file.seek(0, 0) except: print 'Cannot open', filename sys.exit(1) tags = exif.process_file(file, 0, 1) if not tags: print 'no EXIF information in', filename sys.exit(1) if not tags.has_key('Exif Offset') \ or not tags.has_key('Image Orientation'): print 'cannot get orientation info in', filename sys.exit(1) exifp = tags['Exif Offset'] endian = tags['Exif Endian'] tagp = tags['Image Orientation'].field_offset orientp = exifp + tagp if endian == 'M': # MM byte order
def sortPhotos(src_dir, dest_dir, extensions, sort_type, move_files, removeDuplicates): # some error checking if not os.path.exists(src_dir): raise Exception('Source directory does not exist') if not os.path.exists(dest_dir): raise Exception('Destination directory does not exist') # find files that have the specified extensions matched_files = [] # check if file system is case sensitive case_sensitive_os = True if os.path.normcase('A') == os.path.normcase('a'): case_sensitive_os = False # recurvsively search directory for root, dirnames, filenames in os.walk(src_dir): # search for all files that match the extension for ext in extensions: # grab both upper and lower case matches if necessary matches = fnmatch.filter(filenames, '*.' + ext.lower()) if case_sensitive_os: matches += fnmatch.filter(filenames, '*.' + ext.upper()) # add file root and save the matched file in list for match in matches: matched_files.append(os.path.join(root, match)) # setup a progress bar num_files = len(matched_files) idx = 0 for src_file in matched_files: # update progress bar numdots = int(20.0*(idx+1)/num_files) sys.stdout.write('\r') sys.stdout.write('[%-20s] %d of %d ' % ('='*numdots, idx+1, num_files)) sys.stdout.flush() idx += 1 # open file f = open(src_file, 'rb') # get extension for types that may have EXIF data root, ext = os.path.splitext(src_file) if ext.lower() in ['.jpg', '.jpeg', '.tiff']: tags = exif.process_file(f, details=False) # look for date in EXIF data if 'EXIF DateTimeDigitized' in tags and valid_date(tags['EXIF DateTimeDigitized']): year, month, day = parse_date_exif(tags['EXIF DateTimeDigitized']) elif 'EXIF DateTimeOriginal' in tags and valid_date(tags['EXIF DateTimeOriginal']): year, month, day = parse_date_exif(tags['EXIF DateTimeOriginal']) elif 'Image DateTime' in tags and valid_date(tags['Image DateTime']): year, month, day = parse_date_exif(tags['Image DateTime']) else: # use file time stamp year, month, day = parse_date_tstamp(src_file) # if no EXIF data use file timestamp else: year, month, day = parse_date_tstamp(src_file) # create year directory if necessary dest_file = os.path.join(dest_dir, year) if not os.path.exists(dest_file): os.makedirs(dest_file) # create month directory if necessary if sort_type in [SortType.YearMonth, SortType.YearMonthDay]: dest_file = os.path.join(dest_file, month) if not os.path.exists(dest_file): os.makedirs(dest_file) # create day directory if necessary if sort_type == SortType.YearMonthDay: dest_file = os.path.join(dest_file, day) if not os.path.exists(dest_file): os.makedirs(dest_file) # setup destination file dest_file = os.path.join(dest_file, os.path.basename(src_file)) root, ext = os.path.splitext(dest_file) # check for collisions append = 1 fileIsIdentical = False while True: if os.path.isfile(dest_file): # check for existing name if removeDuplicates and filecmp.cmp(src_file, dest_file): # check for identical files fileIsIdentical = True break else: # name is same, but file is different dest_file = root + '_' + str(append) + ext append += 1 else: break # finally move or copy the file if move_files: os.rename(src_file, dest_file) else: if fileIsIdentical: continue # if file is same, we just ignore it (for copy option) else: shutil.copy2(src_file, dest_file) print
def get_tags(self, file_location): "Devuelve todos los tags para UN archivo." pic = open(file_location) tags=exif.process_file(pic, details=False, stop_tag='EXIF DateTimeOriginal', strict=True) pic.close() return tags
def exifInfo(self, fileName): os.chdir(self.dirName) if not(self.exifFlag): return "" import exif file = open(fileName,"rb") data = exif.process_file(file) if not data: return "No EXIF Information available." x = data.keys() x.sort() count = 0 vals = [0,4,9,11,12,15,17,18,22,25,38,39,41,43,45] """ 0 - ApertureValue 4 - DateTimeDigitized 9 - ExposureBiasValue 11 - ExposureProgram 12 - ExposureTime 15 - Flash 17 - FocalLength 18 - ISOSpeedRatings 22 - MeteringMode 25 - ShutterSpeedValue 38 - Image Make 39 - Image Model 41 - Image ResolutionUnit 43 - Image XResolution 45 - Image YResolution """ retVal = [] for i in x: if count in vals: #print 'error', i, '"', data[i], '"' retVal.append(data[i]) count = count + 1 retValStr = [] for i in retVal: retValStr.append(i.__str__()) date = retValStr[1] date = date.split(" ") time = date[1] date = date[0] year = date.split(":")[0] month = int(date.split(":")[1]) day = date.split(":")[2] hr = int(time.split(":")[0]) min = time.split(":")[1] am_pm = "AM" if hr >= 12: am_pm = "PM" if hr > 12: hr = hr - 12 hr = str(hr) monthArr = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"] date = monthArr[month - 1] + " " + day + ", " + year time = hr + ":" + min + " " + am_pm out = """<table align="center" cellpadding="8" cellspacing="0" border="1" style="border: 1; text-align: center; margin-top: 20px;"> <tr> <td colspan="4" align="center" style="text-align: center;"> <strong>Photographed on %s at %s</strong> </td> </tr> <tr> <td><strong>Aperture</strong></td> <td>%s</td> <td><strong>Exposure bias</strong></td> <td>%s</td> </tr> <tr> <td><strong>Exposure program</strong></td> <td>%s</td> <td><strong>Exposure time</strong></td> <td>%s</td> </tr> <tr> <td><strong>Flash</strong></td> <td>%s</td> <td><strong>Focal length</strong></td> <td>%s</td> </tr> <tr> <td><strong>ISO speed ratings</strong></td> <td>%s</td> <td><strong>Light source</strong></td> <td>-</td> </tr> <tr> <td><strong>Make</strong></td> <td>%s</td> <td><strong>Metering mode</strong></td> <td>%s</td> </tr> <tr> <td><strong>Model</strong></td> <td>%s</td> <td><strong>Resolution unit</strong></td> <td>%s</td> </tr> <tr> <td><strong>Shot resolution</strong></td> <td>-</td> <td><strong>Shutter speed</strong></td> <td>%s</td> </tr> <tr> <td><strong>X resolution</strong></td> <td>%s</td> <td><strong>Y resolution</strong></td> <td>%s</td> </tr> </table>""" % (date, time, retValStr[0], retValStr[2], retValStr[3], retValStr[4], retValStr[5], retValStr[6], retValStr[7], retValStr[10], retValStr[8], retValStr[11], retValStr[12], retValStr[9], retValStr[13], retValStr[14]) return out
def exifInfo(self, fileName): os.chdir(self.dirName) if not (self.exifFlag): return "" import exif file = open(fileName, "rb") data = exif.process_file(file) if not data: return "No EXIF Information available." x = data.keys() x.sort() count = 0 vals = [0, 4, 9, 11, 12, 15, 17, 18, 22, 25, 38, 39, 41, 43, 45] """ 0 - ApertureValue 4 - DateTimeDigitized 9 - ExposureBiasValue 11 - ExposureProgram 12 - ExposureTime 15 - Flash 17 - FocalLength 18 - ISOSpeedRatings 22 - MeteringMode 25 - ShutterSpeedValue 38 - Image Make 39 - Image Model 41 - Image ResolutionUnit 43 - Image XResolution 45 - Image YResolution """ retVal = [] for i in x: if count in vals: #print 'error', i, '"', data[i], '"' retVal.append(data[i]) count = count + 1 retValStr = [] for i in retVal: retValStr.append(i.__str__()) date = retValStr[1] date = date.split(" ") time = date[1] date = date[0] year = date.split(":")[0] month = int(date.split(":")[1]) day = date.split(":")[2] hr = int(time.split(":")[0]) min = time.split(":")[1] am_pm = "AM" if hr >= 12: am_pm = "PM" if hr > 12: hr = hr - 12 hr = str(hr) monthArr = [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ] date = monthArr[month - 1] + " " + day + ", " + year time = hr + ":" + min + " " + am_pm out = """<table align="center" cellpadding="8" cellspacing="0" border="1" style="border: 1; text-align: center; margin-top: 20px;"> <tr> <td colspan="4" align="center" style="text-align: center;"> <strong>Photographed on %s at %s</strong> </td> </tr> <tr> <td><strong>Aperture</strong></td> <td>%s</td> <td><strong>Exposure bias</strong></td> <td>%s</td> </tr> <tr> <td><strong>Exposure program</strong></td> <td>%s</td> <td><strong>Exposure time</strong></td> <td>%s</td> </tr> <tr> <td><strong>Flash</strong></td> <td>%s</td> <td><strong>Focal length</strong></td> <td>%s</td> </tr> <tr> <td><strong>ISO speed ratings</strong></td> <td>%s</td> <td><strong>Light source</strong></td> <td>-</td> </tr> <tr> <td><strong>Make</strong></td> <td>%s</td> <td><strong>Metering mode</strong></td> <td>%s</td> </tr> <tr> <td><strong>Model</strong></td> <td>%s</td> <td><strong>Resolution unit</strong></td> <td>%s</td> </tr> <tr> <td><strong>Shot resolution</strong></td> <td>-</td> <td><strong>Shutter speed</strong></td> <td>%s</td> </tr> <tr> <td><strong>X resolution</strong></td> <td>%s</td> <td><strong>Y resolution</strong></td> <td>%s</td> </tr> </table>""" % (date, time, retValStr[0], retValStr[2], retValStr[3], retValStr[4], retValStr[5], retValStr[6], retValStr[7], retValStr[10], retValStr[8], retValStr[11], retValStr[12], retValStr[9], retValStr[13], retValStr[14]) return out