6
0

GetCroppedFile.py 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  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 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 dispatch_request(self, file_id: int, resolution: str, crop_box: str):
  16. # get file from database
  17. file = File.get_or_404(file_id)
  18. project = file.project
  19. if not os.path.exists(file.absolute_path):
  20. abort(404, "File not found!")
  21. # extract desired crop
  22. resolution = re.split(r'[^0-9]', resolution)
  23. max_width = int(resolution[0])
  24. max_height = int(resolution[1]) if len(resolution) > 1 else 2 ** 24
  25. crop_box = re.split(r'[^0-9.]', crop_box)
  26. crop_x = float(crop_box[0])
  27. crop_y = float(crop_box[1]) if len(crop_box) > 1 else 0
  28. crop_w = float(crop_box[2]) if len(crop_box) > 2 else 1 - crop_x
  29. crop_h = float(crop_box[3]) if len(crop_box) > 3 else 1 - crop_y
  30. # crop file
  31. file_directory, file_name = tpool.execute(crop_file, file, project.root_folder,
  32. crop_x, crop_y, crop_w, crop_h,
  33. max_width, max_height)
  34. # send to client
  35. return send_from_directory(file_directory, file_name)