|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +import base64 |
| 4 | +import io |
| 5 | +from typing import Any, Optional |
| 6 | + |
| 7 | +from PIL import Image |
| 8 | + |
| 9 | +from flask_inputfilter.enums import ImageFormatEnum |
| 10 | +from flask_inputfilter.models import BaseFilter |
| 11 | + |
| 12 | + |
| 13 | +class ToBase64ImageFilter(BaseFilter): |
| 14 | + """ |
| 15 | + Converts an image to a base64 encoded string. Supports various input |
| 16 | + formats including file paths, bytes, or PIL Image objects. |
| 17 | +
|
| 18 | + **Parameters:** |
| 19 | +
|
| 20 | + - **format** (*ImageFormatEnum*, default: ``ImageFormatEnum.PNG``): |
| 21 | + The output image format for the base64 encoding. |
| 22 | + - **quality** (*int*, default: ``85``): The image quality (1-100) for |
| 23 | + lossy formats like JPEG. Higher values mean better quality. |
| 24 | +
|
| 25 | + **Expected Behavior:** |
| 26 | +
|
| 27 | + Converts the input image to a base64 encoded string: |
| 28 | + - If input is a PIL Image object, converts it directly |
| 29 | + - If input is a string, tries to open it as a file path |
| 30 | + - If input is bytes, tries to open as image data |
| 31 | + - If input is already a base64 string, validates and returns it |
| 32 | + - Returns the original value if conversion fails |
| 33 | +
|
| 34 | + **Example Usage:** |
| 35 | +
|
| 36 | + .. code-block:: python |
| 37 | +
|
| 38 | + class ImageFilter(InputFilter): |
| 39 | + def __init__(self): |
| 40 | + super().__init__() |
| 41 | +
|
| 42 | + self.add('image', filters=[ |
| 43 | + ToBase64ImageFilter(format=ImageFormatEnum.JPEG) |
| 44 | + ]) |
| 45 | + """ |
| 46 | + |
| 47 | + __slots__ = ("format", "quality") |
| 48 | + |
| 49 | + def __init__( |
| 50 | + self, |
| 51 | + format: Optional[ImageFormatEnum] = None, |
| 52 | + quality: int = 85, |
| 53 | + ) -> None: |
| 54 | + self.format = format if format else ImageFormatEnum.PNG |
| 55 | + self.quality = quality |
| 56 | + |
| 57 | + def apply(self, value: Any) -> Any: |
| 58 | + if isinstance(value, Image.Image): |
| 59 | + return self._image_to_base64(value) |
| 60 | + |
| 61 | + # Try to open as file path |
| 62 | + if isinstance(value, str): |
| 63 | + try: |
| 64 | + with Image.open(value) as img: |
| 65 | + return self._image_to_base64(img) |
| 66 | + except OSError: |
| 67 | + pass |
| 68 | + |
| 69 | + # Try to decode as base64 |
| 70 | + try: |
| 71 | + Image.open(io.BytesIO(base64.b64decode(value))).verify() |
| 72 | + return value |
| 73 | + except Exception: |
| 74 | + pass |
| 75 | + |
| 76 | + # Try to open as raw bytes |
| 77 | + if isinstance(value, bytes): |
| 78 | + try: |
| 79 | + img = Image.open(io.BytesIO(value)) |
| 80 | + return self._image_to_base64(img) |
| 81 | + except OSError: |
| 82 | + pass |
| 83 | + |
| 84 | + return value |
| 85 | + |
| 86 | + def _image_to_base64(self, image: Image.Image) -> str: |
| 87 | + """Convert a PIL Image to base64 encoded string.""" |
| 88 | + if image.mode in ("RGBA", "P"): |
| 89 | + image = image.convert("RGB") |
| 90 | + |
| 91 | + buffered = io.BytesIO() |
| 92 | + |
| 93 | + save_options = {"format": self.format.value} |
| 94 | + |
| 95 | + if self.format in (ImageFormatEnum.JPEG, ImageFormatEnum.WEBP): |
| 96 | + save_options["quality"] = self.quality |
| 97 | + save_options["optimize"] = True |
| 98 | + |
| 99 | + image.save(buffered, **save_options) |
| 100 | + |
| 101 | + return base64.b64encode(buffered.getvalue()).decode("ascii") |
0 commit comments