| 1 | # SPDX-License-Identifier: Apache-2.0 |
| 2 | # SPDX-FileCopyrightText: Copyright contributors to the vLLM project |
| 3 | |
| 4 | import contextlib |
| 5 | |
| 6 | from PIL import Image, ImageOps |
| 7 | |
| 8 | |
| 9 | def rescale_image_size( |
| 10 | image: Image.Image, size_factor: float, transpose: int = -1 |
| 11 | ) -> Image.Image: |
| 12 | """Rescale the dimensions of an image by a constant factor.""" |
| 13 | new_width = int(image.width * size_factor) |
| 14 | new_height = int(image.height * size_factor) |
| 15 | image = image.resize((new_width, new_height)) |
| 16 | if transpose >= 0: |
| 17 | image = image.transpose(Image.Transpose(transpose)) |
| 18 | return image |
| 19 | |
| 20 | |
| 21 | def normalize_image(image: Image.Image) -> Image.Image: |
| 22 | """Normalize EXIF orientation so the pixel data matches visual display.""" |
| 23 | with contextlib.suppress(Exception): |
| 24 | image = ImageOps.exif_transpose(image) |
| 25 | return image |
| 26 | |
| 27 | |
| 28 | def rgba_to_rgb( |
| 29 | image: Image.Image, |
| 30 | background_color: tuple[int, int, int] | list[int] = (255, 255, 255), |
| 31 | ) -> Image.Image: |
| 32 | """Convert an RGBA image to RGB with filled background color.""" |
| 33 | assert image.mode == "RGBA" |
| 34 | converted = Image.new("RGB", image.size, background_color) |
| 35 | converted.paste(image, mask=image.split()[3]) # 3 is the alpha channel |
| 36 | return converted |
| 37 | |
| 38 | |
| 39 | def _has_transparency(image: Image.Image) -> bool: |
| 40 | """Detect whether an image carries transparency data (RGBA, LA, PA, |
| 41 | or tRNS chunk in P/L/RGB PNGs).""" |
| 42 | if image.mode in ("RGBA", "LA", "PA"): |
| 43 | return True |
| 44 | return "transparency" in getattr(image, "info", {}) |
| 45 | |
| 46 | |
| 47 | def convert_image_mode( |
| 48 | image: Image.Image, |
| 49 | to_mode: str, |
| 50 | background_color: tuple[int, int, int] | list[int] = (255, 255, 255), |
| 51 | ) -> Image.Image: |
| 52 | if image.mode == to_mode: |
| 53 | return image |
| 54 | |
| 55 | if to_mode == "RGB" and _has_transparency(image): |
| 56 | if image.mode != "RGBA": |
| 57 | image = image.convert("RGBA") |
| 58 | return rgba_to_rgb(image, background_color) |
| 59 | |
| 60 | return image.convert(to_mode) |