123456789101112131415161718192021222324252627282930313233343536373839404142 |
- from os import path
- from PIL import Image
- from pycs.projects.MediaFile import MediaFile
- class ImageFile(MediaFile):
- def __init__(self, obj, project_id):
- obj['type'] = 'image'
- super().__init__(obj, project_id)
- def resize(self, maximum_width):
- # check if resized file already exists
- resized = MediaFile(self.copy(), self.project_id)
- resized['id'] = self['id'] + '-' + maximum_width
- target_directory, target_name = self._get_file(resized['id'])
- target_path = path.join(target_directory, target_name)
- if path.exists(target_path):
- return resized
- # load full size image
- current_directory, current_name = self.get_file()
- 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
|