image.py

Common functions to manipulate images

get_screen_size(dict_cfg)

Get screen size (only when install/first run)

:param dict_cfg: the dict to put the sizes in :type dict_cfg: dict[str, int]

Source code in src/image.py
def get_screen_size(dict_cfg: dict[str, int]):
    """
    Get screen size (only when install/first run)

    :param dict_cfg: the dict to put the sizes in
    :type dict_cfg: dict[str, int]
    """
    # initial values for testing re
    scr_w = 0
    scr_h = 0

    # get screen size
    try:

        # try to run cmd
        cp = F.run(S_RE_CMD, shell=True, capture_output=True)

        # find screen size using regex
        res = re.search(S_RE_SCH, cp.stdout)
        if res:
            scr_w = int(res.group(1))
            scr_h = int(res.group(2))

        # regex error
        if scr_w == 0 or scr_h == 0:
            # failed to get screen size, fatal error
            raise OSError()

        dict_cfg[K.S_KEY_SCREEN_WIDTH] = scr_w
        dict_cfg[K.S_KEY_SCREEN_HEIGHT] = scr_h

    # cmd error
    except F.CNRunError as exc:
        raise OSError() from exc

resize_and_crop(path, dict_cfg)

Resize and crop downloaded image in place

:param path: Path to the original image (also used as output) :type path: Path :raises: OSError if we could not determine screen size

Source code in src/image.py
def resize_and_crop(path: Path, dict_cfg: dict[str, int]):
    """
    Resize and crop downloaded image in place

    :param path: Path to the original image (also used as output)
    :type path: Path
    :raises: OSError if we could not determine screen size
    """

    # --------------------------------------------------------------------------
    # get screen size

    # get default values
    scr_w = dict_cfg[K.S_KEY_SCREEN_WIDTH]
    scr_h = dict_cfg[K.S_KEY_SCREEN_HEIGHT]

    # --------------------------------------------------------------------------
    # get downloaded image and size

    wp = Image.open(path)
    wp_w, wp_h = wp.size

    # --------------------------------------------------------------------------
    # resize img to screen rect (to fill)

    # get scale in both directions and find max
    rat_w = scr_w / wp_w
    rat_h = scr_h / wp_h
    scale = max(rat_w, rat_h)

    # scale the image and get new size
    scale_w = int(wp_w * scale)
    scale_h = int(wp_h * scale)
    wp = wp.resize([scale_w, scale_h], Image.Resampling.LANCZOS)
    wp_w, wp_h = wp.size

    # --------------------------------------------------------------------------
    # get size of screen vs size of image and crop

    off_x = int((wp_w - scr_w) / 2)
    off_y = int((wp_h - scr_h) / 2)
    off_w = off_x + scr_w
    off_h = off_y + scr_h
    # NB: make a tuple for readability
    t_crop = (off_x, off_y, off_w, off_h)
    wp = wp.crop(t_crop)

    # save resized/cropped wallpaper w/ same name
    wp.save(path)