MediaFile.py 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. from os import path, getcwd
  2. from uuid import uuid1
  3. from PIL import Image
  4. from pycs.observable import ObservableDict
  5. class MediaFile(ObservableDict):
  6. def __init__(self, obj, parent):
  7. super().__init__(obj, parent)
  8. def __get_file(self, id):
  9. file_directory = path.join(getcwd(), 'projects', self.parent['id'], 'data')
  10. file_name = id + self['extension']
  11. return file_directory, file_name
  12. def get_file(self):
  13. return self.__get_file(self['id'])
  14. def add_result(self, result):
  15. result['id'] = str(uuid1())
  16. self['predictionResults'][result['id']] = result
  17. def resize(self, maximum_width):
  18. # check if resized file already exists
  19. resized = MediaFile(self, self.parent)
  20. resized['id'] = self['id'] + '-' + maximum_width
  21. target_directory, target_name = self.__get_file(resized['id'])
  22. target_path = path.join(target_directory, target_name)
  23. if path.exists(target_path):
  24. return resized
  25. # load full size image
  26. current_directory, current_name = self.get_file()
  27. image = Image.open(path.join(current_directory, current_name))
  28. image_width, image_height = image.size
  29. # calculate target height
  30. maximum_width = int(maximum_width)
  31. maximum_height = int(maximum_width * image_height / image_width)
  32. # return self if requested size is larger than the image
  33. if image_width < maximum_width:
  34. return self
  35. # resize image
  36. resized_image = image.resize((maximum_width, maximum_height))
  37. # save to file
  38. resized_image.save(target_path, quality=80)
  39. return resized