| 1 |
from PIL import Image, UnidentifiedImageError |
| 2 |
|
| 3 |
|
| 4 |
def get_image_background_color(img, img_format: str): |
| 5 |
has_alpha = img_format in {"hexa", "rgba"} |
| 6 |
img = img.convert("RGBA" if has_alpha else "RGB") |
| 7 |
pixel_color = img.getpixel((1, 1)) |
| 8 |
if img_format in {"hex", "hexa"}: |
| 9 |
color_format = "#" + "%02x" * len(pixel_color) |
| 10 |
color = color_format % pixel_color |
| 11 |
color = color.upper() |
| 12 |
elif img_format in {"rgb", "rgba"}: |
| 13 |
if has_alpha: |
| 14 |
|
| 15 |
pixel_color = ( |
| 16 |
*pixel_color[:3], |
| 17 |
round(pixel_color[3] / 255, 2), |
| 18 |
) |
| 19 |
|
| 20 |
color = f"{img_format}{pixel_color}" |
| 21 |
else: |
| 22 |
raise NotImplementedError(f"Unsupported color format: {img_format}") |
| 23 |
return color |
| 24 |
|
| 25 |
|
| 26 |
def get_image_file_background_color(img_file, img_format: str): |
| 27 |
color = "" |
| 28 |
try: |
| 29 |
with Image.open(img_file) as image: |
| 30 |
color = get_image_background_color(image, img_format) |
| 31 |
except UnidentifiedImageError: |
| 32 |
pass |
| 33 |
return color |