LastPNGImagePlugin 0.2.0__py3-none-win_amd64.whl

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.
LastPNGImagePlugin.py ADDED
@@ -0,0 +1,481 @@
1
+ """Import for LASTPNG saves. Call register_as_default() to use the Rust PNG decoder."""
2
+
3
+ import ctypes
4
+ import struct
5
+ import sys
6
+ import zlib
7
+ from functools import lru_cache
8
+ from pathlib import Path
9
+
10
+ import PIL
11
+ from PIL import Image, ImageFile, PngImagePlugin
12
+
13
+ from _lastpng import _abi
14
+ from _lastpng._abi import ffi
15
+
16
+
17
+ # Audited prefixes from src/libImaging/Imaging.h up to and including image.
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 *"),
21
+ }
22
+
23
+
24
+ @lru_cache(maxsize=2)
25
+ def _library(stem="lastpng"):
26
+ name = {"darwin": f"lib{stem}.dylib", "win32": f"{stem}.dll"}.get(sys.platform, f"lib{stem}.so")
27
+ flags = 0 if sys.platform == "win32" else ffi.RTLD_NOW | ffi.RTLD_LOCAL
28
+ return ffi.dlopen(str(Path(_abi.__file__).with_name(name)), flags)
29
+
30
+
31
+ def _raster(capsule, layout, size):
32
+ get_pointer = ctypes.pythonapi.PyCapsule_GetPointer
33
+ get_pointer.argtypes = (ctypes.py_object, ctypes.c_char_p)
34
+ get_pointer.restype = ctypes.c_void_p
35
+ raster = ffi.cast(layout, get_pointer(capsule, b"Pillow Imaging"))
36
+ if (raster.xsize, raster.ysize) != size or raster.image == ffi.NULL:
37
+ raise OSError("unexpected Pillow raster layout")
38
+ return raster
39
+
40
+
41
+ class _SharedInput:
42
+ """Keep bytes until both Pillow and Rust have passed them."""
43
+
44
+ def __init__(self, fp):
45
+ self.fp = fp
46
+ self.position = self.start = fp.tell()
47
+ self.data = bytearray()
48
+ self.rust_position = None
49
+
50
+ def tell(self):
51
+ return self.position
52
+
53
+ def seek(self, offset, whence=0):
54
+ if whence == 0:
55
+ position = offset
56
+ elif whence == 1:
57
+ position = self.position + offset
58
+ elif whence == 2:
59
+ position = self.fp.seek(offset, whence)
60
+ else:
61
+ raise ValueError("invalid whence")
62
+ if position < 0:
63
+ raise ValueError("negative seek position")
64
+ self.position = position
65
+ return position
66
+
67
+ def read(self, size=-1):
68
+ data = self.read_at(self.position, size)
69
+ self.position += len(data)
70
+ # Retain a small header for animation detection, not all raw metadata.
71
+ if self.rust_position is None and len(self.data) > 8192:
72
+ self.discard()
73
+ return data
74
+
75
+ def read_at(self, position, size):
76
+ if position < self.start:
77
+ self.fp.seek(position)
78
+ self.start = position
79
+ self.data.clear()
80
+ end = self.start + len(self.data)
81
+ target = position + size
82
+ while size < 0 or end < target:
83
+ if self.fp.tell() != end:
84
+ self.fp.seek(end)
85
+ chunk = self.fp.read(ImageFile.SAFEBLOCK if size < 0 else min(target - end, ImageFile.SAFEBLOCK))
86
+ if not chunk:
87
+ break
88
+ self.data.extend(chunk)
89
+ end += len(chunk)
90
+ begin = position - self.start
91
+ return bytes(self.data[begin:] if size < 0 else self.data[begin:begin + size])
92
+
93
+ def discard(self):
94
+ position = (self.position if self.rust_position is None else
95
+ min(self.position, self.rust_position))
96
+ # Reclaim in batches so copying the remaining bytes stays linear.
97
+ if position - self.start >= len(self.data) // 2:
98
+ del self.data[:position - self.start]
99
+ self.start = position
100
+
101
+ def close(self):
102
+ self.data.clear()
103
+ self.fp.close()
104
+
105
+
106
+ class _PngDecoder(ImageFile.PyDecoder):
107
+ _pulls_fd = True
108
+
109
+ def _static_png(self, allow_truncated):
110
+ # Bound the input at the next chunk header after the IDAT sequence.
111
+ fp = self.fd
112
+ fp.seek(-8, 1)
113
+ length, name = struct.unpack(">I4s", ImageFile._safe_read(fp, 8))
114
+ if name != b"IDAT":
115
+ raise OSError("missing PNG image data")
116
+ while name == b"IDAT":
117
+ fp.seek(length + 4, 1)
118
+ header = fp.read(8)
119
+ if len(header) < 8:
120
+ if not allow_truncated:
121
+ raise OSError("Truncated File Read")
122
+ break
123
+ length, name = struct.unpack(">I4s", header)
124
+ end = fp.tell()
125
+ if allow_truncated:
126
+ fp.seek(0, 2)
127
+ end = min(end, fp.tell())
128
+ fp.seek(0)
129
+ data = fp.read(end) if allow_truncated else ImageFile._safe_read(fp, end)
130
+ # Pillow's load_end starts at the final IDAT CRC and reads trailing metadata.
131
+ fp.seek(end - 12 if len(header) == 8 else end)
132
+ return data
133
+
134
+ def _skip_apng_frame(self, length, allow_truncated):
135
+ fp = self.fd
136
+ png = self.args[0]
137
+ while True:
138
+ if allow_truncated:
139
+ remaining = length + 4
140
+ while remaining:
141
+ chunk = fp.read(min(remaining, ImageFile.SAFEBLOCK))
142
+ if not chunk:
143
+ return
144
+ remaining -= len(chunk)
145
+ else:
146
+ fp.seek(length + 4, 1)
147
+ next_header = fp.read(8)
148
+ if len(next_header) < 8:
149
+ if not allow_truncated:
150
+ raise OSError("Truncated File Read")
151
+ break
152
+ length, name = struct.unpack(">I4s", next_header)
153
+ if name not in (b"IDAT", b"fdAT"):
154
+ fp.seek(-12, 1)
155
+ break
156
+ if name == b"fdAT":
157
+ # Keep Pillow's APNG sequence validation in sync across chunks.
158
+ try:
159
+ png.call(name, fp.tell(), length)
160
+ except EOFError:
161
+ pass
162
+ length -= 4
163
+
164
+ def decode(self, buffer):
165
+ allow_truncated = ImageFile.LOAD_TRUNCATED_IMAGES
166
+ capsule = self.im.ptr
167
+ raster = _raster(capsule, _LAYOUTS[PIL.__version__], self.im.size)
168
+ pixel_bytes = {"1": 1, "P": 1, "L": 1, "I;16": 2, "RGB": 4, "RGBA": 4, "LA": 4}[self.im.mode]
169
+ rows = ffi.cast("uint8_t *const *", raster.image) + self.state.yoff
170
+ if self.state.xoff:
171
+ rows = ffi.new("uint8_t *[]", [
172
+ rows[y] + self.state.xoff * pixel_bytes for y in range(self.state.ysize)
173
+ ])
174
+ error = ffi.new("char[256]")
175
+ library = _library("lastpng_decoder")
176
+ png = self.args[0]
177
+ sequence = png._seq_num if png is not None else None
178
+ try:
179
+ if png is not None:
180
+ self._skip_apng_frame(self.args[3], allow_truncated)
181
+ result = library.lastpng_apng_pillow_rows(
182
+ self.args[1][0], self.args[2], rows, self.state.xsize, self.state.ysize,
183
+ self.state.xsize * pixel_bytes, error,
184
+ )
185
+ if self.args[1][2]:
186
+ raise self.args[1][2].pop()
187
+ else:
188
+ data = self._static_png(allow_truncated)
189
+ result = library.lastpng_decode_pillow_rows(
190
+ data, len(data), rows, self.state.xsize, self.state.ysize,
191
+ self.state.xsize * pixel_bytes, allow_truncated, error,
192
+ )
193
+ if result:
194
+ raise OSError(ffi.string(error).decode(errors="replace"))
195
+ return -1, 0
196
+ except BaseException:
197
+ if png is not None:
198
+ png._seq_num = sequence
199
+ self.args[1][0] = None
200
+ raise
201
+
202
+
203
+ class _PngImageFile(PngImagePlugin.PngImageFile):
204
+ def load(self):
205
+ if getattr(self, "_lastpng_metadata_failed", False):
206
+ raise OSError("PNG metadata loading failed; reopen the image")
207
+ result = super().load()
208
+ if getattr(self, "_lastpng_seek_loaded", None) is False:
209
+ self._lastpng_seek_loaded = True
210
+ return result
211
+
212
+ def _open(self):
213
+ if sys.implementation.name == "cpython" and PIL.__version__ in _LAYOUTS:
214
+ self.fp = _SharedInput(self.fp)
215
+ super()._open()
216
+ if self.png.im_n_frames is None:
217
+ self._unbuffer()
218
+
219
+ def _unbuffer(self):
220
+ if isinstance(self.fp, _SharedInput):
221
+ shared = self.fp
222
+ if shared.fp.tell() != shared.tell():
223
+ shared.fp.seek(shared.tell())
224
+ self.fp = self._fp = self.png.fp = shared.fp
225
+
226
+ def verify(self):
227
+ # Verification has only one reader and does not need replay storage.
228
+ self._unbuffer()
229
+ super().verify()
230
+
231
+ def load_end(self):
232
+ if isinstance(self.fp, _SharedInput) and self.tell() == self.n_frames - 1:
233
+ self._release_reader()
234
+ self.fp.rust_position = None
235
+ try:
236
+ super().load_end()
237
+ except BaseException:
238
+ self._fail_metadata()
239
+ raise
240
+ if isinstance(self.fp, _SharedInput):
241
+ self.fp.discard()
242
+
243
+ def _seek(self, frame, rewind=False):
244
+ if rewind:
245
+ self._release_reader()
246
+ # Pillow loads the previous frame before modifying it for the transition.
247
+ self._lastpng_seek_loaded = False
248
+ try:
249
+ super()._seek(frame, rewind)
250
+ except BaseException:
251
+ if self._lastpng_seek_loaded:
252
+ self._fail_metadata()
253
+ raise
254
+ finally:
255
+ del self._lastpng_seek_loaded
256
+ if rewind:
257
+ self.png.queue.clear()
258
+
259
+ def _fail_metadata(self):
260
+ self._lastpng_metadata_failed = True
261
+ self._release_reader()
262
+ if isinstance(self._fp, _SharedInput):
263
+ self._fp.data.clear()
264
+
265
+ def _release_reader(self):
266
+ state = getattr(self, "_lastpng_reader", None)
267
+ if state is not None:
268
+ state[0] = None
269
+ self._lastpng_reader = None
270
+
271
+ def _close_fp(self):
272
+ self._release_reader()
273
+ # Release handles while preserving the pending tile of an unloaded frame.
274
+ self.tile = [tile._replace(args=(None,)) if tile.codec_name == "lastpng_png" else tile
275
+ for tile in self.tile]
276
+ super()._close_fp()
277
+
278
+ def load_prepare(self):
279
+ 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
324
+
325
+
326
+ def _metadata(im, icc):
327
+ before, after = [], []
328
+ single = {b"cHRM", b"cICP", b"gAMA", b"tIME", b"sRGB", b"pHYs", b"mDCV", b"cLLI"}
329
+ dpi = im.encoderinfo.get("dpi")
330
+ if icc:
331
+ before.append((b"iCCP", b"ICC Profile\0\0" + zlib.compress(icc)))
332
+ single.remove(b"sRGB")
333
+ info = im.encoderinfo.get("pnginfo")
334
+ for chunk in info.chunks if info is not None else ():
335
+ name, data = chunk[:2]
336
+ if name == b"eXIf":
337
+ raise ValueError("eXIf in pnginfo: pass EXIF data with exif=")
338
+ if name == b"iCCP":
339
+ raise ValueError("iCCP in pnginfo: pass the uncompressed ICC profile with icc_profile=")
340
+ if name in {b"IHDR", b"PLTE", b"tRNS", b"IDAT", b"IEND", b"bKGD", b"hIST", b"sBIT"}:
341
+ raise ValueError(f"LASTPNG cannot accept {name!r} in pnginfo")
342
+ if name in {b"mDCV", b"cLLI"}:
343
+ size = 24 if name == b"mDCV" else 8
344
+ if name not in single or len(data) != size:
345
+ raise ValueError(f"supply one {name.decode()} chunk containing {size} bytes")
346
+ if name == b"pHYs":
347
+ if dpi or name not in single:
348
+ raise ValueError("supply only one pHYs chunk or dpi")
349
+ if len(data) != 9:
350
+ raise ValueError("pHYs must contain 9 bytes")
351
+ x, y, unit = struct.unpack(">IIB", data)
352
+ if max(x, y) > 0x7fffffff or unit not in (0, 1):
353
+ raise ValueError("invalid pHYs dimensions or unit")
354
+ if name in single:
355
+ single.remove(name)
356
+ elif name not in {b"tEXt", b"iTXt", b"zTXt", b"sPLT"} and not name[1:2].islower():
357
+ continue
358
+ dest = after if name[1:2].islower() and len(chunk) == 3 and chunk[2] else before
359
+ dest.append((name, data))
360
+ if b"mDCV" not in single and b"cICP" in single:
361
+ raise ValueError("mDCV requires a cICP chunk")
362
+ if dpi:
363
+ before.append((b"pHYs", struct.pack(">IIB", *(int(v / 0.0254 + 0.5) for v in dpi), 1)))
364
+ if exif := im.encoderinfo.get("exif"):
365
+ if isinstance(exif, Image.Exif):
366
+ exif = exif.tobytes(8)
367
+ before.append((b"eXIf", exif.removeprefix(b"Exif\0\0")))
368
+ return before, after
369
+
370
+
371
+ def _palette_and_transparency(im):
372
+ trns = im.encoderinfo.get("transparency", im.info.get("transparency"))
373
+ if im.mode == "P":
374
+ palette = bytes(im.getpalette() or [0, 0, 0])
375
+ # Pillow also allows pixels beyond the defined palette (opaque black).
376
+ if len(palette) < 768:
377
+ palette = palette.ljust((im.getextrema()[1] + 1) * 3, b"\0")
378
+ entries = len(palette) // 3
379
+ if trns is None:
380
+ if im.palette and im.palette.mode == "RGBA":
381
+ trns = bytes(im.getpalette("RGBA")[3::4])
382
+ elif isinstance(trns, int):
383
+ trns = b"\xff" * max(0, min(255, trns)) + b"\0"
384
+ elif not isinstance(trns, bytes):
385
+ raise ValueError("palette transparency must be an index or bytes")
386
+ return palette, (trns or b"")[:entries]
387
+ if trns is not None:
388
+ if im.mode == "1":
389
+ # Pillow exposes white as either 1 or 255 depending on the release.
390
+ return b"", struct.pack(">H", int(trns != 0))
391
+ if im.mode in ("L", "I;16"):
392
+ return b"", struct.pack(">H", max(0, min(65535, trns)))
393
+ if im.mode == "RGB":
394
+ return b"", struct.pack(">3H", *trns)
395
+ if im.encoderinfo.get("transparency") is not None:
396
+ raise ValueError(f"cannot set transparency for {im.mode}")
397
+ return b"", b""
398
+
399
+
400
+ 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
+ lib = _library()
405
+ formats = {
406
+ "RGB": (lib.LASTPNG_RGB, 8, lib.LASTPNG_RGBX),
407
+ "LA": (lib.LASTPNG_GRAY_ALPHA, 8, lib.LASTPNG_LXXA),
408
+ "RGBA": (lib.LASTPNG_RGBA, 8, lib.LASTPNG_PACKED),
409
+ "L": (lib.LASTPNG_GRAY, 8, lib.LASTPNG_PACKED),
410
+ "P": (lib.LASTPNG_INDEXED, 8, lib.LASTPNG_PACKED),
411
+ "1": (lib.LASTPNG_GRAY, 1, lib.LASTPNG_BILEVEL8),
412
+ "I;16": (lib.LASTPNG_GRAY, 16, lib.LASTPNG_GRAY16_LE),
413
+ }
414
+ if im.mode not in formats:
415
+ raise OSError(f"cannot write mode {im.mode} as LASTPNG")
416
+ color, depth, packing = formats[im.mode]
417
+ if im.encoderinfo.get("bits", depth) != depth:
418
+ raise ValueError("LASTPNG selects the output bit depth automatically")
419
+ level = im.encoderinfo.get("level", 3)
420
+ if not isinstance(level, int) or not 1 <= level <= 6:
421
+ raise ValueError("LASTPNG level must be an integer from 1 to 6")
422
+ icc = im.encoderinfo.get("icc_profile", im.info.get("icc_profile"))
423
+ before, after = _metadata(im, icc)
424
+ palette, trns = _palette_and_transparency(im)
425
+ capsule = im.getim()
426
+ raster = _raster(capsule, layout, im.size)
427
+ config = ffi.new("lastpng_config *", dict(width=im.width, height=im.height, depth=depth,
428
+ color=color, layout=packing, level=level, preserve_color_space=bool(icc),
429
+ palette=ffi.from_buffer(palette), palette_len=len(palette),
430
+ transparency=ffi.from_buffer(trns), transparency_len=len(trns)))
431
+ error = ffi.new("lastpng_error *")
432
+ handle = ffi.new("lastpng_encoder **")
433
+ handle[0] = lib.lastpng_encoder_from_rows(config, raster.image, error)
434
+ if handle[0] == ffi.NULL:
435
+ raise ValueError(ffi.string(error.message).decode())
436
+ try:
437
+ result = lib.lastpng_encoder_output_info(handle[0])
438
+ callback_error = None
439
+
440
+ @ffi.callback("lastpng_write_fn", error=-1)
441
+ def write(context, data, size):
442
+ nonlocal callback_error
443
+ try:
444
+ buf = ffi.buffer(data, size)
445
+ # The sink may retain bytes after the native buffer expires.
446
+ # Slice in 64 KiB chunks to avoid copying a whole IDAT at once.
447
+ for start in range(0, size, 65536):
448
+ # Like Pillow's PNG writer, assume write() accepts all bytes or raises.
449
+ fp.write(buf[start:start + 65536])
450
+ return 0
451
+ except BaseException as exc:
452
+ callback_error = exc
453
+ return -1
454
+
455
+ fp.write(b"\x89PNG\r\n\x1a\n")
456
+ header = struct.pack(">IIBBBBB", result.width, result.height, result.depth, result.color, 0, 0, 0)
457
+ PngImagePlugin.putchunk(fp, b"IHDR", header)
458
+ for name, payload in before:
459
+ PngImagePlugin.putchunk(fp, name, payload)
460
+ if lib.lastpng_encoder_write_image_chunks(handle, write, ffi.NULL, error):
461
+ if callback_error is not None:
462
+ raise callback_error
463
+ raise OSError(ffi.string(error.message).decode())
464
+ for name, payload in after:
465
+ PngImagePlugin.putchunk(fp, name, payload)
466
+ PngImagePlugin.putchunk(fp, b"IEND", b"")
467
+ if hasattr(fp, "flush"):
468
+ fp.flush()
469
+ finally:
470
+ lib.lastpng_encoder_free(handle[0])
471
+
472
+
473
+ Image.register_save("LASTPNG", save)
474
+
475
+
476
+ def register_as_default(encoder=True):
477
+ """Enable Rust PNG decoding and, by default, LastPNG for ordinary PNG saves."""
478
+ Image.register_decoder("lastpng_png", _PngDecoder)
479
+ Image.register_open("PNG", _PngImageFile, PngImagePlugin._accept)
480
+ if encoder:
481
+ Image.register_save("PNG", save)
_lastpng/_abi.py ADDED
@@ -0,0 +1,11 @@
1
+ # auto-generated file
2
+ import _cffi_backend
3
+
4
+ ffi = _cffi_backend.FFI('_lastpng._abi',
5
+ _version = 0x2601,
6
+ _types = b'\x00\x00\x07\x0D\x00\x00\x24\x03\x00\x00\x16\x01\x00\x00\x12\x01\x00\x00\x41\x03\x00\x00\x00\x0F\x00\x00\x26\x0D\x00\x00\x3E\x03\x00\x00\x16\x01\x00\x00\x27\x03\x00\x00\x16\x01\x00\x00\x16\x01\x00\x00\x1C\x01\x00\x00\x04\x11\x00\x00\x00\x0F\x00\x00\x26\x0D\x00\x00\x3C\x03\x00\x00\x1F\x03\x00\x00\x4C\x03\x00\x00\x4A\x03\x00\x00\x00\x0F\x00\x00\x26\x0D\x00\x00\x03\x03\x00\x00\x1C\x01\x00\x00\x09\x11\x00\x00\x16\x01\x00\x00\x16\x01\x00\x00\x1C\x01\x00\x00\x12\x01\x00\x00\x04\x11\x00\x00\x00\x0F\x00\x00\x26\x0D\x00\x00\x12\x11\x00\x00\x16\x11\x00\x00\x1C\x01\x00\x00\x00\x0F\x00\x00\x25\x0D\x00\x00\x17\x01\x00\x00\x07\x01\x00\x00\x03\x03\x00\x00\x1C\x01\x00\x00\x00\x0F\x00\x00\x3C\x0D\x00\x00\x48\x03\x00\x00\x16\x03\x00\x00\x13\x11\x00\x00\x00\x0F\x00\x00\x3C\x0D\x00\x00\x2B\x11\x00\x00\x16\x11\x00\x00\x1C\x01\x00\x00\x13\x11\x00\x00\x00\x0F\x00\x00\x4B\x0D\x00\x00\x49\x03\x00\x00\x00\x0F\x00\x00\x4C\x0D\x00\x00\x07\x11\x00\x00\x00\x0F\x00\x00\x4C\x0D\x00\x00\x49\x03\x00\x00\x00\x0F\x00\x00\x05\x09\x00\x00\x00\x09\x00\x00\x01\x09\x00\x00\x02\x01\x00\x00\x41\x05\x00\x00\x01\x00\x00\x00\x41\x05\x00\x00\x00\x07\x00\x00\x00\x0B\x00\x00\x01\x0B\x00\x00\x02\x09\x00\x00\x06\x09\x00\x00\x03\x09\x00\x00\x04\x09\x00\x00\x00\x01',
7
+ _globals = (b'\xFF\xFF\xFF\x0BLASTPNG_BILEVEL8',3,b'\xFF\xFF\xFF\x0BLASTPNG_GRAY',0,b'\xFF\xFF\xFF\x0BLASTPNG_GRAY16_LE',4,b'\xFF\xFF\xFF\x0BLASTPNG_GRAY_ALPHA',4,b'\xFF\xFF\xFF\x0BLASTPNG_INDEXED',3,b'\xFF\xFF\xFF\x0BLASTPNG_LXXA',2,b'\xFF\xFF\xFF\x0BLASTPNG_PACKED',0,b'\xFF\xFF\xFF\x0BLASTPNG_RGB',2,b'\xFF\xFF\xFF\x0BLASTPNG_RGBA',6,b'\xFF\xFF\xFF\x0BLASTPNG_RGBX',1,b'\x00\x00\x38\x23lastpng_apng_free',0,b'\x00\x00\x00\x23lastpng_apng_new',0,b'\x00\x00\x06\x23lastpng_apng_pillow_rows',0,b'\x00\x00\x15\x23lastpng_decode_pillow_rows',0,b'\x00\x00\x3B\x23lastpng_encoder_free',0,b'\x00\x00\x2F\x23lastpng_encoder_from_buffer',0,b'\x00\x00\x2A\x23lastpng_encoder_from_rows',0,b'\x00\x00\x35\x23lastpng_encoder_output_info',0,b'\x00\x00\x0F\x23lastpng_encoder_write_image_chunks',0,b'\x00\x00\x0F\x23lastpng_encoder_write_png',0),
8
+ _struct_unions = ((b'\x00\x00\x00\x3F\x00\x00\x00\x02$Imaging11',b'\x00\x00\x44\x11mode',b'\x00\x00\x26\x11type',b'\x00\x00\x26\x11depth',b'\x00\x00\x26\x11bands',b'\x00\x00\x26\x11xsize',b'\x00\x00\x26\x11ysize',b'\x00\x00\x12\x11palette',b'\x00\x00\x12\x11image8',b'\x00\x00\x12\x11image32',b'\x00\x00\x2C\x11image'),(b'\x00\x00\x00\x40\x00\x00\x00\x02$Imaging12',b'\x00\x00\x26\x11mode',b'\x00\x00\x26\x11type',b'\x00\x00\x26\x11depth',b'\x00\x00\x26\x11bands',b'\x00\x00\x26\x11xsize',b'\x00\x00\x26\x11ysize',b'\x00\x00\x12\x11palette',b'\x00\x00\x12\x11image8',b'\x00\x00\x12\x11image32',b'\x00\x00\x2C\x11image'),(b'\x00\x00\x00\x48\x00\x00\x00\x02$lastpng_config',b'\x00\x00\x02\x11width',b'\x00\x00\x02\x11height',b'\x00\x00\x03\x11color',b'\x00\x00\x03\x11depth',b'\x00\x00\x03\x11layout',b'\x00\x00\x03\x11level',b'\x00\x00\x03\x11preserve_color_space',b'\x00\x00\x16\x11palette',b'\x00\x00\x0C\x11palette_len',b'\x00\x00\x16\x11transparency',b'\x00\x00\x0C\x11transparency_len'),(b'\x00\x00\x00\x4A\x00\x00\x00\x02$lastpng_error',b'\x00\x00\x42\x11message'),(b'\x00\x00\x00\x4B\x00\x00\x00\x02$lastpng_output_info',b'\x00\x00\x02\x11width',b'\x00\x00\x02\x11height',b'\x00\x00\x03\x11color',b'\x00\x00\x03\x11depth'),(b'\x00\x00\x00\x3E\x00\x00\x00\x10APngDecoder',),(b'\x00\x00\x00\x49\x00\x00\x00\x10lastpng_encoder',)),
9
+ _enums = (b'\x00\x00\x00\x46\x00\x00\x00\x16$1\x00LASTPNG_GRAY,LASTPNG_RGB,LASTPNG_INDEXED,LASTPNG_GRAY_ALPHA,LASTPNG_RGBA',b'\x00\x00\x00\x47\x00\x00\x00\x16$2\x00LASTPNG_PACKED,LASTPNG_RGBX,LASTPNG_LXXA,LASTPNG_BILEVEL8,LASTPNG_GRAY16_LE'),
10
+ _typenames = (b'\x00\x00\x00\x3EAPngDecoder',b'\x00\x00\x00\x3FImaging11',b'\x00\x00\x00\x40Imaging12',b'\x00\x00\x00\x01LastPngStreamIo',b'\x00\x00\x00\x48lastpng_config',b'\x00\x00\x00\x49lastpng_encoder',b'\x00\x00\x00\x4Alastpng_error',b'\x00\x00\x00\x4Blastpng_output_info',b'\x00\x00\x00\x11lastpng_write_fn'),
11
+ )
_lastpng/lastpng.dll ADDED
Binary file
Binary file
@@ -0,0 +1,148 @@
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/`.
@@ -0,0 +1,10 @@
1
+ LastPNGImagePlugin.py,sha256=6EgRXV6X2TRCnuw4nvnrwZ5qtFep9051PHBVoP4nbik,19834
2
+ _lastpng/_abi.py,sha256=t4oLNVe9z0ctMpP-qz06NS0WyLyihjIPdJteP187okg,4116
3
+ _lastpng/lastpng.dll,sha256=Jq-rDZDnEv_Y9cukzRnJEG9gOHKayYNb88cUdkf-ZrA,782848
4
+ _lastpng/lastpng_decoder.dll,sha256=lMeEbFkEOmlieO9uybLGrnkq3O7coMxTatjMMoCNWVM,379392
5
+ lastpngimageplugin-0.2.0.dist-info/METADATA,sha256=PXIPAi0XoVuVtJ-JAZz3T7MWQwLFiF1xkzFSdq6ccJg,5891
6
+ lastpngimageplugin-0.2.0.dist-info/WHEEL,sha256=lpoBGaIUIidvvdZ4qRAP61bBKYJdt4FI3WXFL50Gzyo,94
7
+ lastpngimageplugin-0.2.0.dist-info/licenses/LICENSE,sha256=m7fKtIiHXqSz8C56c976SMQsbnPoasvDpl7u8d2bGBM,1077
8
+ lastpngimageplugin-0.2.0.dist-info/licenses/licenses/fdeflate-LICENSE-MIT,sha256=x3pM-dpymYfQ_nzNgR470nOTkU3fPSNGfBjMIpVFE7M,1036
9
+ lastpngimageplugin-0.2.0.dist-info/licenses/licenses/libdeflate-COPYING,sha256=StaQmctDdINv0nWD2ZkeKDjNhrbkZmqyay0yWCyR5zo,1078
10
+ lastpngimageplugin-0.2.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: false
4
+ Tag: py3-none-win_amd64
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Aleksandr Karpinskii
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,25 @@
1
+ MIT License
2
+
3
+ Permission is hereby granted, free of charge, to any
4
+ person obtaining a copy of this software and associated
5
+ documentation files (the "Software"), to deal in the
6
+ Software without restriction, including without
7
+ limitation the rights to use, copy, modify, merge,
8
+ publish, distribute, sublicense, and/or sell copies of
9
+ the Software, and to permit persons to whom the Software
10
+ is furnished to do so, subject to the following
11
+ conditions:
12
+
13
+ The above copyright notice and this permission notice
14
+ shall be included in all copies or substantial portions
15
+ of the Software.
16
+
17
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
18
+ ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
19
+ TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
20
+ PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
21
+ SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
22
+ CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
23
+ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
24
+ IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
25
+ DEALINGS IN THE SOFTWARE.
@@ -0,0 +1,22 @@
1
+ Copyright 2016 Eric Biggers
2
+ Copyright 2024 Google LLC
3
+
4
+ Permission is hereby granted, free of charge, to any person
5
+ obtaining a copy of this software and associated documentation files
6
+ (the "Software"), to deal in the Software without restriction,
7
+ including without limitation the rights to use, copy, modify, merge,
8
+ publish, distribute, sublicense, and/or sell copies of the Software,
9
+ and to permit persons to whom the Software is furnished to do so,
10
+ subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be
13
+ included in all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
19
+ BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
20
+ ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
21
+ CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
+ SOFTWARE.