image.py 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. import io
  2. import PIL
  3. import PIL.Image
  4. import base64
  5. import pathlib
  6. from .exception import image_exception
  7. class image:
  8. """
  9. This class is responsible for image storing. It get image coded as base64
  10. validate it, and when all went well, it could be saved and also thumbnail
  11. could be generated.
  12. """
  13. def __init__(
  14. self,
  15. coded: str,
  16. max_size: int = 2 * 1024 * 1024 * 16
  17. ) -> None:
  18. """
  19. This initialize new image saver.
  20. Parameters:
  21. coded (str): Image as base64 content
  22. thumbnail (int): Diameters of image thumbnail (default = 400)
  23. max_size (int): Max size of image file (default = 16Mb)
  24. """
  25. if len(coded) > max_size:
  26. raise image_exception()
  27. self.__content = base64.standard_b64decode(coded)
  28. if not self.valid:
  29. raise image_exception()
  30. @property
  31. def content(self) -> bytes:
  32. """ Image as bytes. """
  33. return self.__content
  34. @property
  35. def __file(self) -> io.BytesIO:
  36. """ Image bytes as IO file like buffer. """
  37. return io.BytesIO(self.content)
  38. @property
  39. def __image(self) -> PIL.Image:
  40. """ New PIL Image object from received bytes. """
  41. try:
  42. return PIL.Image.open(self.__file)
  43. except:
  44. raise image_exception()
  45. def save_thumbnail(
  46. self,
  47. location: pathlib.Path,
  48. diameter: int = 400
  49. ) -> object:
  50. """
  51. This save generated thumbnail in given location. Format of the
  52. thumbnail is defined by location extension.
  53. Parameters:
  54. location (pathlib.Path): Place to store thumbnail
  55. Returns:
  56. (image): Self to chain dot calls
  57. """
  58. with self.__image as image:
  59. image.thumbnail((diameter, diameter))
  60. image.save(location)
  61. return self
  62. def save_full(self, location: pathlib.Path) -> object:
  63. """
  64. This save received image in given location. Format of the image is
  65. based on the location extension.
  66. Parameters:
  67. location (pathlib.Path): Place to store image
  68. Returns:
  69. (image): Self to chain dot calls
  70. """
  71. with self.__image as image:
  72. image.save(location)
  73. return self
  74. @property
  75. def valid(self) -> bool:
  76. """ True when image is valid, false when not. """
  77. try:
  78. with self.__image as image:
  79. image.verify()
  80. return True
  81. except:
  82. return False