image.py 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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. def __init__(
  9. self,
  10. coded: str,
  11. thumbnail: int = 400,
  12. max_size: int = 2 * 1024 * 1024 * 16
  13. ) -> None:
  14. if len(coded) > max_size:
  15. raise image_exception()
  16. self.__thumbnail = thumbnail
  17. self.__content = base64.standard_b64decode(coded)
  18. if not self.valid:
  19. raise image_exception()
  20. @property
  21. def thumbnail(self) -> tuple:
  22. return (self.__thumbnail, self.__thumbnail)
  23. @property
  24. def content(self) -> bytes:
  25. return self.__content
  26. @property
  27. def __file(self) -> io.BytesIO:
  28. return io.BytesIO(self.content)
  29. @property
  30. def __image(self) -> PIL.Image:
  31. try:
  32. return PIL.Image.open(self.__file)
  33. except:
  34. raise image_exception()
  35. def save_thumbnail(self, location: pathlib.Path) -> object:
  36. with self.__image as image:
  37. image.thumbnail(self.thumbnail)
  38. image.save(location)
  39. return self
  40. def save_full(self, location: pathlib.Path) -> object:
  41. with self.__image as image:
  42. image.save(location)
  43. return self
  44. @property
  45. def valid(self) -> bool:
  46. try:
  47. with self.__image as image:
  48. image.verify()
  49. return True
  50. except:
  51. return False