Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- Improve contribution setup instructions: use `hatch shell`, clarify commands must be run from local clone root (#153)
- Bring coverage back to 100% (#293)
- Fix `Creator.config_indexing` docstring to reflect that only the full-text index is toggled; title indexing is always performed by libzim (#294)
- Fix `format_for` to not modify input BytesIO position (#296)

### Changed

Expand Down
6 changes: 6 additions & 0 deletions src/zimscraperlib/image/probing.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,9 @@ def format_for(
) -> str | None:
"""Pillow format of a given filename, either Pillow-detected or from suffix"""
if not from_suffix:
original_position = 0
if isinstance(src, io.BytesIO):
original_position = src.tell()
try:
with PIL.Image.open(src) as img:
return img.format
Expand All @@ -85,6 +88,9 @@ def format_for(
return "SVG"
else: # pragma: no cover
raise
finally:
if isinstance(src, io.BytesIO):
src.seek(original_position)

if not isinstance(src, pathlib.Path):
raise ValueError(
Expand Down
19 changes: 19 additions & 0 deletions tests/image/test_image.py
Original file line number Diff line number Diff line change
Expand Up @@ -1058,6 +1058,25 @@ def test_format_for_cannot_use_suffix_with_byte_array():
assert format_for(src=io.BytesIO(), from_suffix=True)


@pytest.mark.parametrize(
"seek_to_zero",
[
(True),
(False),
],
)
def test_format_for_does_not_alter_buffer(
svg_image: pathlib.Path, *, seek_to_zero: bool
):
svg_bytes = io.BytesIO()
svg_bytes.write(svg_image.read_bytes())
if seek_to_zero:
svg_bytes.seek(0)
original_position = svg_bytes.tell()
assert format_for(svg_bytes, from_suffix=False) == "SVG"
assert svg_bytes.tell() == original_position


def test_is_valid_image(
png_image: pathlib.Path,
png_image2: pathlib.Path,
Expand Down
Loading