LastPNGImagePlugin 0.2.0__tar.gz → 0.2.1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. lastpngimageplugin-0.2.1/PKG-INFO +92 -0
  2. lastpngimageplugin-0.2.1/README.md +79 -0
  3. {lastpngimageplugin-0.2.0 → lastpngimageplugin-0.2.1}/pyproject.toml +1 -1
  4. {lastpngimageplugin-0.2.0 → lastpngimageplugin-0.2.1}/src/LastPNGImagePlugin.py +58 -52
  5. {lastpngimageplugin-0.2.0 → lastpngimageplugin-0.2.1}/tests/test_pillow_plugin.py +69 -6
  6. lastpngimageplugin-0.2.0/PKG-INFO +0 -148
  7. lastpngimageplugin-0.2.0/README.md +0 -135
  8. {lastpngimageplugin-0.2.0 → lastpngimageplugin-0.2.1}/.gitignore +0 -0
  9. {lastpngimageplugin-0.2.0 → lastpngimageplugin-0.2.1}/LICENSE +0 -0
  10. {lastpngimageplugin-0.2.0 → lastpngimageplugin-0.2.1}/decoder/Cargo.lock +0 -0
  11. {lastpngimageplugin-0.2.0 → lastpngimageplugin-0.2.1}/decoder/Cargo.toml +0 -0
  12. {lastpngimageplugin-0.2.0 → lastpngimageplugin-0.2.1}/decoder/src/lib.rs +0 -0
  13. {lastpngimageplugin-0.2.0 → lastpngimageplugin-0.2.1}/hatch_build.py +0 -0
  14. {lastpngimageplugin-0.2.0 → lastpngimageplugin-0.2.1}/licenses/fdeflate-LICENSE-MIT +0 -0
  15. {lastpngimageplugin-0.2.0 → lastpngimageplugin-0.2.1}/licenses/libdeflate-COPYING +0 -0
  16. {lastpngimageplugin-0.2.0 → lastpngimageplugin-0.2.1}/rust/Cargo.lock +0 -0
  17. {lastpngimageplugin-0.2.0 → lastpngimageplugin-0.2.1}/rust/Cargo.toml +0 -0
  18. {lastpngimageplugin-0.2.0 → lastpngimageplugin-0.2.1}/rust/build.rs +0 -0
  19. {lastpngimageplugin-0.2.0 → lastpngimageplugin-0.2.1}/rust/include/lastpng.h +0 -0
  20. {lastpngimageplugin-0.2.0 → lastpngimageplugin-0.2.1}/rust/models/higher.f32le +0 -0
  21. {lastpngimageplugin-0.2.0 → lastpngimageplugin-0.2.1}/rust/native/row_deflate.c +0 -0
  22. {lastpngimageplugin-0.2.0 → lastpngimageplugin-0.2.1}/rust/src/deflate.rs +0 -0
  23. {lastpngimageplugin-0.2.0 → lastpngimageplugin-0.2.1}/rust/src/encode.rs +0 -0
  24. {lastpngimageplugin-0.2.0 → lastpngimageplugin-0.2.1}/rust/src/ffi.rs +0 -0
  25. {lastpngimageplugin-0.2.0 → lastpngimageplugin-0.2.1}/rust/src/lib.rs +0 -0
  26. {lastpngimageplugin-0.2.0 → lastpngimageplugin-0.2.1}/rust/src/palette.rs +0 -0
  27. {lastpngimageplugin-0.2.0 → lastpngimageplugin-0.2.1}/rust/src/row_deflate.rs +0 -0
  28. {lastpngimageplugin-0.2.0 → lastpngimageplugin-0.2.1}/rust/src/row_model.rs +0 -0
  29. {lastpngimageplugin-0.2.0 → lastpngimageplugin-0.2.1}/rust/src/tiny.rs +0 -0
  30. {lastpngimageplugin-0.2.0 → lastpngimageplugin-0.2.1}/rust/src/ultrafast.rs +0 -0
  31. {lastpngimageplugin-0.2.0 → lastpngimageplugin-0.2.1}/rust/vendor/fdeflate-LICENSE-MIT +0 -0
  32. {lastpngimageplugin-0.2.0 → lastpngimageplugin-0.2.1}/rust/vendor/libdeflate/COPYING +0 -0
  33. {lastpngimageplugin-0.2.0 → lastpngimageplugin-0.2.1}/rust/vendor/libdeflate/README.md +0 -0
  34. {lastpngimageplugin-0.2.0 → lastpngimageplugin-0.2.1}/rust/vendor/libdeflate/common_defs.h +0 -0
  35. {lastpngimageplugin-0.2.0 → lastpngimageplugin-0.2.1}/rust/vendor/libdeflate/lib/adler32.c +0 -0
  36. {lastpngimageplugin-0.2.0 → lastpngimageplugin-0.2.1}/rust/vendor/libdeflate/lib/arm/adler32_impl.h +0 -0
  37. {lastpngimageplugin-0.2.0 → lastpngimageplugin-0.2.1}/rust/vendor/libdeflate/lib/arm/cpu_features.c +0 -0
  38. {lastpngimageplugin-0.2.0 → lastpngimageplugin-0.2.1}/rust/vendor/libdeflate/lib/arm/cpu_features.h +0 -0
  39. {lastpngimageplugin-0.2.0 → lastpngimageplugin-0.2.1}/rust/vendor/libdeflate/lib/arm/matchfinder_impl.h +0 -0
  40. {lastpngimageplugin-0.2.0 → lastpngimageplugin-0.2.1}/rust/vendor/libdeflate/lib/bt_matchfinder.h +0 -0
  41. {lastpngimageplugin-0.2.0 → lastpngimageplugin-0.2.1}/rust/vendor/libdeflate/lib/bt_matchfinder_search.h +0 -0
  42. {lastpngimageplugin-0.2.0 → lastpngimageplugin-0.2.1}/rust/vendor/libdeflate/lib/cpu_features_common.h +0 -0
  43. {lastpngimageplugin-0.2.0 → lastpngimageplugin-0.2.1}/rust/vendor/libdeflate/lib/deflate_compress.c +0 -0
  44. {lastpngimageplugin-0.2.0 → lastpngimageplugin-0.2.1}/rust/vendor/libdeflate/lib/deflate_compress.h +0 -0
  45. {lastpngimageplugin-0.2.0 → lastpngimageplugin-0.2.1}/rust/vendor/libdeflate/lib/deflate_constants.h +0 -0
  46. {lastpngimageplugin-0.2.0 → lastpngimageplugin-0.2.1}/rust/vendor/libdeflate/lib/deflate_write_sequences.h +0 -0
  47. {lastpngimageplugin-0.2.0 → lastpngimageplugin-0.2.1}/rust/vendor/libdeflate/lib/hc_matchfinder.h +0 -0
  48. {lastpngimageplugin-0.2.0 → lastpngimageplugin-0.2.1}/rust/vendor/libdeflate/lib/ht_matchfinder.h +0 -0
  49. {lastpngimageplugin-0.2.0 → lastpngimageplugin-0.2.1}/rust/vendor/libdeflate/lib/lib_common.h +0 -0
  50. {lastpngimageplugin-0.2.0 → lastpngimageplugin-0.2.1}/rust/vendor/libdeflate/lib/matchfinder_common.h +0 -0
  51. {lastpngimageplugin-0.2.0 → lastpngimageplugin-0.2.1}/rust/vendor/libdeflate/lib/riscv/matchfinder_impl.h +0 -0
  52. {lastpngimageplugin-0.2.0 → lastpngimageplugin-0.2.1}/rust/vendor/libdeflate/lib/utils.c +0 -0
  53. {lastpngimageplugin-0.2.0 → lastpngimageplugin-0.2.1}/rust/vendor/libdeflate/lib/x86/adler32_impl.h +0 -0
  54. {lastpngimageplugin-0.2.0 → lastpngimageplugin-0.2.1}/rust/vendor/libdeflate/lib/x86/adler32_template.h +0 -0
  55. {lastpngimageplugin-0.2.0 → lastpngimageplugin-0.2.1}/rust/vendor/libdeflate/lib/x86/cpu_features.c +0 -0
  56. {lastpngimageplugin-0.2.0 → lastpngimageplugin-0.2.1}/rust/vendor/libdeflate/lib/x86/cpu_features.h +0 -0
  57. {lastpngimageplugin-0.2.0 → lastpngimageplugin-0.2.1}/rust/vendor/libdeflate/lib/x86/matchfinder_impl.h +0 -0
  58. {lastpngimageplugin-0.2.0 → lastpngimageplugin-0.2.1}/rust/vendor/libdeflate/lib/zlib_compress.c +0 -0
  59. {lastpngimageplugin-0.2.0 → lastpngimageplugin-0.2.1}/rust/vendor/libdeflate/lib/zlib_constants.h +0 -0
  60. {lastpngimageplugin-0.2.0 → lastpngimageplugin-0.2.1}/rust/vendor/libdeflate/libdeflate.h +0 -0
  61. {lastpngimageplugin-0.2.0 → lastpngimageplugin-0.2.1}/tests/test_native_loading.py +0 -0
@@ -0,0 +1,92 @@
1
+ Metadata-Version: 2.5
2
+ Name: LastPNGImagePlugin
3
+ Version: 0.2.1
4
+ Summary: A vibe-coded, blazingly fast PNG compressor for Pillow
5
+ License-Expression: MIT
6
+ License-File: LICENSE
7
+ License-File: licenses/fdeflate-LICENSE-MIT
8
+ License-File: licenses/libdeflate-COPYING
9
+ Requires-Python: >=3.10
10
+ Requires-Dist: cffi>=1.17
11
+ Requires-Dist: pillow<=13.0.0,>=11
12
+ Description-Content-Type: text/markdown
13
+
14
+ # LastPNG for Pillow
15
+
16
+ LastPNG makes reading and saving PNG images in Pillow faster and optimizes file size by choosing the palette, bit depth, and color type automatically. Output remains standard PNG, preserving visible colors and transparency; RGB values in fully transparent pixels may change. Reading supports PNG and APNG, with Pillow handling metadata and animation composition.
17
+
18
+ ## Installation
19
+
20
+ Requires Python ≥3.10 and Pillow ≥11, ≤13.0.0.
21
+
22
+ ```sh
23
+ pip install LastPNGImagePlugin
24
+ ```
25
+
26
+ Wheels bundle the native libraries; no separate libdeflate or Windows VC Redistributable installation is needed.
27
+
28
+ ## Usage
29
+
30
+ ```python
31
+ from PIL import Image
32
+ import LastPNGImagePlugin
33
+
34
+ # Select LastPNG explicitly when saving.
35
+ with Image.open("input.png") as image:
36
+ image.save("output.png", format="LASTPNG", level=3)
37
+
38
+ # Use Rust decoding and LastPNG encoding by default throughout the process.
39
+ LastPNGImagePlugin.register_as_default()
40
+ with Image.open("input.png") as image:
41
+ image.save("output.png", level=3)
42
+ ```
43
+
44
+ Use `register_as_default(encoder=False)` to enable only Rust decoding and keep the current PNG encoder.
45
+
46
+ Choose a compression level from 1 (fastest) to 6 (experimental, highest effort). The default is 3.
47
+
48
+ ### Save options
49
+
50
+ Supports `pnginfo`, `icc_profile`, `transparency`, `dpi`, and `exif`. An ICC profile preserves the input color family.
51
+
52
+ In `pnginfo`, IHDR, PLTE, tRNS, IDAT, IEND, bKGD, hIST, sBIT, eXIf, and iCCP raise `ValueError`. LastPNG selects the output representation; use `exif=` for EXIF and `icc_profile=` for an uncompressed ICC profile.
53
+
54
+ For a unitless pixel aspect ratio or exact pixels-per-metre values, pass one `pHYs` chunk in `pnginfo`; it is written before IDAT. Combining it with `dpi` raises `ValueError`.
55
+
56
+ HDR `mDCV` (24 bytes) and `cLLI` (8 bytes) are accepted once each through `pnginfo` and written before PLTE and IDAT. `mDCV` requires `cICP`, in either input order.
57
+
58
+ ## Limitations and behavior
59
+
60
+ ### Formats and compatibility
61
+
62
+ Encoding supports single images in modes `1`, `L`, `I;16`, `P`, `RGB`, `LA`, and `RGBA`. APNG saving uses Pillow's encoder. Decoding supports Adam7 interlacing and APNG.
63
+
64
+ Supports CPython with Pillow major versions 11, 12, and 13. Unsupported versions raise an error when importing the plugin.
65
+
66
+ ### Image access and animation
67
+
68
+ Keep the image unchanged until `save()` returns. Serialize loading, seeking, and pixel access on the same image object.
69
+
70
+ APNG decoding streams frames on demand, reading frame data once during forward playback, including gzip streams. Initialization may reread large headers; rewinding or retrying a failed native decode rereads the stream. Keep the file open while frames are needed.
71
+
72
+ Pillow's animation limitations apply, including unsupported `I;16` blending with `OP_OVER`. Reopen the image after errors in Pillow metadata processing, frame transitions, or composition.
73
+
74
+ ### Damaged PNGs
75
+
76
+ With `PIL.ImageFile.LOAD_TRUNCATED_IMAGES = True`, decoding tolerates early EOF, missing rows, and damaged compressed data. Complete rows (including Adam7 pass rows) are retained; unrecovered pixels remain zero or retain the existing APNG canvas. CRC and Adler-32 checks are disabled, but Pillow still validates headers, metadata, and APNG frame controls and sequences.
77
+
78
+ Recovered pixels may differ from Pillow's zlib decoder. Rust's structural checks and static PNG memory limits can reject files Pillow accepts. For APNG, Rust's internal allocation budget is disabled; Pillow controls destination image allocation.
79
+
80
+ Without truncated loading, corrupt static PNG IDAT checksums or a missing chunk header after frame data cause errors that Pillow may tolerate during `load()`. APNG fdAT CRC errors are accepted, as in Pillow.
81
+
82
+ ## Building from source
83
+
84
+ A Rust toolchain and a C compiler are required. From the repository root:
85
+
86
+ ```sh
87
+ python -m pip install ./python # Install from the checkout.
88
+
89
+ # Build an sdist and wheel in python/dist/.
90
+ python -m pip install build
91
+ python -m build ./python
92
+ ```
@@ -0,0 +1,79 @@
1
+ # LastPNG for Pillow
2
+
3
+ LastPNG makes reading and saving PNG images in Pillow faster and optimizes file size by choosing the palette, bit depth, and color type automatically. Output remains standard PNG, preserving visible colors and transparency; RGB values in fully transparent pixels may change. Reading supports PNG and APNG, with Pillow handling metadata and animation composition.
4
+
5
+ ## Installation
6
+
7
+ Requires Python ≥3.10 and Pillow ≥11, ≤13.0.0.
8
+
9
+ ```sh
10
+ pip install LastPNGImagePlugin
11
+ ```
12
+
13
+ Wheels bundle the native libraries; no separate libdeflate or Windows VC Redistributable installation is needed.
14
+
15
+ ## Usage
16
+
17
+ ```python
18
+ from PIL import Image
19
+ import LastPNGImagePlugin
20
+
21
+ # Select LastPNG explicitly when saving.
22
+ with Image.open("input.png") as image:
23
+ image.save("output.png", format="LASTPNG", level=3)
24
+
25
+ # Use Rust decoding and LastPNG encoding by default throughout the process.
26
+ LastPNGImagePlugin.register_as_default()
27
+ with Image.open("input.png") as image:
28
+ image.save("output.png", level=3)
29
+ ```
30
+
31
+ Use `register_as_default(encoder=False)` to enable only Rust decoding and keep the current PNG encoder.
32
+
33
+ Choose a compression level from 1 (fastest) to 6 (experimental, highest effort). The default is 3.
34
+
35
+ ### Save options
36
+
37
+ Supports `pnginfo`, `icc_profile`, `transparency`, `dpi`, and `exif`. An ICC profile preserves the input color family.
38
+
39
+ In `pnginfo`, IHDR, PLTE, tRNS, IDAT, IEND, bKGD, hIST, sBIT, eXIf, and iCCP raise `ValueError`. LastPNG selects the output representation; use `exif=` for EXIF and `icc_profile=` for an uncompressed ICC profile.
40
+
41
+ For a unitless pixel aspect ratio or exact pixels-per-metre values, pass one `pHYs` chunk in `pnginfo`; it is written before IDAT. Combining it with `dpi` raises `ValueError`.
42
+
43
+ HDR `mDCV` (24 bytes) and `cLLI` (8 bytes) are accepted once each through `pnginfo` and written before PLTE and IDAT. `mDCV` requires `cICP`, in either input order.
44
+
45
+ ## Limitations and behavior
46
+
47
+ ### Formats and compatibility
48
+
49
+ Encoding supports single images in modes `1`, `L`, `I;16`, `P`, `RGB`, `LA`, and `RGBA`. APNG saving uses Pillow's encoder. Decoding supports Adam7 interlacing and APNG.
50
+
51
+ Supports CPython with Pillow major versions 11, 12, and 13. Unsupported versions raise an error when importing the plugin.
52
+
53
+ ### Image access and animation
54
+
55
+ Keep the image unchanged until `save()` returns. Serialize loading, seeking, and pixel access on the same image object.
56
+
57
+ APNG decoding streams frames on demand, reading frame data once during forward playback, including gzip streams. Initialization may reread large headers; rewinding or retrying a failed native decode rereads the stream. Keep the file open while frames are needed.
58
+
59
+ Pillow's animation limitations apply, including unsupported `I;16` blending with `OP_OVER`. Reopen the image after errors in Pillow metadata processing, frame transitions, or composition.
60
+
61
+ ### Damaged PNGs
62
+
63
+ With `PIL.ImageFile.LOAD_TRUNCATED_IMAGES = True`, decoding tolerates early EOF, missing rows, and damaged compressed data. Complete rows (including Adam7 pass rows) are retained; unrecovered pixels remain zero or retain the existing APNG canvas. CRC and Adler-32 checks are disabled, but Pillow still validates headers, metadata, and APNG frame controls and sequences.
64
+
65
+ Recovered pixels may differ from Pillow's zlib decoder. Rust's structural checks and static PNG memory limits can reject files Pillow accepts. For APNG, Rust's internal allocation budget is disabled; Pillow controls destination image allocation.
66
+
67
+ Without truncated loading, corrupt static PNG IDAT checksums or a missing chunk header after frame data cause errors that Pillow may tolerate during `load()`. APNG fdAT CRC errors are accepted, as in Pillow.
68
+
69
+ ## Building from source
70
+
71
+ A Rust toolchain and a C compiler are required. From the repository root:
72
+
73
+ ```sh
74
+ python -m pip install ./python # Install from the checkout.
75
+
76
+ # Build an sdist and wheel in python/dist/.
77
+ python -m pip install build
78
+ python -m build ./python
79
+ ```
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "LastPNGImagePlugin"
7
- version = "0.2.0"
7
+ version = "0.2.1"
8
8
  description = "A vibe-coded, blazingly fast PNG compressor for Pillow"
9
9
  readme = "README.md"
10
10
  license = "MIT"
@@ -16,9 +16,14 @@ from _lastpng._abi import ffi
16
16
 
17
17
  # Audited prefixes from src/libImaging/Imaging.h up to and including image.
18
18
  _LAYOUTS = {
19
- **dict.fromkeys(("11.0.0", "11.1.0", "11.2.1", "11.3.0"), "Imaging11 *"),
20
- **dict.fromkeys(("12.0.0", "12.1.0", "12.1.1", "12.2.0", "12.3.0", "13.0.0"), "Imaging12 *"),
19
+ 11: "Imaging11 *",
20
+ 12: "Imaging12 *",
21
+ 13: "Imaging12 *",
21
22
  }
23
+ _PILLOW_VERSION = tuple(map(int, PIL.__version__.split(".")[:3]))
24
+ _PILLOW_LAYOUT = _LAYOUTS.get(_PILLOW_VERSION[0]) if sys.implementation.name == "cpython" else None
25
+ if _PILLOW_LAYOUT is None:
26
+ raise OSError(f"unsupported Pillow ABI: {sys.implementation.name} / Pillow {PIL.__version__}")
22
27
 
23
28
 
24
29
  @lru_cache(maxsize=2)
@@ -164,7 +169,7 @@ class _PngDecoder(ImageFile.PyDecoder):
164
169
  def decode(self, buffer):
165
170
  allow_truncated = ImageFile.LOAD_TRUNCATED_IMAGES
166
171
  capsule = self.im.ptr
167
- raster = _raster(capsule, _LAYOUTS[PIL.__version__], self.im.size)
172
+ raster = _raster(capsule, _PILLOW_LAYOUT, self.im.size)
168
173
  pixel_bytes = {"1": 1, "P": 1, "L": 1, "I;16": 2, "RGB": 4, "RGBA": 4, "LA": 4}[self.im.mode]
169
174
  rows = ffi.cast("uint8_t *const *", raster.image) + self.state.yoff
170
175
  if self.state.xoff:
@@ -210,8 +215,7 @@ class _PngImageFile(PngImagePlugin.PngImageFile):
210
215
  return result
211
216
 
212
217
  def _open(self):
213
- if sys.implementation.name == "cpython" and PIL.__version__ in _LAYOUTS:
214
- self.fp = _SharedInput(self.fp)
218
+ self.fp = _SharedInput(self.fp)
215
219
  super()._open()
216
220
  if self.png.im_n_frames is None:
217
221
  self._unbuffer()
@@ -277,50 +281,49 @@ class _PngImageFile(PngImagePlugin.PngImageFile):
277
281
 
278
282
  def load_prepare(self):
279
283
  super().load_prepare()
280
- if sys.implementation.name == "cpython" and PIL.__version__ in _LAYOUTS:
281
- args = (None,)
282
- if self.png.im_n_frames is not None:
283
- allow_truncated = ImageFile.LOAD_TRUNCATED_IMAGES
284
- state = getattr(self, "_lastpng_reader", None)
285
- if state is None or state[0] is None or state[1] != allow_truncated:
286
- fp = self.fp
287
- fp.seek(self.tile[0][2])
288
- fp.rust_position = 0
289
- errors = []
290
-
291
- @ffi.callback("int64_t(int64_t, int, uint8_t *, size_t)", error=-1)
292
- def stream_io(offset, whence, buffer, length):
293
- try:
294
- if buffer == ffi.NULL:
295
- fp.fp.seek(offset, whence)
296
- return fp.fp.tell()
297
- data = fp.read_at(offset, length)
298
- fp.rust_position = offset + len(data)
299
- ffi.buffer(buffer, length)[:len(data)] = data
300
- fp.discard()
301
- return len(data)
302
- except BaseException as error:
303
- errors.append(error)
304
- return -1
305
-
306
- library = _library("lastpng_decoder")
307
- error = ffi.new("char[256]")
308
- reader = library.lastpng_apng_new(stream_io, self.tell(), allow_truncated, error)
309
- if reader != ffi.NULL:
310
- # Keep the callback and its file alive until the Reader is destroyed.
311
- reader = ffi.gc(reader, lambda ptr, stream_io=stream_io: library.lastpng_apng_free(ptr))
312
- if errors:
313
- raise errors.pop()
314
- if reader == ffi.NULL:
315
- raise OSError(ffi.string(error).decode(errors="replace"))
316
- state = self._lastpng_reader = [reader, allow_truncated, errors]
317
- # Pillow has already read the chunk header and any fdAT sequence number.
318
- args = (self.png, state, self.tell(), self._PngImageFile__idat)
319
- self.tile = [self.tile[0]._replace(
320
- codec_name="lastpng_png",
321
- args=args,
322
- )]
323
- self._PngImageFile__idat = 0
284
+ args = (None,)
285
+ if self.png.im_n_frames is not None:
286
+ allow_truncated = ImageFile.LOAD_TRUNCATED_IMAGES
287
+ state = getattr(self, "_lastpng_reader", None)
288
+ if state is None or state[0] is None or state[1] != allow_truncated:
289
+ fp = self.fp
290
+ fp.seek(self.tile[0][2])
291
+ fp.rust_position = 0
292
+ errors = []
293
+
294
+ @ffi.callback("int64_t(int64_t, int, uint8_t *, size_t)", error=-1)
295
+ def stream_io(offset, whence, buffer, length):
296
+ try:
297
+ if buffer == ffi.NULL:
298
+ fp.fp.seek(offset, whence)
299
+ return fp.fp.tell()
300
+ data = fp.read_at(offset, length)
301
+ fp.rust_position = offset + len(data)
302
+ ffi.buffer(buffer, length)[:len(data)] = data
303
+ fp.discard()
304
+ return len(data)
305
+ except BaseException as error:
306
+ errors.append(error)
307
+ return -1
308
+
309
+ library = _library("lastpng_decoder")
310
+ error = ffi.new("char[256]")
311
+ reader = library.lastpng_apng_new(stream_io, self.tell(), allow_truncated, error)
312
+ if reader != ffi.NULL:
313
+ # Keep the callback and its file alive until the Reader is destroyed.
314
+ reader = ffi.gc(reader, lambda ptr, stream_io=stream_io: library.lastpng_apng_free(ptr))
315
+ if errors:
316
+ raise errors.pop()
317
+ if reader == ffi.NULL:
318
+ raise OSError(ffi.string(error).decode(errors="replace"))
319
+ state = self._lastpng_reader = [reader, allow_truncated, errors]
320
+ # Pillow has already read the chunk header and any fdAT sequence number.
321
+ args = (self.png, state, self.tell(), self._PngImageFile__idat)
322
+ self.tile = [self.tile[0]._replace(
323
+ codec_name="lastpng_png",
324
+ args=args,
325
+ )]
326
+ self._PngImageFile__idat = 0
324
327
 
325
328
 
326
329
  def _metadata(im, icc):
@@ -398,9 +401,7 @@ def _palette_and_transparency(im):
398
401
 
399
402
 
400
403
  def save(im, fp, filename):
401
- layout = _LAYOUTS.get(PIL.__version__)
402
- if sys.implementation.name != "cpython" or layout is None:
403
- raise OSError(f"unsupported Pillow ABI: {sys.implementation.name} / Pillow {PIL.__version__}")
404
+ layout = _PILLOW_LAYOUT
404
405
  lib = _library()
405
406
  formats = {
406
407
  "RGB": (lib.LASTPNG_RGB, 8, lib.LASTPNG_RGBX),
@@ -470,7 +471,12 @@ def save(im, fp, filename):
470
471
  lib.lastpng_encoder_free(handle[0])
471
472
 
472
473
 
474
+ def save_all(im, fp, filename):
475
+ raise NotImplementedError("LastPNG animation encoding is not implemented yet; use format='PNG' to save with Pillow")
476
+
477
+
473
478
  Image.register_save("LASTPNG", save)
479
+ Image.register_save_all("LASTPNG", save_all)
474
480
 
475
481
 
476
482
  def register_as_default(encoder=True):
@@ -1,10 +1,11 @@
1
1
  import gzip
2
+ import importlib.util
2
3
  import io
3
4
  import random
4
5
  import struct
5
6
  import tracemalloc
6
7
  import zlib
7
- from unittest.mock import Mock, patch
8
+ from unittest.mock import Mock, call, patch
8
9
 
9
10
  import PIL
10
11
  import pytest
@@ -39,6 +40,27 @@ def test_register_as_default_optionally_enables_png_saves(tmp_path):
39
40
  assert decoded.tobytes() == source.tobytes()
40
41
 
41
42
 
43
+ def test_lastpng_rejects_animation_saves():
44
+ frames = [Image.new("RGB", (3, 2), color) for color in ("red", "blue")]
45
+ with pytest.raises(NotImplementedError, match="LastPNG animation encoding is not implemented yet"):
46
+ frames[0].save(io.BytesIO(), format="LASTPNG", save_all=True, append_images=frames[1:])
47
+
48
+
49
+ def test_default_png_animation_saves_use_pillow():
50
+ frames = [Image.new("RGB", (3, 2), color) for color in ("red", "blue")]
51
+ with patch.dict(Image.OPEN), patch.dict(Image.DECODERS), patch.dict(Image.SAVE):
52
+ LastPNGImagePlugin.register_as_default()
53
+ fp = io.BytesIO()
54
+ with patch.object(LastPNGImagePlugin, "_library", side_effect=AssertionError("unexpected native encoding")):
55
+ frames[0].save(fp, format="PNG", save_all=True, append_images=frames[1:])
56
+ fp.seek(0)
57
+ with PngImagePlugin.PngImageFile(fp) as decoded:
58
+ assert decoded.n_frames == len(frames)
59
+ for index, frame in enumerate(frames):
60
+ decoded.seek(index)
61
+ assert decoded.tobytes() == frame.tobytes()
62
+
63
+
42
64
  @pytest.mark.parametrize("allow_truncated", [False, True])
43
65
  def test_static_png_uses_rust_with_either_truncated_loading_setting(rust_decoder, monkeypatch, allow_truncated):
44
66
  source = Image.new("RGB", (3, 2), (12, 34, 56))
@@ -788,11 +810,52 @@ def test_grayscale_sample_depth(mode, level):
788
810
  assert result.tobytes() == source.tobytes()
789
811
 
790
812
 
791
- def test_version_gate_before_pointer_access(monkeypatch):
792
- monkeypatch.setattr(PIL, "__version__", "13.0.1")
793
- with patch.object(Image.Image, "getim", side_effect=AssertionError):
794
- with pytest.raises(OSError, match="unsupported Pillow ABI"):
795
- encode(Image.new("RGB", (1, 1)))
813
+ @pytest.fixture
814
+ def plugin_at_version(monkeypatch):
815
+ def load(version):
816
+ monkeypatch.setattr(PIL, "__version__", version)
817
+ spec = importlib.util.spec_from_file_location("lastpng_version_test", LastPNGImagePlugin.__file__)
818
+ plugin = importlib.util.module_from_spec(spec)
819
+ spec.loader.exec_module(plugin)
820
+ return plugin
821
+
822
+ with patch.dict(Image.OPEN), patch.dict(Image.DECODERS), patch.dict(Image.SAVE), patch.dict(Image.SAVE_ALL):
823
+ yield load
824
+
825
+
826
+ @pytest.mark.parametrize("suffix", [".post0", ".post3", ".dev0"])
827
+ def test_version_suffixes_use_native_encoding_and_decoding(plugin_at_version, suffix):
828
+ plugin = plugin_at_version(PIL.__version__ + suffix)
829
+ plugin.register_as_default(encoder=False)
830
+ source = Image.new("RGB", (3, 2), (12, 34, 56))
831
+ fp = io.BytesIO()
832
+ with patch.object(plugin, "_library", wraps=plugin._library) as library:
833
+ source.save(fp, format="LASTPNG")
834
+ fp.seek(0)
835
+ with Image.open(fp) as decoded:
836
+ assert decoded.tobytes() == source.tobytes()
837
+ assert library.call_args_list == [call(), call("lastpng_decoder")]
838
+
839
+
840
+ @pytest.mark.parametrize(("version", "layout"), [
841
+ ("11.99.7", "Imaging11 *"),
842
+ ("12.99.7.post0", "Imaging12 *"),
843
+ ("13.0.1", "Imaging12 *"),
844
+ ])
845
+ def test_supported_pillow_major_versions_import(plugin_at_version, version, layout):
846
+ assert plugin_at_version(version)._PILLOW_LAYOUT == layout
847
+
848
+
849
+ @pytest.mark.parametrize("version", ["10.9.9", "14.0.0", "14.0.0.post0"])
850
+ def test_unsupported_pillow_version_rejected_on_import(plugin_at_version, version):
851
+ with pytest.raises(OSError, match="unsupported Pillow ABI"):
852
+ plugin_at_version(version)
853
+
854
+
855
+ @pytest.mark.parametrize("version", ["13.0.0rc1", "13.0.0+custom"])
856
+ def test_nonnumeric_version_components_rejected_on_import(plugin_at_version, version):
857
+ with pytest.raises(ValueError):
858
+ plugin_at_version(version)
796
859
 
797
860
 
798
861
  def test_metadata_and_icc_family():
@@ -1,148 +0,0 @@
1
- Metadata-Version: 2.5
2
- Name: LastPNGImagePlugin
3
- Version: 0.2.0
4
- Summary: A vibe-coded, blazingly fast PNG compressor for Pillow
5
- License-Expression: MIT
6
- License-File: LICENSE
7
- License-File: licenses/fdeflate-LICENSE-MIT
8
- License-File: licenses/libdeflate-COPYING
9
- Requires-Python: >=3.10
10
- Requires-Dist: cffi>=1.17
11
- Requires-Dist: pillow<=13.0.0,>=11
12
- Description-Content-Type: text/markdown
13
-
14
- # LastPNG for Pillow
15
-
16
- LastPNG adds an alternative PNG encoder and decoder to Pillow: LastPNG compression
17
- for saving images and the Rust `png` decoder for reading PNG and APNG files.
18
- Use it through the usual Pillow API, either selecting LastPNG when saving or
19
- registering it as the default PNG handler. Pillow continues to handle palettes,
20
- metadata, and animation composition.
21
-
22
- ## Installation
23
-
24
- Requires Python 3.10 or newer and Pillow 11 through 13.0.0. See the compatibility
25
- details below for the Pillow versions supported by the native decoder.
26
-
27
- ```sh
28
- pip install LastPNGImagePlugin
29
- ```
30
-
31
- Platform wheels include both native libraries and require no separate installation
32
- of libdeflate or the Windows VC Redistributable.
33
-
34
- ## Usage
35
-
36
- ```python
37
- from PIL import Image
38
- import LastPNGImagePlugin
39
-
40
- # Select LastPNG explicitly when saving.
41
- with Image.open("input.png") as image:
42
- image.save("output.png", format="LASTPNG", level=3)
43
-
44
- # Use Rust decoding and LastPNG encoding by default throughout the process.
45
- LastPNGImagePlugin.register_as_default()
46
- with Image.open("input.png") as image:
47
- image.save("output.png", level=3)
48
- ```
49
-
50
- To enable only Rust decoding, use this initialization instead:
51
-
52
- ```python
53
- import LastPNGImagePlugin
54
-
55
- # Enable Rust decoding and keep the current PNG encoder.
56
- LastPNGImagePlugin.register_as_default(encoder=False)
57
- ```
58
-
59
- Choose a compression level from 1 (fastest) to 6 (experimental, highest effort).
60
- The default is 3.
61
-
62
- ### Save options
63
-
64
- Use `pnginfo` for text and ancillary chunks, and the usual `icc_profile`,
65
- `transparency`, `dpi`, and `exif` save options. When an ICC profile is supplied,
66
- LastPNG preserves the input color family.
67
-
68
- The plugin rejects IHDR, PLTE, tRNS, IDAT, IEND, bKGD, hIST, and sBIT in `pnginfo`,
69
- since LastPNG selects the output representation. Raw `eXIf` and `iCCP` chunks in
70
- `pnginfo` raise `ValueError`. Pass EXIF data with `exif=` and the uncompressed ICC
71
- profile with `icc_profile=`.
72
-
73
- To preserve a unitless pixel aspect ratio or exact pixels-per-metre values, pass a
74
- single `pHYs` chunk in `pnginfo`. It is written before IDAT. Supplying both `pHYs`
75
- and `dpi` raises `ValueError`.
76
-
77
- HDR `mDCV` and `cLLI` chunks supplied through `pnginfo` are preserved before PLTE
78
- and IDAT. Each is accepted once, with payload lengths of 24 and 8 bytes respectively.
79
- An `mDCV` chunk requires an accompanying `cICP` chunk, in either input order.
80
-
81
- ## Limitations and behavior
82
-
83
- ### Formats and compatibility
84
-
85
- The encoder saves single images in modes `1`, `L`, `I;16`, `P`, `RGB`, `LA`, and
86
- `RGBA`. The decoder reads static PNGs, Adam7 interlaced images, and APNG frames.
87
-
88
- On CPython, the plugin supports Pillow versions 11.0.0, 11.1.0, 11.2.1, 11.3.0,
89
- 12.0.0, 12.1.0, 12.1.1, 12.2.0, 12.3.0, and 13.0.0. Pillow ABIs outside this list
90
- use Pillow's built-in decoder.
91
-
92
- ### Image access and animation
93
-
94
- The plugin reads pixel rows directly, so keep the image unchanged until `save()`
95
- returns. Serialize loading, seeking, and pixel access on the same image object.
96
-
97
- APNG frames are decoded on demand without reading the whole animation into memory
98
- or scanning ahead for IEND or EOF. Forward playback reads frame data once, including
99
- gzip streams; large headers can be reread during decoder initialization. Rewinding
100
- or retrying a native decode after an error rereads the stream. Keep the file open
101
- while more frames are needed. Verification uses the original stream directly.
102
-
103
- Pillow handles animation timing, seeking, blending, and disposal. Its compositor
104
- limitations still apply, including unsupported `I;16` frame blending with `OP_OVER`.
105
- If Pillow raises while processing metadata, transitioning between frames, or
106
- composing a frame, subsequent loading and pixel access require reopening the image.
107
-
108
- ### Damaged PNGs
109
-
110
- With `PIL.ImageFile.LOAD_TRUNCATED_IMAGES = True`, the Rust decoder accepts early
111
- EOF, missing pixel rows and damaged compressed image data. It retains complete
112
- decoded rows, including Adam7 pass rows. Unrecovered pixels retain their initial
113
- contents: zeroes for new images, or the existing canvas for APNG frame rectangles.
114
- CRC and Adler-32 validation are disabled in this mode. Pillow still parses the
115
- headers, metadata, and APNG frame controls, including frame sequence validation.
116
-
117
- Recovery can differ from Pillow's zlib decoder. The two decompressors can recover
118
- different numbers of rows from an incomplete DEFLATE stream and can stop at
119
- different positions after a corrupt byte. Consequently, the pixels recovered from
120
- a damaged stream can differ. Rust's structural checks before image decoding and
121
- its working-memory limits for static PNGs still apply and can reject inputs
122
- accepted by Pillow. APNG decoding disables Rust png's internal allocation budget:
123
- version 0.18.1 incorrectly charges it cumulatively across frames. Pillow still
124
- controls the destination image allocation.
125
- With truncated loading disabled, Rust reports corrupt static PNG IDAT checksums
126
- and the plugin requires a readable chunk header after frame data; Pillow can
127
- accept some of these files during `load()`. APNG fdAT CRC errors are accepted by
128
- Rust png's default ancillary-chunk policy, as they are by Pillow's decoder.
129
-
130
- ## Building from source
131
-
132
- A Rust toolchain and a C compiler are required. Run these commands from the
133
- repository root.
134
-
135
- To install directly from the checkout:
136
-
137
- ```sh
138
- python -m pip install ./python
139
- ```
140
-
141
- To build a source distribution and a wheel:
142
-
143
- ```sh
144
- python -m pip install build
145
- python -m build ./python
146
- ```
147
-
148
- The packages are written to `python/dist/`.
@@ -1,135 +0,0 @@
1
- # LastPNG for Pillow
2
-
3
- LastPNG adds an alternative PNG encoder and decoder to Pillow: LastPNG compression
4
- for saving images and the Rust `png` decoder for reading PNG and APNG files.
5
- Use it through the usual Pillow API, either selecting LastPNG when saving or
6
- registering it as the default PNG handler. Pillow continues to handle palettes,
7
- metadata, and animation composition.
8
-
9
- ## Installation
10
-
11
- Requires Python 3.10 or newer and Pillow 11 through 13.0.0. See the compatibility
12
- details below for the Pillow versions supported by the native decoder.
13
-
14
- ```sh
15
- pip install LastPNGImagePlugin
16
- ```
17
-
18
- Platform wheels include both native libraries and require no separate installation
19
- of libdeflate or the Windows VC Redistributable.
20
-
21
- ## Usage
22
-
23
- ```python
24
- from PIL import Image
25
- import LastPNGImagePlugin
26
-
27
- # Select LastPNG explicitly when saving.
28
- with Image.open("input.png") as image:
29
- image.save("output.png", format="LASTPNG", level=3)
30
-
31
- # Use Rust decoding and LastPNG encoding by default throughout the process.
32
- LastPNGImagePlugin.register_as_default()
33
- with Image.open("input.png") as image:
34
- image.save("output.png", level=3)
35
- ```
36
-
37
- To enable only Rust decoding, use this initialization instead:
38
-
39
- ```python
40
- import LastPNGImagePlugin
41
-
42
- # Enable Rust decoding and keep the current PNG encoder.
43
- LastPNGImagePlugin.register_as_default(encoder=False)
44
- ```
45
-
46
- Choose a compression level from 1 (fastest) to 6 (experimental, highest effort).
47
- The default is 3.
48
-
49
- ### Save options
50
-
51
- Use `pnginfo` for text and ancillary chunks, and the usual `icc_profile`,
52
- `transparency`, `dpi`, and `exif` save options. When an ICC profile is supplied,
53
- LastPNG preserves the input color family.
54
-
55
- The plugin rejects IHDR, PLTE, tRNS, IDAT, IEND, bKGD, hIST, and sBIT in `pnginfo`,
56
- since LastPNG selects the output representation. Raw `eXIf` and `iCCP` chunks in
57
- `pnginfo` raise `ValueError`. Pass EXIF data with `exif=` and the uncompressed ICC
58
- profile with `icc_profile=`.
59
-
60
- To preserve a unitless pixel aspect ratio or exact pixels-per-metre values, pass a
61
- single `pHYs` chunk in `pnginfo`. It is written before IDAT. Supplying both `pHYs`
62
- and `dpi` raises `ValueError`.
63
-
64
- HDR `mDCV` and `cLLI` chunks supplied through `pnginfo` are preserved before PLTE
65
- and IDAT. Each is accepted once, with payload lengths of 24 and 8 bytes respectively.
66
- An `mDCV` chunk requires an accompanying `cICP` chunk, in either input order.
67
-
68
- ## Limitations and behavior
69
-
70
- ### Formats and compatibility
71
-
72
- The encoder saves single images in modes `1`, `L`, `I;16`, `P`, `RGB`, `LA`, and
73
- `RGBA`. The decoder reads static PNGs, Adam7 interlaced images, and APNG frames.
74
-
75
- On CPython, the plugin supports Pillow versions 11.0.0, 11.1.0, 11.2.1, 11.3.0,
76
- 12.0.0, 12.1.0, 12.1.1, 12.2.0, 12.3.0, and 13.0.0. Pillow ABIs outside this list
77
- use Pillow's built-in decoder.
78
-
79
- ### Image access and animation
80
-
81
- The plugin reads pixel rows directly, so keep the image unchanged until `save()`
82
- returns. Serialize loading, seeking, and pixel access on the same image object.
83
-
84
- APNG frames are decoded on demand without reading the whole animation into memory
85
- or scanning ahead for IEND or EOF. Forward playback reads frame data once, including
86
- gzip streams; large headers can be reread during decoder initialization. Rewinding
87
- or retrying a native decode after an error rereads the stream. Keep the file open
88
- while more frames are needed. Verification uses the original stream directly.
89
-
90
- Pillow handles animation timing, seeking, blending, and disposal. Its compositor
91
- limitations still apply, including unsupported `I;16` frame blending with `OP_OVER`.
92
- If Pillow raises while processing metadata, transitioning between frames, or
93
- composing a frame, subsequent loading and pixel access require reopening the image.
94
-
95
- ### Damaged PNGs
96
-
97
- With `PIL.ImageFile.LOAD_TRUNCATED_IMAGES = True`, the Rust decoder accepts early
98
- EOF, missing pixel rows and damaged compressed image data. It retains complete
99
- decoded rows, including Adam7 pass rows. Unrecovered pixels retain their initial
100
- contents: zeroes for new images, or the existing canvas for APNG frame rectangles.
101
- CRC and Adler-32 validation are disabled in this mode. Pillow still parses the
102
- headers, metadata, and APNG frame controls, including frame sequence validation.
103
-
104
- Recovery can differ from Pillow's zlib decoder. The two decompressors can recover
105
- different numbers of rows from an incomplete DEFLATE stream and can stop at
106
- different positions after a corrupt byte. Consequently, the pixels recovered from
107
- a damaged stream can differ. Rust's structural checks before image decoding and
108
- its working-memory limits for static PNGs still apply and can reject inputs
109
- accepted by Pillow. APNG decoding disables Rust png's internal allocation budget:
110
- version 0.18.1 incorrectly charges it cumulatively across frames. Pillow still
111
- controls the destination image allocation.
112
- With truncated loading disabled, Rust reports corrupt static PNG IDAT checksums
113
- and the plugin requires a readable chunk header after frame data; Pillow can
114
- accept some of these files during `load()`. APNG fdAT CRC errors are accepted by
115
- Rust png's default ancillary-chunk policy, as they are by Pillow's decoder.
116
-
117
- ## Building from source
118
-
119
- A Rust toolchain and a C compiler are required. Run these commands from the
120
- repository root.
121
-
122
- To install directly from the checkout:
123
-
124
- ```sh
125
- python -m pip install ./python
126
- ```
127
-
128
- To build a source distribution and a wheel:
129
-
130
- ```sh
131
- python -m pip install build
132
- python -m build ./python
133
- ```
134
-
135
- The packages are written to `python/dist/`.