ImageFile.py 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  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, type='data'):
  6. obj['type'] = 'image'
  7. super().__init__(obj, project, type)
  8. def resize(self, maximum_width):
  9. # check if resized file already exists
  10. resized = ImageFile(self.copy(), self.project, 'temp')
  11. resized['id'] = self['id'] + '-' + maximum_width
  12. target_path = resized.path
  13. if path.exists(target_path):
  14. return resized
  15. # load full size image
  16. current_directory, current_name = self.directory, self.full_name
  17. image = Image.open(path.join(current_directory, current_name))
  18. image_width, image_height = image.size
  19. # calculate target height
  20. maximum_width = int(maximum_width)
  21. maximum_height = int(maximum_width * image_height / image_width)
  22. # return self if requested size is larger than the image
  23. if image_width < maximum_width:
  24. return self
  25. # resize image
  26. resized_image = image.resize((maximum_width, maximum_height))
  27. # save to file
  28. resized_image.save(target_path, quality=80)
  29. return resized