libimgquant 3.0.0__cp39-abi3-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.
@@ -0,0 +1,77 @@
1
+ """Pure-Rust, BSD-licensed color quantizer: converts RGBA images to 8-bit palette images
2
+ with alpha, for small PNGs and GIFs.
3
+
4
+ - :func:`quantize` turns RGBA pixels into a palette and one palette index per pixel.
5
+ - :func:`compress_png` converts a PNG file to a small palette PNG, like pngquant.
6
+ - :func:`quantize_frames` finds one palette for several images, such as animation frames.
7
+ - :func:`quantize_image` does the same as :func:`quantize` for a Pillow image.
8
+
9
+ All of them release the GIL while they work.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ from typing import TYPE_CHECKING, Literal
15
+
16
+ from ._libimgquant import (
17
+ QualityTooLowError,
18
+ QuantizeResult,
19
+ __version__,
20
+ compress_png,
21
+ quantize,
22
+ quantize_frames,
23
+ )
24
+
25
+ if TYPE_CHECKING:
26
+ from PIL import Image
27
+
28
+ __all__ = [
29
+ "QualityTooLowError",
30
+ "QuantizeResult",
31
+ "__version__",
32
+ "compress_png",
33
+ "quantize",
34
+ "quantize_frames",
35
+ "quantize_image",
36
+ ]
37
+
38
+
39
+ def quantize_image(
40
+ img: Image.Image,
41
+ *,
42
+ max_colors: int = 256,
43
+ speed: int = 3,
44
+ quality: int | tuple[int, int] | None = None,
45
+ dithering: float = 1.0,
46
+ profile: Literal["improved", "compat"] = "improved",
47
+ ) -> Image.Image:
48
+ """Quantizes a Pillow image and returns it in mode ``"P"``.
49
+
50
+ Images in other modes are converted to RGBA first. Alpha is kept: the palette's alpha
51
+ values go to ``info["transparency"]`` (up to the last translucent entry, like a PNG
52
+ tRNS chunk), which ``Image.save`` writes to PNG files. The options are those of
53
+ :func:`quantize`. Pillow is imported only when this function is called.
54
+ """
55
+ from PIL import Image
56
+
57
+ rgba = img if img.mode == "RGBA" else img.convert("RGBA")
58
+ width, height = rgba.size
59
+ result = quantize(
60
+ rgba.tobytes(),
61
+ width,
62
+ height,
63
+ max_colors=max_colors,
64
+ speed=speed,
65
+ quality=quality,
66
+ dithering=dithering,
67
+ profile=profile,
68
+ )
69
+ palette = result.palette
70
+ out = Image.frombytes("P", (width, height), result.indices)
71
+ out.putpalette(bytes(c for r, g, b, _ in palette for c in (r, g, b)), "RGB")
72
+ # translucent entries come first, so this is usually short or empty
73
+ alphas = [a for _, _, _, a in palette]
74
+ last_translucent = max((i for i, a in enumerate(alphas) if a < 255), default=-1)
75
+ if last_translucent >= 0:
76
+ out.info["transparency"] = bytes(alphas[: last_translucent + 1])
77
+ return out
Binary file
@@ -0,0 +1,112 @@
1
+ import sys
2
+ from collections.abc import Iterable
3
+ from typing import Literal, final
4
+
5
+ from typing_extensions import TypeAlias
6
+
7
+ if sys.version_info >= (3, 12):
8
+ from collections.abc import Buffer
9
+ else:
10
+ from typing_extensions import Buffer
11
+
12
+ __all__ = [
13
+ "QualityTooLowError",
14
+ "QuantizeResult",
15
+ "__version__",
16
+ "compress_png",
17
+ "quantize",
18
+ "quantize_frames",
19
+ ]
20
+
21
+ __version__: str
22
+
23
+ _Color: TypeAlias = tuple[int, int, int, int]
24
+ """A palette entry: (r, g, b, a), each 0-255, not premultiplied."""
25
+
26
+ _Quality: TypeAlias = int | tuple[int, int] | None
27
+ """None (no limit), a target 0-100, or (minimum, target)."""
28
+
29
+ _Profile: TypeAlias = Literal["improved", "compat"]
30
+
31
+ class QualityTooLowError(ValueError):
32
+ """The image could not be quantized within the minimum ``quality``."""
33
+
34
+ @final
35
+ class QuantizeResult:
36
+ """The result of :func:`quantize`."""
37
+
38
+ @property
39
+ def palette(self) -> list[_Color]:
40
+ """At most ``max_colors`` (r, g, b, a) entries, translucent entries first."""
41
+ @property
42
+ def indices(self) -> bytes:
43
+ """One palette index per pixel, row by row (``width * height`` bytes)."""
44
+ @property
45
+ def quality(self) -> int | None:
46
+ """The quality reached, 0-100, on the scale of the ``quality`` option."""
47
+ @property
48
+ def width(self) -> int: ...
49
+ @property
50
+ def height(self) -> int: ...
51
+
52
+ def quantize(
53
+ pixels: Buffer,
54
+ width: int,
55
+ height: int,
56
+ *,
57
+ max_colors: int = 256,
58
+ speed: int = 3,
59
+ quality: _Quality = None,
60
+ dithering: float = 1.0,
61
+ profile: _Profile = "improved",
62
+ ) -> QuantizeResult:
63
+ """Quantizes ``width * height`` RGBA pixels (``width * height * 4`` bytes, row by row)
64
+ to at most ``max_colors`` colors, and remaps them with Floyd-Steinberg ``dithering``
65
+ (0 = none, 1 = full).
66
+
67
+ ``pixels`` is any bytes-like object of 8-bit values: bytes, bytearray, memoryview,
68
+ array.array("B") or a uint8 numpy array such as one of shape (height, width, 4).
69
+
70
+ ``speed`` goes from 1 (slowest, best) to 10 (fastest). ``quality`` works like JPEG
71
+ quality: the fewest colors that reach the target are used, and below the minimum
72
+ :class:`QualityTooLowError` is raised. ``profile="compat"`` reproduces libimagequant
73
+ 2.4.1's algorithms, apart from a few bug fixes.
74
+
75
+ Raises ValueError for arguments out of range, TypeError for objects without the buffer
76
+ protocol, and QualityTooLowError (a ValueError) when the minimum quality can't be
77
+ reached.
78
+ """
79
+
80
+ def compress_png(
81
+ data: Buffer,
82
+ *,
83
+ max_colors: int = 256,
84
+ speed: int = 3,
85
+ quality: _Quality = None,
86
+ dithering: float = 1.0,
87
+ profile: _Profile = "improved",
88
+ ) -> bytes:
89
+ """Converts a PNG file to a palette PNG, like pngquant, and returns the new file.
90
+
91
+ Any PNG can be read; the output keeps its dimensions, gamma and RGB ICC profile, uses the
92
+ smallest bit depth,
93
+ a tRNS chunk only as long as needed, and the smaller of a filtered and an unfiltered
94
+ encoding. Options and errors as for :func:`quantize`; ValueError for an invalid PNG.
95
+ """
96
+
97
+ def quantize_frames(
98
+ frames: Iterable[Buffer],
99
+ width: int,
100
+ height: int,
101
+ *,
102
+ max_colors: int = 256,
103
+ speed: int = 3,
104
+ quality: _Quality = None,
105
+ dithering: float = 1.0,
106
+ profile: _Profile = "improved",
107
+ ) -> tuple[list[_Color], list[bytes]]:
108
+ """Quantizes several RGBA images of the same size to one palette, for example the
109
+ frames of an animated GIF, and returns ``(palette, indices)`` with the indices of each
110
+ frame. Each frame is weighted as :func:`quantize` would weight it on its own.
111
+ Options and errors as for :func:`quantize`.
112
+ """
libimgquant/py.typed ADDED
File without changes
@@ -0,0 +1,192 @@
1
+ Metadata-Version: 2.4
2
+ Name: libimgquant
3
+ Version: 3.0.0
4
+ Classifier: Development Status :: 5 - Production/Stable
5
+ Classifier: Intended Audience :: Developers
6
+ Classifier: Operating System :: OS Independent
7
+ Classifier: Programming Language :: Python :: 3
8
+ Classifier: Programming Language :: Python :: 3 :: Only
9
+ Classifier: Programming Language :: Python :: 3.9
10
+ Classifier: Programming Language :: Python :: 3.10
11
+ Classifier: Programming Language :: Python :: 3.11
12
+ Classifier: Programming Language :: Python :: 3.12
13
+ Classifier: Programming Language :: Python :: 3.13
14
+ Classifier: Programming Language :: Python :: 3.14
15
+ Classifier: Programming Language :: Python :: 3.15
16
+ Classifier: Programming Language :: Python :: Implementation :: CPython
17
+ Classifier: Programming Language :: Rust
18
+ Classifier: Topic :: Multimedia :: Graphics
19
+ Classifier: Topic :: Multimedia :: Graphics :: Graphics Conversion
20
+ Classifier: Typing :: Typed
21
+ Requires-Dist: pillow>=9.1 ; extra == 'pillow'
22
+ Requires-Dist: pytest>=8 ; extra == 'test'
23
+ Requires-Dist: pillow>=9.1 ; extra == 'test'
24
+ Requires-Dist: numpy>=1.22 ; extra == 'test'
25
+ Provides-Extra: pillow
26
+ Provides-Extra: test
27
+ License-File: LICENSE
28
+ License-File: NOTICE
29
+ License-File: THIRD-PARTY-LICENSES.txt
30
+ Summary: Pure-Rust, BSD-licensed color quantizer: RGBA images to 8-bit palette images with alpha, for small PNGs and GIFs
31
+ Keywords: quantization,palette,png,gif,pngquant,libimagequant,image compression
32
+ Author: kiwina
33
+ License-Expression: BSD-2-Clause
34
+ Requires-Python: >=3.9
35
+ Description-Content-Type: text/markdown; charset=UTF-8; variant=GFM
36
+ Project-URL: Changelog, https://github.com/kiwina/libimgquant/blob/main/CHANGELOG.md
37
+ Project-URL: Documentation, https://github.com/kiwina/libimgquant/tree/main/python#readme
38
+ Project-URL: Homepage, https://github.com/kiwina/libimgquant
39
+ Project-URL: Issues, https://github.com/kiwina/libimgquant/issues
40
+ Project-URL: Repository, https://github.com/kiwina/libimgquant
41
+
42
+ # libimgquant for Python
43
+
44
+ Converts RGBA images to 8-bit palette images with alpha, for small PNGs and GIFs, like
45
+ pngquant. Pure Rust underneath, BSD-licensed, with no runtime dependencies.
46
+
47
+ libimgquant 3 is a Rust rewrite of libimagequant **2.4.1**, the last BSD-licensed release
48
+ of the library behind pngquant, improved with published color quantization research: a
49
+ variance-based median cut, Hartigan refinement after k-means, an exact nearest-color search,
50
+ an OKLab-shaped color difference and a palette order that makes PNGs smaller.
51
+ `profile="compat"` reproduces 2.4.1's algorithms instead, apart from a few bug fixes. The
52
+ [Rust crate's README](https://crates.io/crates/libimgquant) describes the algorithms and
53
+ compares them with libimagequant 2.4.1 and imagequant 4.4.1.
54
+
55
+ - **BSD-2-Clause**, no GPL code: usable in closed-source and commercial software.
56
+ - **One wheel per platform** for CPython 3.9 and newer (stable ABI, `abi3`).
57
+ - **Multi-threaded**, and every function releases the GIL while it works.
58
+ - **Typed**: ships type hints (`py.typed`).
59
+
60
+ ## Install
61
+
62
+ ```bash
63
+ pip install libimgquant
64
+ pip install "libimgquant[pillow]" # also installs Pillow, for quantize_image()
65
+ ```
66
+
67
+ From a checkout of the repository, with a Rust toolchain installed: `pip install ./python`
68
+ (maturin builds the wheel).
69
+
70
+ ## Compress a PNG file
71
+
72
+ ```python
73
+ import libimgquant
74
+
75
+ with open("photo.png", "rb") as f:
76
+ data = f.read()
77
+
78
+ small = libimgquant.compress_png(data, quality=(65, 90))
79
+ with open("photo-fs8.png", "wb") as f:
80
+ f.write(small)
81
+ ```
82
+
83
+ `compress_png` reads any PNG and writes a palette PNG with the same dimensions, gamma and
84
+ ICC color profile, the smallest bit depth, a tRNS chunk only as long as needed, and the
85
+ smaller of a filtered and an unfiltered encoding.
86
+
87
+ ## Quantize pixels
88
+
89
+ `quantize` takes `width * height` RGBA pixels as any bytes-like object (`width * height * 4`
90
+ bytes, row by row) and returns the palette and one palette index per pixel:
91
+
92
+ ```python
93
+ import libimgquant
94
+
95
+ width, height = 64, 48
96
+ pixels = bytes(
97
+ v
98
+ for y in range(height)
99
+ for x in range(width)
100
+ for v in (x * 4, y * 5, 128, 100 if y < 8 else 255)
101
+ )
102
+
103
+ result = libimgquant.quantize(pixels, width, height, max_colors=64)
104
+ result.palette # [(r, g, b, a), ...], at most 64 entries, translucent entries first
105
+ result.indices # bytes, one palette index per pixel
106
+ result.quality # quality reached, 0-100
107
+ ```
108
+
109
+ ### numpy
110
+
111
+ A `uint8` array of shape `(height, width, 4)` works as it is:
112
+
113
+ ```python
114
+ import numpy as np
115
+ import libimgquant
116
+
117
+ rgba = np.zeros((480, 640, 4), dtype=np.uint8) # your image
118
+ result = libimgquant.quantize(rgba, 640, 480)
119
+
120
+ palette = np.array(result.palette, dtype=np.uint8) # (colors, 4)
121
+ indices = np.frombuffer(result.indices, np.uint8).reshape(480, 640)
122
+ restored = palette[indices] # (480, 640, 4)
123
+ ```
124
+
125
+ ### Pillow
126
+
127
+ `quantize_image` takes a Pillow image in any mode, so any format Pillow opens (JPEG, WebP,
128
+ GIF, ...) works, and returns a mode `"P"` image. The palette's alpha values go to
129
+ `info["transparency"]`, so saving it as PNG keeps transparency:
130
+
131
+ ```python
132
+ from PIL import Image
133
+ import libimgquant
134
+
135
+ img = Image.open("sprite.png")
136
+ small = libimgquant.quantize_image(img, max_colors=128, dithering=0.5)
137
+ small.save("sprite-128.png", optimize=True)
138
+ ```
139
+
140
+ Pillow is imported only when `quantize_image` is called; the other functions don't need it.
141
+
142
+ ## One palette for many images
143
+
144
+ For an animated GIF, a sprite sheet or a tile set, `quantize_frames` computes one palette
145
+ for several images of the same size and remaps each of them to it. Colors that appear in
146
+ only one frame still get palette entries.
147
+
148
+ ```python
149
+ palette, frame_indices = libimgquant.quantize_frames(frames, width, height, max_colors=255)
150
+ # frame_indices[i]: the indices of frames[i] into the shared palette
151
+ ```
152
+
153
+ ## Options
154
+
155
+ All functions take the same keyword-only options:
156
+
157
+ | Option | Default | Meaning |
158
+ | --- | --- | --- |
159
+ | `max_colors` | `256` | At most this many palette entries, 2–256. |
160
+ | `speed` | `3` | 1 (slowest, best) to 10 (fastest). With `profile="improved"`, speeds 1–7 also order the palette for smaller PNGs (not in `quantize_frames`, whose palette is shared). |
161
+ | `quality` | `None` | Like JPEG quality, 0–100. An int is the target; `(minimum, target)` also sets a minimum. The fewest colors that reach the target are used; below the minimum, `QualityTooLowError` is raised. |
162
+ | `dithering` | `1.0` | Floyd-Steinberg dithering, 0 (none) to 1 (full). |
163
+ | `profile` | `"improved"` | `"improved"`: the version 3 algorithms. `"compat"`: libimagequant 2.4.1's algorithms, step by step, apart from a few bug fixes. |
164
+
165
+ ## Errors
166
+
167
+ - `ValueError`: an option is out of range, the pixel buffer has the wrong size or is not
168
+ 8-bit, or the PNG is invalid.
169
+ - `libimgquant.QualityTooLowError` (a `ValueError`): the minimum quality can't be reached
170
+ with `max_colors` colors. Keep the original image in that case, as pngquant does.
171
+ - `TypeError`: the pixels are not a bytes-like object.
172
+
173
+ ```python
174
+ try:
175
+ small = libimgquant.compress_png(data, quality=(80, 95))
176
+ except libimgquant.QualityTooLowError:
177
+ small = data # not worth converting
178
+ ```
179
+
180
+ ## Threads
181
+
182
+ Quantization runs on all cores (a rayon thread pool), and the GIL is released while it
183
+ runs, so other Python threads keep working and several images can be converted at once
184
+ from a `ThreadPoolExecutor`. The output does not depend on the number of threads.
185
+
186
+ ## License
187
+
188
+ BSD-2-Clause, plus the original permissive notice by Jef Poskanzer. See the `LICENSE` and
189
+ `NOTICE` files in the package. The wheels and the sdist also contain
190
+ `THIRD-PARTY-LICENSES.txt`, the licenses of the Rust crates compiled into the extension. The
191
+ Rust library is [libimgquant on crates.io](https://crates.io/crates/libimgquant).
192
+
@@ -0,0 +1,11 @@
1
+ libimgquant/__init__.py,sha256=TsCZ0P1aQTlIkRnIIMJiLjEmLv0MQiomof05MC_nWt0,2433
2
+ libimgquant/_libimgquant.pyd,sha256=2fF6-APY_yesAqXr462qbuZHsYY_kXdsD9hECQwQC2Q,1127936
3
+ libimgquant/_libimgquant.pyi,sha256=or5TtkBck65DrT7OJuYRa8roo5xc6W33f0HimLOD-ms,3666
4
+ libimgquant/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
5
+ libimgquant-3.0.0.dist-info/METADATA,sha256=notBUbbqk3IUbK_xJXKSg1tYHJbQwuXblnxzh4oSDPY,7728
6
+ libimgquant-3.0.0.dist-info/WHEEL,sha256=xw8F9xBWUOgm5ym2S9tihj_bLJOb723bjhA0kdANo2I,95
7
+ libimgquant-3.0.0.dist-info/licenses/LICENSE,sha256=mJxr7X1MZKYhsehgAA488nepzT7meErChV9dSXN_qOQ,1416
8
+ libimgquant-3.0.0.dist-info/licenses/NOTICE,sha256=rXQVuzLyBlv0Us5qT4kkCwZjr4fCEqdFABeqKn9EqK8,759
9
+ libimgquant-3.0.0.dist-info/licenses/THIRD-PARTY-LICENSES.txt,sha256=CjC0iYnGaXQog2DpR5CYEjq0-6NgG651pELww3NdnLY,30161
10
+ libimgquant-3.0.0.dist-info/sboms/libimgquant-python.cyclonedx.json,sha256=Xi5Xwcytl-vVKF5ov7uPruwIOr5hrn5hXwkvGKaHpzo,38270
11
+ libimgquant-3.0.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: maturin (1.16.0)
3
+ Root-Is-Purelib: false
4
+ Tag: cp39-abi3-win_amd64
@@ -0,0 +1,26 @@
1
+ © 1997-2002 by Greg Roelofs; based on an idea by Stefan Schneider.
2
+ © 2009-2014 by Kornel Lesiński.
3
+ © 2026 libimgquant contributors (Rust port).
4
+
5
+ All rights reserved.
6
+
7
+ Redistribution and use in source and binary forms, with or without modification,
8
+ are permitted provided that the following conditions are met:
9
+
10
+ 1. Redistributions of source code must retain the above copyright notice,
11
+ this list of conditions and the following disclaimer.
12
+
13
+ 2. Redistributions in binary form must reproduce the above copyright notice,
14
+ this list of conditions and the following disclaimer in the documentation
15
+ and/or other materials provided with the distribution.
16
+
17
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
18
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
20
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
21
+ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22
+ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
23
+ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
24
+ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
25
+ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
@@ -0,0 +1,16 @@
1
+ This Rust port is derived from libimagequant 2.4.1
2
+ (https://github.com/ImageOptim/libimagequant, tag 2.4.1, commit
3
+ 976e021cda07c14cd36630f611a5a6eb2cafc28e), which was distributed under the
4
+ licenses reproduced in LICENSE and below. The port is distributed under the
5
+ same terms.
6
+
7
+ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
8
+
9
+ © 1989, 1991 by Jef Poskanzer.
10
+
11
+ Permission to use, copy, modify, and distribute this software and its
12
+ documentation for any purpose and without fee is hereby granted, provided
13
+ that the above copyright notice appear in all copies and that both that
14
+ copyright notice and this permission notice appear in supporting
15
+ documentation. This software is provided "as is" without express or
16
+ implied warranty.