def main(argv): if len(argv) != 2: print('Usage: {} <directory containing photos_and_videos>'.format( argv[0])) basedir = argv[1] edited = 0 unedited = 0 for partial_image_path, timestamp in get_files_and_timestamps( os.path.join(basedir, 'photos_and_videos', 'photos_synced_from_your_device.json')): image_path = os.path.join(basedir, partial_image_path) exif_editor = pyexif.ExifEditor(image_path) if exif_editor._getDateTimeField("DateTimeOriginal") is None: try: exif_editor.setOriginalDateTime(timestamp) except: print("Oops!", sys.exc_info()[0], "occured for photo: ", partial_image_path) unedited += 1 edited += 1 else: # This should use .getOriginalDateTime(), but the bug fix at # https://github.com/EdLeafe/pyexif/commit/600510a9266f30b63181e54cd10dc4e9879c0e73 has not been pushed to pip # yet. existing_timestamp = exif_editor._getDateTimeField( "DateTimeOriginal") diff = abs(existing_timestamp - timestamp) if diff > datetime.timedelta(minutes=1): print(( 'WARNING: {} has a timestamp already ({}), but the timestamp in moments.json ({}) is different ' + 'by {}. If the photo was taken in a different time zone, this is expected.' ).format(image_path, existing_timestamp, timestamp, diff)) unedited += 1 print( '{} done. Added timestamps to {} files, left {} untouched.'.format( partial_image_path, edited, unedited))
def build_gallery(): ''' This does all the name detection and directory transversal to build a dict of the gallery contents which is then used to actually write the templates ''' print "Building gallery" os.chdir('content/assests/gallery/images/') albums = {} for root, subFolders, files in os.walk('.'): for folder in subFolders: # Figure out our relative dirs album_dir = os.path.join(root, folder)[2:] parent_album_dir = '/'.join(album_dir.split('/')[:-1]) # Add the parent album dir to the albums if it doesn't exist if parent_album_dir not in albums: albums[parent_album_dir] = { "sub_albums": [], "images": {}, "name": "Home", "parent_albums": [], "path": "", "parent_path": "", } # Add the album to the parent album's entry # only do this if they are different if album_dir != parent_album_dir: # Just in case...f if album_dir not in albums[parent_album_dir]["sub_albums"]: albums[parent_album_dir]["sub_albums"].append(album_dir) # Add the album to the albums if it doesn't exist if album_dir not in albums: albums[album_dir] = {"sub_albums": [], "images": {}} # Check if we need to figure out the name if "name" not in albums[album_dir]: # Check if there is an explicit name file album_name_file = os.path.realpath( os.path.join(album_dir, 'ALBUM_DESCRIPTION')) if os.path.isfile(album_name_file): fh = open(album_name_file, 'r') album_name = fh.read() fh.close() else: # Use magical guess work album_name = album_dir.split('/')[-1].replace('_', ' ') albums[album_dir]["name"] = album_name.strip() if "parent_path" not in albums[album_dir]: albums[album_dir]["parent_path"] = parent_album_dir if "parent_albums" not in albums[album_dir]: albums[album_dir]["parent_albums"] = [] parts = parent_album_dir.split('/') i = len(parts) while i > 0: p = '/'.join(parts[:-i]).strip() print p if p != "": albums[album_dir]["parent_albums"].append(p) i -= 1 if parent_album_dir != "": albums[album_dir]["parent_albums"].append(parent_album_dir) # Add all the image files to the gallery for f in files: # Get the real path + ext - this is used for generating the thumbs album_dir = root[2:] image_path = os.path.join(album_dir, f) basename, extension = os.path.splitext(image_path) # Figure out if we can support the format if extension.lower() in [".png", ".jpeg", ".jpg"]: # We fill this stuff in image_description = f image_author = 'Unknown' # Check if we even need to bother getting this image info if image_path not in albums[album_dir]["images"]: # Try and get the description file desc_path = os.path.realpath( os.path.join(image_path, '-DESCRIPTION')) if os.path.isfile(desc_path): fh = open(desc_path, 'r') image_description = fh.read() fh.close() else: # Try and get the EXIF comment try: image = pyexif.ExifEditor(real_path) image_description = image.getTag('Comment') except: pass # Try and read the authors file author_path = os.path.realpath( os.path.join(image_path, '-AUTHOR')) if os.path.isfile(author_path): fh = open(author_path, 'r') image_author = fh.read() fh.close() albums[album_dir]["images"][image_path] = {} albums[album_dir]["images"][image_path][ "author"] = image_author albums[album_dir]["images"][image_path][ "description"] = image_description os.chdir(TMP_DIR) handle_gallery(albums)
def main(arguments): register_heif_opener() # get image info if arguments.exifinfo: try: img = Image.open(arguments.input) except IOError as ex: print("read img failed %s"%ex) img = None exif_editor = pyexif.ExifEditor(arguments.input) exif = exif_editor.getDictTags() # width & height if img: print('width|{0}'.format(img.size[0])) print('height|{0}'.format(img.size[1])) else: print('width|{0}'.format(exif['ImageWidth'])) print('height|{0}'.format(exif['ImageHeight'])) # exif if exif is not None: if 'DateTimeOriginal' in exif.keys(): print('DateTimeOriginal|{0}'.format(exif['DateTimeOriginal'])) if 'Orientation' in exif.keys(): # heif 图片如果宽高是已旋转之后的,就不用返回该值 if img is None: print('orientation|{0}'.format(OrientationDict[exif['Orientation']])) if 'GPSLatitudeRef' in exif.keys(): print('latiR|{0}'.format(exif['GPSLatitudeRef'])) if 'GPSLatitude' in exif.keys(): print('lati|{0}'.format(exif['GPSLatitude'])) if 'GPSLongitudeRef' in exif.keys(): print('longR|{0}'.format(exif['GPSLongitudeRef'])) if 'GPSLongitude' in exif.keys(): print('long|{0}'.format(exif['GPSLongitude'])) if 'GPSAltitudeRef' in exif.keys(): print('altiR|{0}'.format(exif['GPSAltitudeRef'])) if 'GPSAltitude' in exif.keys(): print('alti|{0}'.format(exif['GPSAltitude'])) print("success") return # remove gps if arguments.rmgps: exif_editor = pyexif.ExifEditor(arguments.input) exif_dict = {"GPSLatitudeRef": "", "GPSLatitude": "", "GPSLongitudeRef": "", "GPSLongitude": "", "GPSAltitudeRef": "", "GPSAltitude": "", "GPSAreaInformation": ""} exif_editor.setTags(exif_dict) print("remove gps info success") return if arguments.dominantcolor: try: img = Image.open(arguments.input) except IOError: print("read img failed") img = None proportion, color = get_dominant_color(img) print("dominantColor|{0}".format(color)) print("proportion|{0}".format(proportion)) return # open image try: img = Image.open(arguments.input) except IOError: print("Can't load %s", arguments.input) return # convert to sRGB if contain iccProfile img_convert = convert_to_srgb(img) if img.info.get('icc_profile', '') != img_convert.info.get('icc_profile', ''): img_icc_profile = img_convert.info.get('icc_profile', '') else: img_icc_profile = None # rotate if arguments.rotate: exif_editor = pyexif.ExifEditor(arguments.input) exif = exif_editor.getDictTags() if exif is not None: # find orientation in exif for orientation in ExifTags.TAGS.keys(): if ExifTags.TAGS[orientation] == 'Orientation': orientation_val = exif.get(orientation) if orientation_val: if orientation_val == 2: img_convert = img_convert.transpose(Image.FLIP_LEFT_RIGHT) elif orientation_val == 3: img_convert = img_convert.rotate(180, expand=True) elif orientation_val == 4: img_convert = img_convert.rotate(180, expand=True).transpose(Image.FLIP_LEFT_RIGHT) elif orientation_val == 5: img_convert = img_convert.rotate(-90, expand=True).transpose(Image.FLIP_LEFT_RIGHT) elif orientation_val == 6: img_convert = img_convert.rotate(-90, expand=True) elif orientation_val == 7: img_convert = img_convert.rotate(90, expand=True).transpose(Image.FLIP_LEFT_RIGHT) elif orientation_val == 8: img_convert = img_convert.rotate(90, expand=True) del exif[orientation] break # resize if arguments.resize: # 输出路径以及对应的尺寸 {'out.jpg':'1600x1600'} size_dict = eval(arguments.resize) for output, size in size_dict.items(): size_arr = size.split('x') out_size = list(int(x) for x in size_arr) fit_out_size = fit_size(img.size, out_size) print("resize image to w {0} and h {1}".format(fit_out_size[0], fit_out_size[1])) # resize img_out = img_convert.resize((fit_out_size[0], fit_out_size[1]), Image.ANTIALIAS) # crop if arguments.crop: left = (img_out.size[0] - out_size[0]) / 2 right = left + out_size[0] upper = (img_out.size[1] - out_size[1]) / 2 lower = upper + out_size[1] img_out = img_out.crop((left, upper, right, lower)) save_image(img_out, output, arguments.quality, img_icc_profile) print('resize img success.') return if arguments.output: save_image(img_convert, arguments.output, arguments.quality, img_icc_profile) print("success")