Advertisement
Guest User

Untitled

a guest
Sep 4th, 2015
65
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.93 KB | None | 0 0
  1.  
  2. class ImageSizeValidator(object):
  3. def __init__(self, min_width=None, min_height=None, max_width=None, max_height=None, min_ratio=None, max_ratio=None):
  4. self.min_width = min_width
  5. self.min_height = min_height
  6. self.max_width = max_width
  7. self.max_height = max_height
  8. self.min_ratio = min_ratio
  9. self.max_ratio = max_ratio
  10.  
  11. def __call__(self, value):
  12. w, h = Image.open(value).size
  13. ratio = float(w)/float(h)
  14. errors = []
  15. error_message_size = "%s is {size} pixel {type}. It's supposed to be {comparison} than {limit}px." % value.name
  16. error_message_ratio = "%s's width/height ratio is {ratio}. It's supposed to be {comparison} than {limit}" % value.name
  17. if self.min_width and w < self.min_width:
  18. errors.append(error_message_size.format(
  19. size=w, type="wide", comparison="greater", limit=self.min_width)
  20. )
  21. if self.min_height and h < self.min_height:
  22. errors.append(error_message_size.format(
  23. size=h, type="high", comparison="greater", limit=self.min_height)
  24. )
  25. if self.max_width and w > self.max_width:
  26. errors.append(error_message_size.format(
  27. size=w, type="wide", comparison="less", limit=self.max_width)
  28. )
  29. if self.max_height and h > self.max_height:
  30. errors.append(error_message_size.format(
  31. size=h, type="high", comparison="less", limit=self.max_height)
  32. )
  33. if self.min_ratio and ratio < self.min_ratio:
  34. errors.append(error_message_ratio.format(
  35. ratio=ratio, comparison="greater", limit=self.min_ratio)
  36. )
  37. if self.max_ratio and ratio > self.max_ratio:
  38. errors.append(error_message_ratio.format(
  39. ratio=ratio, comparison="less", limit=self.max_ratio)
  40. )
  41. if errors:
  42. raise ValidationError(errors)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement