| 1 | import base64 |
| 2 | import cv2 |
| 3 | from typing import List, Literal, Optional, Union |
| 4 | from PIL import Image |
| 5 | |
| 6 | from utils.image import download_image |
| 7 | |
| 8 | |
| 9 | |
| 10 | class ImageOutput: |
| 11 | fmt: Literal["b64", "url", "pil", "np"] |
| 12 | ext: str = "png" |
| 13 | data: Union[str, Image.Image] |
| 14 | |
| 15 | def __init__( |
| 16 | self, |
| 17 | fmt: Literal["b64", "url", "pil", "np"], |
| 18 | ext: str, |
| 19 | data: Union[str, Image.Image], |
| 20 | ): |
| 21 | self.fmt = fmt |
| 22 | self.ext = ext |
| 23 | self.data = data |
| 24 | |
| 25 | |
| 26 | def save_b64(self, path: str) -> None: |
| 27 | """Save a base64 encoded image to the specified path. |
| 28 | |
| 29 | Args: |
| 30 | path (str): Path where the image will be saved. |
| 31 | """ |
| 32 | with open(path, 'wb') as f: |
| 33 | f.write(base64.b64decode(self.data)) |
| 34 | |
| 35 | def save_url(self, path: str) -> None: |
| 36 | """Download and save an image from a URL to the specified path. |
| 37 | |
| 38 | Args: |
| 39 | path (str): Path where the image will be saved. |
| 40 | """ |
| 41 | download_image(self.data, path) |
| 42 | |
| 43 | def save_pil(self, path: str) -> None: |
| 44 | """Save a PIL Image to the specified path. |
| 45 | |
| 46 | Args: |
| 47 | path (str): Path where the image will be saved. |
| 48 | """ |
| 49 | self.data.save(path) |
| 50 | |
| 51 | def save_np(self, path: str) -> None: |
| 52 | """Save a numpy array to the specified path. |
| 53 | |
| 54 | Args: |
| 55 | path (str): Path where the image will be saved. |
| 56 | """ |
| 57 | cv2.imencode('.png', self.data)[1].tofile(path) |
| 58 | |
| 59 | def save(self, path: str) -> None: |
| 60 | save_func = getattr(self, f"save_{self.fmt}") |
| 61 | save_func(path) |