aboutsummaryrefslogtreecommitdiffstats
path: root/bsie/reader/preview/utils.py
blob: 82ecc316fb6c4d9c3137f80a327f0572a2dabc7e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34

# standard imports
import typing

# external imports
import PIL.Image

# exports
__all__: typing.Sequence[str] = (
    'resize',
    )


## code ##

def resize(
        img: PIL.Image.Image,
        max_size: int,
        ) -> PIL.Image.Image:
    """Resize an image to a given maximum side length."""
    # determine target dimensions
    ratio = img.width / img.height
    if img.width > img.height:
        width, height = max_size, round(max_size / ratio)
    else:
        width, height = round(ratio * max_size), max_size
    # rescale and return
    return img.resize(
        (width, height),
        resample=PIL.Image.Resampling.LANCZOS, # create high-quality image
        reducing_gap=3.0, # optimize computation via fast size reduction
        )

## EOF ##