GetCroppedFile.py 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  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.File import File
  8. from pycs.util.FileOperations import BoundingBox
  9. from pycs.util.FileOperations import crop_file
  10. class GetCroppedFile(View):
  11. """
  12. return the image crop defined by the result.
  13. """
  14. # pylint: disable=arguments-differ
  15. methods = ['GET']
  16. def dispatch_request(self, file_id: int, resolution: str, crop_box: str):
  17. # get file from database
  18. file = File.get_or_404(file_id)
  19. project = file.project
  20. if not os.path.exists(file.absolute_path):
  21. abort(404, "File not found!")
  22. # extract desired crop
  23. resolution = re.split(r'[^0-9]', resolution)
  24. max_width = int(resolution[0])
  25. max_height = int(resolution[1]) if len(resolution) > 1 else 2 ** 24
  26. crop_box = re.split(r'[^0-9.]', crop_box)
  27. crop_x = float(crop_box[0])
  28. crop_y = float(crop_box[1]) if len(crop_box) > 1 else 0
  29. crop_w = float(crop_box[2]) if len(crop_box) > 2 else 1 - crop_x
  30. crop_h = float(crop_box[3]) if len(crop_box) > 3 else 1 - crop_y
  31. box = BoundingBox(x=crop_x, y=crop_y, w=crop_w, h=crop_h)
  32. # crop file
  33. file_directory, file_name = tpool.execute(crop_file, file, project.root_folder,
  34. box, max_width, max_height)
  35. # send to client
  36. return send_from_directory(file_directory, file_name)