"""Utility functions for image manipulation.""" import hashlib from PIL import Image def transform(input_filename, width, height, output_format, output_filename): """Modify image on disk. Args: input_filename (str): file on disk to modify width (int): resize width height (int): resize height output_format (str): result image encoding output_filename (str): file on disk to save results Returns: None """ with Image.open(input_filename) as im: resized = im.resize((width, height)) resized.save(output_filename, output_format) def analyze(input_filename): """Gather data about an image on disk. Args: input_filename (str): file on disk to analyze Returns: tuple: 0 (str): MD5 digest of file contents 1 (int): width of image 2 (int): height of image """ with Image.open(input_filename) as im: (width, height) = im.size # don't use im.tobytes() with compressed images # https://pillow.readthedocs.io/en/stable/reference/Image.html#PIL.Image.Image.tobytes md5 = hashlib.md5(open(input_filename, 'rb').read()).hexdigest() return ( md5, width, height )