1
1

GetCroppedFile.py 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. import os
  2. import re
  3. from eventlet import tpool
  4. from flask import abort
  5. from flask import send_from_directory
  6. from flask.views import View
  7. from pycs.database.Database import Database
  8. from pycs.util.FileOperations import crop_file
  9. class GetCroppedFile(View):
  10. """
  11. return the image crop defined by the result.
  12. """
  13. # pylint: disable=arguments-differ
  14. methods = ['GET']
  15. def __init__(self, db: Database):
  16. # pylint: disable=invalid-name
  17. self.db = db
  18. def dispatch_request(self, file_id: int, resolution: str, crop_box: str):
  19. # get file from database
  20. file = self.db.file(file_id)
  21. if file is None:
  22. return abort(404)
  23. project = file.project()
  24. if not os.path.exists(file.absolute_path):
  25. abort(404, "File not found!")
  26. # extract desired crop
  27. resolution = re.split(r'[^0-9]', resolution)
  28. max_width = int(resolution[0])
  29. max_height = int(resolution[1]) if len(resolution) > 1 else 2 ** 24
  30. crop_box = re.split(r'[^0-9.]', crop_box)
  31. crop_x = float(crop_box[0])
  32. crop_y = float(crop_box[1]) if len(crop_box) > 1 else 0
  33. crop_w = float(crop_box[2]) if len(crop_box) > 2 else 1 - crop_x
  34. crop_h = float(crop_box[3]) if len(crop_box) > 3 else 1 - crop_y
  35. # crop file
  36. file_directory, file_name = tpool.execute(crop_file, file, project.root_folder,
  37. crop_x, crop_y, crop_w, crop_h,
  38. max_width, max_height)
  39. # send to client
  40. return send_from_directory(file_directory, file_name)