Skip to content

Commit

Permalink
Add more admissible types for convert_image + corresponding tests
Browse files Browse the repository at this point in the history
  • Loading branch information
benoit74 committed Feb 12, 2024
1 parent 46345e1 commit 0b7cebf
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 5 deletions.
7 changes: 5 additions & 2 deletions src/zimscraperlib/image/convertion.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
#!/usr/bin/env python3
# vim: ai ts=4 sts=4 et sw=4 nu

import io
import pathlib
from typing import Optional
from typing import Union

import PIL

Expand All @@ -13,7 +14,9 @@


def convert_image(
src: pathlib.Path, dst: pathlib.Path, **params: Optional[dict]
src: Union[pathlib.Path, io.BytesIO],
dst: Union[pathlib.Path, io.BytesIO],
**params: str,
) -> None:
"""convert an image file from one format to another
params: Image.save() parameters. Depends on dest format.
Expand Down
7 changes: 4 additions & 3 deletions src/zimscraperlib/image/utils.py
Original file line number Diff line number Diff line change
@@ -1,17 +1,18 @@
#!/usr/bin/env python
# vim: ai ts=4 sts=4 et sw=4 nu

import io
import pathlib
from typing import Optional
from typing import Optional, Union

from PIL import Image


def save_image(
src: Image, # pyright: ignore
dst: pathlib.Path,
dst: Union[pathlib.Path, io.BytesIO],
fmt: Optional[str] = None,
**params: Optional[dict],
**params: str,
) -> None:
"""PIL.Image.save() wrapper setting default parameters"""
args = {"JPEG": {"quality": 100}, "PNG": {}}.get(fmt, {}) # pyright: ignore
Expand Down
24 changes: 24 additions & 0 deletions tests/image/test_image.py
Original file line number Diff line number Diff line change
Expand Up @@ -296,6 +296,30 @@ def test_change_image_format_defaults(png_image, tmp_path):
assert dst_image.format == "WEBP"


def test_convert_io_src_dst(png_image: pathlib.Path):
src = io.BytesIO(png_image.read_bytes())
dst = io.BytesIO()
convert_image(src, dst, fmt="PNG")
dst_image = Image.open(dst)
assert dst_image.format == "PNG"


def test_convert_io_src_path_dst(png_image: pathlib.Path, tmp_path: pathlib.Path):
src = io.BytesIO(png_image.read_bytes())
dst = tmp_path / "test.png"
convert_image(src, dst, fmt="PNG")
dst_image = Image.open(dst)
assert dst_image.format == "PNG"


def test_convert_path_src_io_dst(png_image: pathlib.Path):
src = png_image
dst = io.BytesIO()
convert_image(src, dst, fmt="PNG")
dst_image = Image.open(dst)
assert dst_image.format == "PNG"


@pytest.mark.parametrize(
"fmt,exp_size",
[("png", 128), ("jpg", 128)],
Expand Down

0 comments on commit 0b7cebf

Please sign in to comment.