from os import path from PIL import Image from pycs.projects.MediaFile import MediaFile class ImageFile(MediaFile): def __init__(self, obj, project, type='data'): obj['type'] = 'image' super().__init__(obj, project, type) def resize(self, maximum_width): # check if resized file already exists resized = ImageFile(self.copy(), self.project, 'temp') resized['id'] = self['id'] + '-' + maximum_width target_path = resized.path if path.exists(target_path): return resized # load full size image current_directory, current_name = self.directory, self.full_name image = Image.open(path.join(current_directory, current_name)) image_width, image_height = image.size # calculate target height maximum_width = int(maximum_width) maximum_height = int(maximum_width * image_height / image_width) # return self if requested size is larger than the image if image_width < maximum_width: return self # resize image resized_image = image.resize((maximum_width, maximum_height)) # save to file resized_image.save(target_path, quality=80) return resized