Skip to content
Merged
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
20 changes: 20 additions & 0 deletions Tests/test_file_apng.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from __future__ import annotations

from io import BytesIO
from pathlib import Path

import pytest
Expand Down Expand Up @@ -718,6 +719,25 @@ def test_apng_save_size(tmp_path: Path) -> None:
assert reloaded.size == (200, 200)


def test_compress_level() -> None:
compress_level_sizes = {}
for compress_level in (0, 9):
out = BytesIO()

im = Image.new("L", (100, 100))
im.save(
out,
"PNG",
save_all=True,
append_images=[Image.new("L", (200, 200))],
compress_level=compress_level,
)

compress_level_sizes[compress_level] = len(out.getvalue())

assert compress_level_sizes[0] > compress_level_sizes[9]


def test_seek_after_close() -> None:
im = Image.open("Tests/images/apng/delay.png")
im.seek(1)
Expand Down
25 changes: 14 additions & 11 deletions src/PIL/PngImagePlugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -1152,6 +1152,15 @@ def write(self, data: bytes) -> None:
self.seq_num += 1


def _apply_encoderinfo(im: Image.Image, encoderinfo: dict[str, Any]) -> None:
im.encoderconfig = (
encoderinfo.get("optimize", False),
encoderinfo.get("compress_level", -1),
encoderinfo.get("compress_type", -1),
encoderinfo.get("dictionary", b""),
)


class _Frame(NamedTuple):
im: Image.Image
bbox: tuple[int, int, int, int] | None
Expand Down Expand Up @@ -1245,10 +1254,10 @@ def _write_multiple_frames(

# default image IDAT (if it exists)
if default_image:
if im.mode != mode:
im = im.convert(mode)
default_im = im if im.mode == mode else im.convert(mode)
_apply_encoderinfo(default_im, im.encoderinfo)
ImageFile._save(
im,
default_im,
cast(IO[bytes], _idat(fp, chunk)),
[ImageFile._Tile("zip", (0, 0) + im.size, 0, rawmode)],
)
Expand Down Expand Up @@ -1282,6 +1291,7 @@ def _write_multiple_frames(
)
seq_num += 1
# frame data
_apply_encoderinfo(im_frame, im.encoderinfo)
if frame == 0 and not default_image:
# first frame must be in IDAT chunks for backwards compatibility
ImageFile._save(
Expand Down Expand Up @@ -1357,14 +1367,6 @@ def _save(
bits = 4
outmode += f";{bits}"

# encoder options
im.encoderconfig = (
im.encoderinfo.get("optimize", False),
im.encoderinfo.get("compress_level", -1),
im.encoderinfo.get("compress_type", -1),
im.encoderinfo.get("dictionary", b""),
)

# get the corresponding PNG mode
try:
rawmode, bit_depth, color_type = _OUTMODES[outmode]
Expand Down Expand Up @@ -1494,6 +1496,7 @@ def _save(
im, fp, chunk, mode, rawmode, default_image, append_images
)
if single_im:
_apply_encoderinfo(single_im, im.encoderinfo)
ImageFile._save(
single_im,
cast(IO[bytes], _idat(fp, chunk)),
Expand Down
Loading