Skip to content

zimscraperlib.image.illustration

Functions:

get_zim_illustration

get_zim_illustration(
    illustration_location: Path | str,
    width: int = DEFAULT_ZIM_ILLLUSTRATION_SIZE,
    height: int = DEFAULT_ZIM_ILLLUSTRATION_SIZE,
    resize_method: str = "contain",
) -> BytesIO

Get ZIM-ready illustration from any image path or URL

illustration_location will be downloaded if needed. Image is automatically converted to PNG, resized and optimized as needed.

Parameters:

  • illustration_location (Path | str) –

    path or URL to an image

  • width (int, default: DEFAULT_ZIM_ILLLUSTRATION_SIZE ) –

    target illustration width

  • height (int, default: DEFAULT_ZIM_ILLLUSTRATION_SIZE ) –

    target illustration height

  • resize_method (str, default: 'contain' ) –

    method to resize the image ; in general only 'contain' or 'cover' make sense, but 'crop', 'width', 'height' and 'thumbnail' can be used

Source code in src/zimscraperlib/image/illustration.py
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
def get_zim_illustration(
    illustration_location: pathlib.Path | str,
    width: int = DEFAULT_ZIM_ILLLUSTRATION_SIZE,
    height: int = DEFAULT_ZIM_ILLLUSTRATION_SIZE,
    resize_method: str = "contain",
) -> io.BytesIO:
    """Get ZIM-ready illustration from any image path or URL

    illustration_location will be downloaded if needed. Image is automatically
    converted to PNG, resized and optimized as needed.

    Arguments:
        illustration_location: path or URL to an image
        width: target illustration width
        height: target illustration height
        resize_method: method to resize the image ; in general only 'contain' or
          'cover' make sense, but 'crop', 'width', 'height' and 'thumbnail' can be used
    """

    illustration_path = handle_user_provided_file(illustration_location)

    if not illustration_path:
        # given handle_user_provided_file logic, this is not supposed to happen besides
        # when empty string is passed, hence the simple error message
        raise ValueError("Illustration is missing")

    illustration = io.BytesIO()
    illustration_format = format_for(illustration_path, from_suffix=False)
    if illustration_format == "SVG":
        convert_svg2png(illustration_path, illustration, width, height)
    else:
        if illustration_format != "PNG":
            convert_image(illustration_path, illustration, fmt="PNG")
        else:
            illustration = io.BytesIO(illustration_path.read_bytes())
        resize_image(illustration, width, height, method=resize_method)

    optimized_illustration = io.BytesIO()
    optimize_png(illustration, optimized_illustration)

    return optimized_illustration