| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566 |
- import io
- import PIL
- import PIL.Image
- import base64
- import pathlib
- from .exception import image_exception
- class image:
- def __init__(
- self,
- coded: str,
- thumbnail: int = 400,
- max_size: int = 2 * 1024 * 1024 * 16
- ) -> None:
- if len(coded) > max_size:
- raise image_exception()
- self.__thumbnail = thumbnail
- self.__content = base64.standard_b64decode(coded)
- if not self.valid:
- raise image_exception()
- @property
- def thumbnail(self) -> tuple:
- return (self.__thumbnail, self.__thumbnail)
- @property
- def content(self) -> bytes:
- return self.__content
- @property
- def __file(self) -> io.BytesIO:
- return io.BytesIO(self.content)
- @property
- def __image(self) -> PIL.Image:
- try:
- return PIL.Image.open(self.__file)
-
- except:
- raise image_exception()
-
- def save_thumbnail(self, location: pathlib.Path) -> object:
- with self.__image as image:
- image.thumbnail(self.thumbnail)
- image.save(location)
-
- return self
- def save_full(self, location: pathlib.Path) -> object:
- with self.__image as image:
- image.save(location)
- return self
- @property
- def valid(self) -> bool:
- try:
- with self.__image as image:
- image.verify()
- return True
-
- except:
- return False
|