|
| 1 | +import base64 |
| 2 | +import io |
| 3 | +from typing import Any |
| 4 | + |
| 5 | +from PIL import Image |
| 6 | + |
| 7 | +from ..Enum import ImageFormatEnum |
| 8 | +from .BaseFilter import BaseFilter |
| 9 | + |
| 10 | + |
| 11 | +class Base64ImageResizeFilter(BaseFilter): |
| 12 | + """ |
| 13 | + A filter to reduce the file size of a base64-encoded |
| 14 | + image by resizing and compressing it. |
| 15 | + """ |
| 16 | + |
| 17 | + def __init__( |
| 18 | + self, |
| 19 | + max_size: int = 4 * 1024 * 1024, |
| 20 | + format: ImageFormatEnum = ImageFormatEnum.JPEG, |
| 21 | + preserve_icc_profile: bool = False, |
| 22 | + preserve_metadata: bool = False, |
| 23 | + ) -> None: |
| 24 | + self.max_size = max_size |
| 25 | + self.format = format |
| 26 | + self.preserve_metadata = preserve_metadata |
| 27 | + self.preserve_icc_profile = preserve_icc_profile |
| 28 | + |
| 29 | + def apply(self, value: Any) -> Any: |
| 30 | + if not isinstance(value, (str, Image.Image)): |
| 31 | + return value |
| 32 | + |
| 33 | + try: |
| 34 | + if isinstance(value, Image.Image): |
| 35 | + return self.reduce_image(value) |
| 36 | + |
| 37 | + value = Image.open(io.BytesIO(base64.b64decode(value))) |
| 38 | + return self.reduce_image(value) |
| 39 | + except Exception: |
| 40 | + return value |
| 41 | + |
| 42 | + def reduce_image(self, image: Image) -> Image: |
| 43 | + """Reduce the size of an image by resizing and compressing it.""" |
| 44 | + is_animated = getattr(image, "is_animated", False) |
| 45 | + |
| 46 | + if not is_animated and image.mode in ("RGBA", "P"): |
| 47 | + image = image.convert("RGB") |
| 48 | + |
| 49 | + buffer = self.save_image_to_buffer(image, quality=80) |
| 50 | + if buffer.getbuffer().nbytes <= self.max_size: |
| 51 | + return self.image_to_base64(image) |
| 52 | + |
| 53 | + new_width, new_height = image.size |
| 54 | + |
| 55 | + while ( |
| 56 | + buffer.getbuffer().nbytes > self.max_size |
| 57 | + and new_width > 10 |
| 58 | + and new_height > 10 |
| 59 | + ): |
| 60 | + new_width = int(new_width * 0.9) |
| 61 | + new_height = int(new_height * 0.9) |
| 62 | + image = image.resize((new_width, new_height), Image.LANCZOS) |
| 63 | + |
| 64 | + buffer = self.save_image_to_buffer(image, quality=80) |
| 65 | + |
| 66 | + quality = 80 |
| 67 | + while buffer.getbuffer().nbytes > self.max_size and quality > 0: |
| 68 | + buffer = self.save_image_to_buffer(image, quality) |
| 69 | + quality -= 5 |
| 70 | + |
| 71 | + return self.image_to_base64(image) |
| 72 | + |
| 73 | + def save_image_to_buffer( |
| 74 | + self, image: Image.Image, quality: int |
| 75 | + ) -> io.BytesIO: |
| 76 | + """Save the image to an in-memory buffer with the specified quality.""" |
| 77 | + buffer = io.BytesIO() |
| 78 | + image.save(buffer, format=self.format.value, quality=quality) |
| 79 | + buffer.seek(0) |
| 80 | + return buffer |
| 81 | + |
| 82 | + def image_to_base64(self, image: Image) -> str: |
| 83 | + """Convert an image to a base64-encoded string.""" |
| 84 | + buffered = io.BytesIO() |
| 85 | + options = { |
| 86 | + "format": self.format.value, |
| 87 | + "optimize": True, |
| 88 | + } |
| 89 | + if self.preserve_icc_profile: |
| 90 | + options["icc_profile"] = image.info.get("icc_profile", None) |
| 91 | + if self.preserve_metadata: |
| 92 | + options["exif"] = image.info.get("exif", None) |
| 93 | + image.save(buffered, **options) |
| 94 | + return base64.b64encode(buffered.getvalue()).decode("ascii") |
0 commit comments