ImageFile.py 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. from os import path
  2. from PIL import Image
  3. from pycs.projects.MediaFile import MediaFile
  4. class ImageFile(MediaFile):
  5. def __init__(self, obj, project_id):
  6. obj['type'] = 'image'
  7. super().__init__(obj, project_id)
  8. def resize(self, maximum_width):
  9. # check if resized file already exists
  10. resized = MediaFile(self.copy(), self.project_id)
  11. resized['id'] = self['id'] + '-' + maximum_width
  12. target_directory, target_name = self._get_file(resized['id'])
  13. target_path = path.join(target_directory, target_name)
  14. if path.exists(target_path):
  15. return resized
  16. # load full size image
  17. current_directory, current_name = self.get_file()
  18. image = Image.open(path.join(current_directory, current_name))
  19. image_width, image_height = image.size
  20. # calculate target height
  21. maximum_width = int(maximum_width)
  22. maximum_height = int(maximum_width * image_height / image_width)
  23. # return self if requested size is larger than the image
  24. if image_width < maximum_width:
  25. return self
  26. # resize image
  27. resized_image = image.resize((maximum_width, maximum_height))
  28. # save to file
  29. resized_image.save(target_path, quality=80)
  30. return resized