File: utils.py

package info (click to toggle)
python-django-colorfield 0.8.0%2Bds1-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 336 kB
  • sloc: javascript: 2,510; python: 569; makefile: 12; sh: 2
file content (20 lines) | stat: -rw-r--r-- 576 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
from PIL import Image, UnidentifiedImageError


def get_image_background_color(img, alpha=False):
    img = img.convert("RGBA" if alpha else "RGB")
    pixel_color = img.getpixel((1, 1))
    color_format = "#" + "%02x" * len(pixel_color)
    color = color_format % pixel_color
    color = color.upper()
    return color


def get_image_file_background_color(img_file, alpha=False):
    color = ""
    try:
        with Image.open(img_file) as image:
            color = get_image_background_color(image, alpha)
    except UnidentifiedImageError:
        pass
    return color