uppercut-pixel-art-sheets 0.1.0__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.
- uppercut_pixel_art_sheets-0.1.0/.gitignore +8 -0
- uppercut_pixel_art_sheets-0.1.0/PKG-INFO +78 -0
- uppercut_pixel_art_sheets-0.1.0/README.md +63 -0
- uppercut_pixel_art_sheets-0.1.0/pyproject.toml +28 -0
- uppercut_pixel_art_sheets-0.1.0/src/uppercut_pixel_art_sheets/__init__.py +36 -0
- uppercut_pixel_art_sheets-0.1.0/src/uppercut_pixel_art_sheets/draw.py +176 -0
- uppercut_pixel_art_sheets-0.1.0/src/uppercut_pixel_art_sheets/palette.py +139 -0
- uppercut_pixel_art_sheets-0.1.0/src/uppercut_pixel_art_sheets/py.typed +0 -0
- uppercut_pixel_art_sheets-0.1.0/src/uppercut_pixel_art_sheets/sheet.py +73 -0
- uppercut_pixel_art_sheets-0.1.0/tests/test_pixel_art_sheets.py +253 -0
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: uppercut-pixel-art-sheets
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Pillow helpers for indexed pixel-art sheets: palettes, pattern fills, a bitmap font and sheet packing.
|
|
5
|
+
Project-URL: Source, https://github.com/uppercut-labs/py-kit/tree/main/packages/uppercut-pixel-art-sheets
|
|
6
|
+
Author-email: Uppercut Labs <packages@uppercut-labs.com>
|
|
7
|
+
License-Expression: MIT
|
|
8
|
+
Keywords: indexed png,palette,pillow,pixel art,sprite sheet
|
|
9
|
+
Classifier: Programming Language :: Python :: 3
|
|
10
|
+
Classifier: Topic :: Multimedia :: Graphics
|
|
11
|
+
Classifier: Typing :: Typed
|
|
12
|
+
Requires-Python: >=3.10
|
|
13
|
+
Requires-Dist: pillow>=10
|
|
14
|
+
Description-Content-Type: text/markdown
|
|
15
|
+
|
|
16
|
+
# uppercut-pixel-art-sheets
|
|
17
|
+
|
|
18
|
+
Pillow helpers for building indexed pixel-art sheets. It covers palettes with a reserved transparent index, stamping 1-bit patterns, drawing text with a built-in 5x7 bitmap font, drawing in a tile's own coordinates, packing tiles into a sheet grid with metadata, and saving indexed PNGs.
|
|
19
|
+
|
|
20
|
+
## Install
|
|
21
|
+
|
|
22
|
+
```sh
|
|
23
|
+
pip install uppercut-pixel-art-sheets
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
Requires Python 3.10 or newer and Pillow 10 or newer.
|
|
27
|
+
|
|
28
|
+
## Example
|
|
29
|
+
|
|
30
|
+
```python
|
|
31
|
+
from PIL import ImageDraw
|
|
32
|
+
from uppercut_pixel_art_sheets import (
|
|
33
|
+
build_sheet, draw_text, hex_to_rgb, new_indexed, save_indexed, snap_to_bits,
|
|
34
|
+
)
|
|
35
|
+
|
|
36
|
+
palette = [snap_to_bits(hex_to_rgb(c)) for c in ("#000000", "#f4e5ba", "#b63f3b", "#4fb9c3")]
|
|
37
|
+
|
|
38
|
+
def tile(label, color):
|
|
39
|
+
im = new_indexed(16, 16) # index 0 is transparent
|
|
40
|
+
d = ImageDraw.Draw(im)
|
|
41
|
+
d.rectangle((1, 1, 14, 14), fill=color)
|
|
42
|
+
draw_text(d, label, 5, 4, 1)
|
|
43
|
+
return label, im
|
|
44
|
+
|
|
45
|
+
sheet, meta = build_sheet([tile("A", 2), tile("B", 3), tile("C", 2)], cols=2, cell_w=16, cell_h=16, palette=palette)
|
|
46
|
+
save_indexed(sheet, palette, "sheet.png")
|
|
47
|
+
print(meta[1]) # {'index': 1, 'name': 'B', 'col': 1, 'row': 0, 'x': 16, 'y': 0, 'w': 16, 'h': 16}
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
## Functions
|
|
51
|
+
|
|
52
|
+
| Name | What it does |
|
|
53
|
+
| --- | --- |
|
|
54
|
+
| `hex_to_rgb(value)` | Parses `#rrggbb`. |
|
|
55
|
+
| `snap_to_bits(color, bits=5)` | Rounds each channel to `bits` bits and back to 8, for console-style color depth. |
|
|
56
|
+
| `new_indexed(width, height, fill=0)` | A palette-mode image filled with one index. |
|
|
57
|
+
| `apply_palette(image, palette, *, transparency=0, size=256)` | Sets the palette, padded with black to `size` entries. `transparency` is a transparent index, a bytes object with one alpha per index, or `None`. |
|
|
58
|
+
| `save_indexed(image, palette, path, *, transparency=0, size=256)` | Applies the palette, creates parent folders and saves an indexed PNG. Returns the path. |
|
|
59
|
+
| `force_corner_transparent(image)` | Swaps the top-left pixel's color into index 0 and marks index 0 transparent. The picture looks the same. |
|
|
60
|
+
| `quantize_indexed(image, colors=16, *, transparent_corner=True)` | Adaptive palette reduction, optionally followed by `force_corner_transparent`. |
|
|
61
|
+
| `indexed_to_rgba(image, *, transparent_index=0)` | RGBA copy with one index made transparent. |
|
|
62
|
+
| `stamp_pattern(draw, pattern, x, y, color, *, scale=1, ink="1")` | Draws each `ink` character of a list of strings as a block. Works on indexed and RGB images. |
|
|
63
|
+
| `FONT_5X7` | Glyph table for letters, digits and common punctuation. |
|
|
64
|
+
| `draw_text(draw, text, x, y, color, *, font=FONT_5X7, spacing=6, scale=1)` | Draws upper-cased text, shows `?` for unknown characters, returns the advance in pixels. |
|
|
65
|
+
| `text_width(text, *, font=FONT_5X7, spacing=6, scale=1)` | Pixel width of a string. |
|
|
66
|
+
| `cut_corner_box(draw, box, fill, outline=None)` | Rectangle with its corner pixels cut off. |
|
|
67
|
+
| `Origin(draw, ox, oy)` | Offsets `point`, `line`, `rect`, `ellipse`, `polygon`, `pattern` and `text` by `(ox, oy)`. |
|
|
68
|
+
| `nearest_scale(image, factor)` | Whole-number nearest-neighbour upscale. |
|
|
69
|
+
| `paste_cell(sheet, tile, col, row, cell_w, cell_h)` | Pastes a tile into the top-left of a grid cell. |
|
|
70
|
+
| `build_sheet(tiles, cols, cell_w, cell_h, palette=None, *, fill=0, transparency=0, size=256)` | Packs tiles (images or `(name, image)` pairs) into a sheet and returns it with one metadata dict per tile. With a palette the sheet is indexed; without one it is RGBA. |
|
|
71
|
+
|
|
72
|
+
## Errors
|
|
73
|
+
|
|
74
|
+
All functions raise `ValueError` for bad input: an image that is not in palette mode where one is required, a palette larger than `size`, a tile bigger than its cell, an empty tile list, a scale or factor below 1, or a malformed hex color.
|
|
75
|
+
|
|
76
|
+
## License
|
|
77
|
+
|
|
78
|
+
MIT
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
# uppercut-pixel-art-sheets
|
|
2
|
+
|
|
3
|
+
Pillow helpers for building indexed pixel-art sheets. It covers palettes with a reserved transparent index, stamping 1-bit patterns, drawing text with a built-in 5x7 bitmap font, drawing in a tile's own coordinates, packing tiles into a sheet grid with metadata, and saving indexed PNGs.
|
|
4
|
+
|
|
5
|
+
## Install
|
|
6
|
+
|
|
7
|
+
```sh
|
|
8
|
+
pip install uppercut-pixel-art-sheets
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
Requires Python 3.10 or newer and Pillow 10 or newer.
|
|
12
|
+
|
|
13
|
+
## Example
|
|
14
|
+
|
|
15
|
+
```python
|
|
16
|
+
from PIL import ImageDraw
|
|
17
|
+
from uppercut_pixel_art_sheets import (
|
|
18
|
+
build_sheet, draw_text, hex_to_rgb, new_indexed, save_indexed, snap_to_bits,
|
|
19
|
+
)
|
|
20
|
+
|
|
21
|
+
palette = [snap_to_bits(hex_to_rgb(c)) for c in ("#000000", "#f4e5ba", "#b63f3b", "#4fb9c3")]
|
|
22
|
+
|
|
23
|
+
def tile(label, color):
|
|
24
|
+
im = new_indexed(16, 16) # index 0 is transparent
|
|
25
|
+
d = ImageDraw.Draw(im)
|
|
26
|
+
d.rectangle((1, 1, 14, 14), fill=color)
|
|
27
|
+
draw_text(d, label, 5, 4, 1)
|
|
28
|
+
return label, im
|
|
29
|
+
|
|
30
|
+
sheet, meta = build_sheet([tile("A", 2), tile("B", 3), tile("C", 2)], cols=2, cell_w=16, cell_h=16, palette=palette)
|
|
31
|
+
save_indexed(sheet, palette, "sheet.png")
|
|
32
|
+
print(meta[1]) # {'index': 1, 'name': 'B', 'col': 1, 'row': 0, 'x': 16, 'y': 0, 'w': 16, 'h': 16}
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
## Functions
|
|
36
|
+
|
|
37
|
+
| Name | What it does |
|
|
38
|
+
| --- | --- |
|
|
39
|
+
| `hex_to_rgb(value)` | Parses `#rrggbb`. |
|
|
40
|
+
| `snap_to_bits(color, bits=5)` | Rounds each channel to `bits` bits and back to 8, for console-style color depth. |
|
|
41
|
+
| `new_indexed(width, height, fill=0)` | A palette-mode image filled with one index. |
|
|
42
|
+
| `apply_palette(image, palette, *, transparency=0, size=256)` | Sets the palette, padded with black to `size` entries. `transparency` is a transparent index, a bytes object with one alpha per index, or `None`. |
|
|
43
|
+
| `save_indexed(image, palette, path, *, transparency=0, size=256)` | Applies the palette, creates parent folders and saves an indexed PNG. Returns the path. |
|
|
44
|
+
| `force_corner_transparent(image)` | Swaps the top-left pixel's color into index 0 and marks index 0 transparent. The picture looks the same. |
|
|
45
|
+
| `quantize_indexed(image, colors=16, *, transparent_corner=True)` | Adaptive palette reduction, optionally followed by `force_corner_transparent`. |
|
|
46
|
+
| `indexed_to_rgba(image, *, transparent_index=0)` | RGBA copy with one index made transparent. |
|
|
47
|
+
| `stamp_pattern(draw, pattern, x, y, color, *, scale=1, ink="1")` | Draws each `ink` character of a list of strings as a block. Works on indexed and RGB images. |
|
|
48
|
+
| `FONT_5X7` | Glyph table for letters, digits and common punctuation. |
|
|
49
|
+
| `draw_text(draw, text, x, y, color, *, font=FONT_5X7, spacing=6, scale=1)` | Draws upper-cased text, shows `?` for unknown characters, returns the advance in pixels. |
|
|
50
|
+
| `text_width(text, *, font=FONT_5X7, spacing=6, scale=1)` | Pixel width of a string. |
|
|
51
|
+
| `cut_corner_box(draw, box, fill, outline=None)` | Rectangle with its corner pixels cut off. |
|
|
52
|
+
| `Origin(draw, ox, oy)` | Offsets `point`, `line`, `rect`, `ellipse`, `polygon`, `pattern` and `text` by `(ox, oy)`. |
|
|
53
|
+
| `nearest_scale(image, factor)` | Whole-number nearest-neighbour upscale. |
|
|
54
|
+
| `paste_cell(sheet, tile, col, row, cell_w, cell_h)` | Pastes a tile into the top-left of a grid cell. |
|
|
55
|
+
| `build_sheet(tiles, cols, cell_w, cell_h, palette=None, *, fill=0, transparency=0, size=256)` | Packs tiles (images or `(name, image)` pairs) into a sheet and returns it with one metadata dict per tile. With a palette the sheet is indexed; without one it is RGBA. |
|
|
56
|
+
|
|
57
|
+
## Errors
|
|
58
|
+
|
|
59
|
+
All functions raise `ValueError` for bad input: an image that is not in palette mode where one is required, a palette larger than `size`, a tile bigger than its cell, an empty tile list, a scale or factor below 1, or a malformed hex color.
|
|
60
|
+
|
|
61
|
+
## License
|
|
62
|
+
|
|
63
|
+
MIT
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling>=1.25"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "uppercut-pixel-art-sheets"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Pillow helpers for indexed pixel-art sheets: palettes, pattern fills, a bitmap font and sheet packing."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.10"
|
|
11
|
+
license = "MIT"
|
|
12
|
+
authors = [{ name = "Uppercut Labs", email = "packages@uppercut-labs.com" }]
|
|
13
|
+
dependencies = ["Pillow>=10"]
|
|
14
|
+
keywords = ["pixel art", "sprite sheet", "indexed png", "palette", "pillow"]
|
|
15
|
+
classifiers = [
|
|
16
|
+
"Programming Language :: Python :: 3",
|
|
17
|
+
"Topic :: Multimedia :: Graphics",
|
|
18
|
+
"Typing :: Typed",
|
|
19
|
+
]
|
|
20
|
+
|
|
21
|
+
[project.urls]
|
|
22
|
+
Source = "https://github.com/uppercut-labs/py-kit/tree/main/packages/uppercut-pixel-art-sheets"
|
|
23
|
+
|
|
24
|
+
[tool.hatch.build.targets.wheel]
|
|
25
|
+
packages = ["src/uppercut_pixel_art_sheets"]
|
|
26
|
+
|
|
27
|
+
[tool.hatch.build.targets.sdist]
|
|
28
|
+
include = ["src", "tests", "README.md"]
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
"""Pillow helpers for indexed pixel-art sheets."""
|
|
2
|
+
|
|
3
|
+
from .draw import FONT_5X7, Origin, cut_corner_box, draw_text, stamp_pattern, text_width
|
|
4
|
+
from .palette import (
|
|
5
|
+
apply_palette,
|
|
6
|
+
force_corner_transparent,
|
|
7
|
+
hex_to_rgb,
|
|
8
|
+
indexed_to_rgba,
|
|
9
|
+
new_indexed,
|
|
10
|
+
quantize_indexed,
|
|
11
|
+
save_indexed,
|
|
12
|
+
snap_to_bits,
|
|
13
|
+
)
|
|
14
|
+
from .sheet import build_sheet, nearest_scale, paste_cell
|
|
15
|
+
|
|
16
|
+
__all__ = [
|
|
17
|
+
"FONT_5X7",
|
|
18
|
+
"Origin",
|
|
19
|
+
"apply_palette",
|
|
20
|
+
"build_sheet",
|
|
21
|
+
"cut_corner_box",
|
|
22
|
+
"draw_text",
|
|
23
|
+
"force_corner_transparent",
|
|
24
|
+
"hex_to_rgb",
|
|
25
|
+
"indexed_to_rgba",
|
|
26
|
+
"nearest_scale",
|
|
27
|
+
"new_indexed",
|
|
28
|
+
"paste_cell",
|
|
29
|
+
"quantize_indexed",
|
|
30
|
+
"save_indexed",
|
|
31
|
+
"snap_to_bits",
|
|
32
|
+
"stamp_pattern",
|
|
33
|
+
"text_width",
|
|
34
|
+
]
|
|
35
|
+
|
|
36
|
+
__version__ = "0.1.0"
|
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
"""Bitmap font, pattern stamping and offset drawing helpers."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Mapping, Sequence
|
|
6
|
+
|
|
7
|
+
from PIL import ImageDraw
|
|
8
|
+
|
|
9
|
+
Color = int | tuple[int, ...]
|
|
10
|
+
Pattern = Sequence[str]
|
|
11
|
+
|
|
12
|
+
# 5 wide, 7 tall glyphs. "1" is an inked pixel. Lowercase draws as uppercase.
|
|
13
|
+
FONT_5X7: Mapping[str, Pattern] = {
|
|
14
|
+
"A": ("01110", "10001", "10001", "11111", "10001", "10001", "10001"),
|
|
15
|
+
"B": ("11110", "10001", "10001", "11110", "10001", "10001", "11110"),
|
|
16
|
+
"C": ("01110", "10001", "10000", "10000", "10000", "10001", "01110"),
|
|
17
|
+
"D": ("11100", "10010", "10001", "10001", "10001", "10010", "11100"),
|
|
18
|
+
"E": ("11111", "10000", "10000", "11110", "10000", "10000", "11111"),
|
|
19
|
+
"F": ("11111", "10000", "10000", "11110", "10000", "10000", "10000"),
|
|
20
|
+
"G": ("01110", "10001", "10000", "10111", "10001", "10001", "01111"),
|
|
21
|
+
"H": ("10001", "10001", "10001", "11111", "10001", "10001", "10001"),
|
|
22
|
+
"I": ("01110", "00100", "00100", "00100", "00100", "00100", "01110"),
|
|
23
|
+
"J": ("00111", "00010", "00010", "00010", "00010", "10010", "01100"),
|
|
24
|
+
"K": ("10001", "10010", "10100", "11000", "10100", "10010", "10001"),
|
|
25
|
+
"L": ("10000", "10000", "10000", "10000", "10000", "10000", "11111"),
|
|
26
|
+
"M": ("10001", "11011", "10101", "10101", "10001", "10001", "10001"),
|
|
27
|
+
"N": ("10001", "11001", "10101", "10011", "10001", "10001", "10001"),
|
|
28
|
+
"O": ("01110", "10001", "10001", "10001", "10001", "10001", "01110"),
|
|
29
|
+
"P": ("11110", "10001", "10001", "11110", "10000", "10000", "10000"),
|
|
30
|
+
"Q": ("01110", "10001", "10001", "10001", "10101", "10010", "01101"),
|
|
31
|
+
"R": ("11110", "10001", "10001", "11110", "10100", "10010", "10001"),
|
|
32
|
+
"S": ("01111", "10000", "10000", "01110", "00001", "00001", "11110"),
|
|
33
|
+
"T": ("11111", "00100", "00100", "00100", "00100", "00100", "00100"),
|
|
34
|
+
"U": ("10001", "10001", "10001", "10001", "10001", "10001", "01110"),
|
|
35
|
+
"V": ("10001", "10001", "10001", "10001", "10001", "01010", "00100"),
|
|
36
|
+
"W": ("10001", "10001", "10001", "10101", "10101", "10101", "01010"),
|
|
37
|
+
"X": ("10001", "10001", "01010", "00100", "01010", "10001", "10001"),
|
|
38
|
+
"Y": ("10001", "10001", "01010", "00100", "00100", "00100", "00100"),
|
|
39
|
+
"Z": ("11111", "00001", "00010", "00100", "01000", "10000", "11111"),
|
|
40
|
+
"0": ("01110", "10001", "10011", "10101", "11001", "10001", "01110"),
|
|
41
|
+
"1": ("00100", "01100", "00100", "00100", "00100", "00100", "01110"),
|
|
42
|
+
"2": ("01110", "10001", "00001", "00110", "01000", "10000", "11111"),
|
|
43
|
+
"3": ("11110", "00001", "00001", "01110", "00001", "00001", "11110"),
|
|
44
|
+
"4": ("00010", "00110", "01010", "10010", "11111", "00010", "00010"),
|
|
45
|
+
"5": ("11111", "10000", "11110", "00001", "00001", "10001", "01110"),
|
|
46
|
+
"6": ("00110", "01000", "10000", "11110", "10001", "10001", "01110"),
|
|
47
|
+
"7": ("11111", "00001", "00010", "00100", "01000", "01000", "01000"),
|
|
48
|
+
"8": ("01110", "10001", "10001", "01110", "10001", "10001", "01110"),
|
|
49
|
+
"9": ("01110", "10001", "10001", "01111", "00001", "00010", "01100"),
|
|
50
|
+
" ": ("00000",) * 7,
|
|
51
|
+
".": ("00000", "00000", "00000", "00000", "00000", "01100", "01100"),
|
|
52
|
+
",": ("00000", "00000", "00000", "00000", "01100", "00100", "01000"),
|
|
53
|
+
":": ("00000", "01100", "01100", "00000", "01100", "01100", "00000"),
|
|
54
|
+
"!": ("00100", "00100", "00100", "00100", "00100", "00000", "00100"),
|
|
55
|
+
"?": ("01110", "10001", "00001", "00110", "00100", "00000", "00100"),
|
|
56
|
+
"-": ("00000", "00000", "00000", "11111", "00000", "00000", "00000"),
|
|
57
|
+
"+": ("00000", "00100", "00100", "11111", "00100", "00100", "00000"),
|
|
58
|
+
"=": ("00000", "00000", "11111", "00000", "11111", "00000", "00000"),
|
|
59
|
+
"/": ("00001", "00010", "00010", "00100", "01000", "01000", "10000"),
|
|
60
|
+
"<": ("00010", "00100", "01000", "10000", "01000", "00100", "00010"),
|
|
61
|
+
">": ("01000", "00100", "00010", "00001", "00010", "00100", "01000"),
|
|
62
|
+
"(": ("00010", "00100", "01000", "01000", "01000", "00100", "00010"),
|
|
63
|
+
")": ("01000", "00100", "00010", "00010", "00010", "00100", "01000"),
|
|
64
|
+
"'": ("00100", "00100", "01000", "00000", "00000", "00000", "00000"),
|
|
65
|
+
"#": ("01010", "01010", "11111", "01010", "11111", "01010", "01010"),
|
|
66
|
+
"%": ("11001", "11010", "00010", "00100", "01000", "01011", "10011"),
|
|
67
|
+
"_": ("00000", "00000", "00000", "00000", "00000", "00000", "11111"),
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def stamp_pattern(
|
|
72
|
+
draw: ImageDraw.ImageDraw,
|
|
73
|
+
pattern: Pattern,
|
|
74
|
+
x: int,
|
|
75
|
+
y: int,
|
|
76
|
+
color: Color,
|
|
77
|
+
*,
|
|
78
|
+
scale: int = 1,
|
|
79
|
+
ink: str = "1",
|
|
80
|
+
) -> None:
|
|
81
|
+
"""Draw every ``ink`` character of ``pattern`` as a ``scale`` by ``scale`` block at (x, y).
|
|
82
|
+
|
|
83
|
+
Works on indexed and RGB images; ``color`` is a palette index or a tuple.
|
|
84
|
+
"""
|
|
85
|
+
if scale < 1:
|
|
86
|
+
raise ValueError("scale must be at least 1")
|
|
87
|
+
for row, line in enumerate(pattern):
|
|
88
|
+
for col, ch in enumerate(line):
|
|
89
|
+
if ch == ink:
|
|
90
|
+
px, py = x + col * scale, y + row * scale
|
|
91
|
+
draw.rectangle((px, py, px + scale - 1, py + scale - 1), fill=color)
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def text_width(text: str, *, font: Mapping[str, Pattern] = FONT_5X7, spacing: int = 6, scale: int = 1) -> int:
|
|
95
|
+
"""Pixels used by ``text``, not counting the gap after the last glyph."""
|
|
96
|
+
if not text:
|
|
97
|
+
return 0
|
|
98
|
+
glyph_w = max(len(p[0]) for p in font.values())
|
|
99
|
+
return ((len(text) - 1) * spacing + glyph_w) * scale
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def draw_text(
|
|
103
|
+
draw: ImageDraw.ImageDraw,
|
|
104
|
+
text: str,
|
|
105
|
+
x: int,
|
|
106
|
+
y: int,
|
|
107
|
+
color: Color,
|
|
108
|
+
*,
|
|
109
|
+
font: Mapping[str, Pattern] = FONT_5X7,
|
|
110
|
+
spacing: int = 6,
|
|
111
|
+
scale: int = 1,
|
|
112
|
+
) -> int:
|
|
113
|
+
"""Draw ``text`` with a bitmap font and return the advance in pixels.
|
|
114
|
+
|
|
115
|
+
``spacing`` is the distance between glyph origins before scaling. Text is
|
|
116
|
+
upper-cased, and characters missing from the font draw as ``?``.
|
|
117
|
+
"""
|
|
118
|
+
fallback = font.get("?")
|
|
119
|
+
cursor = x
|
|
120
|
+
for ch in text.upper():
|
|
121
|
+
pattern = font.get(ch, fallback)
|
|
122
|
+
if pattern is not None:
|
|
123
|
+
stamp_pattern(draw, pattern, cursor, y, color, scale=scale)
|
|
124
|
+
cursor += spacing * scale
|
|
125
|
+
return cursor - x
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def cut_corner_box(
|
|
129
|
+
draw: ImageDraw.ImageDraw,
|
|
130
|
+
box: tuple[int, int, int, int],
|
|
131
|
+
fill: Color,
|
|
132
|
+
outline: Color | None = None,
|
|
133
|
+
) -> None:
|
|
134
|
+
"""Draw a rectangle with its four corner pixels cut off. ``box`` is inclusive (x0, y0, x1, y1)."""
|
|
135
|
+
x0, y0, x1, y1 = box
|
|
136
|
+
if x1 - x0 < 2 or y1 - y0 < 2:
|
|
137
|
+
raise ValueError("box must be at least 3 pixels in each direction")
|
|
138
|
+
poly = [(x0 + 1, y0), (x1 - 1, y0), (x1, y0 + 1), (x1, y1 - 1),
|
|
139
|
+
(x1 - 1, y1), (x0 + 1, y1), (x0, y1 - 1), (x0, y0 + 1)]
|
|
140
|
+
draw.polygon(poly, fill=fill)
|
|
141
|
+
if outline is not None:
|
|
142
|
+
draw.line([*poly, poly[0]], fill=outline, width=1)
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
class Origin:
|
|
146
|
+
"""Drawing calls that add an offset ``(ox, oy)``, so a tile can be drawn in its own coordinates."""
|
|
147
|
+
|
|
148
|
+
def __init__(self, draw: ImageDraw.ImageDraw, ox: int = 0, oy: int = 0) -> None:
|
|
149
|
+
self.draw, self.ox, self.oy = draw, ox, oy
|
|
150
|
+
|
|
151
|
+
def _pt(self, p: tuple[int, int]) -> tuple[int, int]:
|
|
152
|
+
return (p[0] + self.ox, p[1] + self.oy)
|
|
153
|
+
|
|
154
|
+
def _box(self, b: Sequence[int]) -> tuple[int, int, int, int]:
|
|
155
|
+
return (b[0] + self.ox, b[1] + self.oy, b[2] + self.ox, b[3] + self.oy)
|
|
156
|
+
|
|
157
|
+
def point(self, p: tuple[int, int], fill: Color) -> None:
|
|
158
|
+
self.draw.point(self._pt(p), fill=fill)
|
|
159
|
+
|
|
160
|
+
def line(self, points: Sequence[tuple[int, int]], fill: Color, width: int = 1) -> None:
|
|
161
|
+
self.draw.line([self._pt(p) for p in points], fill=fill, width=width)
|
|
162
|
+
|
|
163
|
+
def rect(self, box: Sequence[int], fill: Color | None = None, outline: Color | None = None) -> None:
|
|
164
|
+
self.draw.rectangle(self._box(box), fill=fill, outline=outline)
|
|
165
|
+
|
|
166
|
+
def ellipse(self, box: Sequence[int], fill: Color | None = None, outline: Color | None = None) -> None:
|
|
167
|
+
self.draw.ellipse(self._box(box), fill=fill, outline=outline)
|
|
168
|
+
|
|
169
|
+
def polygon(self, points: Sequence[tuple[int, int]], fill: Color | None = None, outline: Color | None = None) -> None:
|
|
170
|
+
self.draw.polygon([self._pt(p) for p in points], fill=fill, outline=outline)
|
|
171
|
+
|
|
172
|
+
def pattern(self, pattern: Pattern, x: int, y: int, color: Color, *, scale: int = 1) -> None:
|
|
173
|
+
stamp_pattern(self.draw, pattern, x + self.ox, y + self.oy, color, scale=scale)
|
|
174
|
+
|
|
175
|
+
def text(self, text: str, x: int, y: int, color: Color, *, spacing: int = 6, scale: int = 1) -> int:
|
|
176
|
+
return draw_text(self.draw, text, x + self.ox, y + self.oy, color, spacing=spacing, scale=scale)
|
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
"""Palettes and indexed-image helpers."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import os
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
from typing import Sequence
|
|
8
|
+
|
|
9
|
+
from PIL import Image
|
|
10
|
+
|
|
11
|
+
RGB = tuple[int, int, int]
|
|
12
|
+
Transparency = int | bytes | Sequence[int] | None
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def hex_to_rgb(value: str) -> RGB:
|
|
16
|
+
"""Parse ``#rrggbb`` or ``rrggbb``."""
|
|
17
|
+
text = value.strip().lstrip("#")
|
|
18
|
+
if len(text) != 6:
|
|
19
|
+
raise ValueError(f"expected a 6 digit hex color, got {value!r}")
|
|
20
|
+
try:
|
|
21
|
+
return (int(text[0:2], 16), int(text[2:4], 16), int(text[4:6], 16))
|
|
22
|
+
except ValueError:
|
|
23
|
+
raise ValueError(f"not a hex color: {value!r}") from None
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def snap_to_bits(color: RGB, bits: int = 5) -> RGB:
|
|
27
|
+
"""Round each channel to ``bits`` bits and scale back to 8 bits.
|
|
28
|
+
|
|
29
|
+
``bits=5`` gives the 15-bit color of many handheld consoles.
|
|
30
|
+
"""
|
|
31
|
+
if not 1 <= bits <= 8:
|
|
32
|
+
raise ValueError("bits must be between 1 and 8")
|
|
33
|
+
top = (1 << bits) - 1
|
|
34
|
+
|
|
35
|
+
def one(v: int) -> int:
|
|
36
|
+
level = round(max(0, min(255, v)) * top / 255)
|
|
37
|
+
return round(level * 255 / top)
|
|
38
|
+
|
|
39
|
+
return (one(color[0]), one(color[1]), one(color[2]))
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def new_indexed(width: int, height: int, fill: int = 0) -> Image.Image:
|
|
43
|
+
"""A palette-mode image filled with palette index ``fill``."""
|
|
44
|
+
if not 0 <= fill <= 255:
|
|
45
|
+
raise ValueError("fill must be a palette index from 0 to 255")
|
|
46
|
+
return Image.new("P", (width, height), fill)
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def _flat_palette(palette: Sequence[RGB], size: int) -> list[int]:
|
|
50
|
+
if len(palette) > size:
|
|
51
|
+
raise ValueError(f"palette has {len(palette)} colors, more than size={size}")
|
|
52
|
+
if not 1 <= size <= 256:
|
|
53
|
+
raise ValueError("size must be between 1 and 256")
|
|
54
|
+
flat = [c for color in palette for c in color]
|
|
55
|
+
return flat + [0] * (size * 3 - len(flat))
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def apply_palette(
|
|
59
|
+
image: Image.Image,
|
|
60
|
+
palette: Sequence[RGB],
|
|
61
|
+
*,
|
|
62
|
+
transparency: Transparency = 0,
|
|
63
|
+
size: int = 256,
|
|
64
|
+
) -> Image.Image:
|
|
65
|
+
"""Set ``palette`` on a palette-mode image and return it.
|
|
66
|
+
|
|
67
|
+
Unused entries up to ``size`` are filled with black. ``transparency`` is a
|
|
68
|
+
palette index that saves as fully transparent (default 0), a bytes object
|
|
69
|
+
with one alpha value per index, or None for an opaque image.
|
|
70
|
+
"""
|
|
71
|
+
if image.mode != "P":
|
|
72
|
+
raise ValueError(f"image must be in P mode, got {image.mode}")
|
|
73
|
+
image.putpalette(_flat_palette(palette, size))
|
|
74
|
+
if transparency is None:
|
|
75
|
+
image.info.pop("transparency", None)
|
|
76
|
+
else:
|
|
77
|
+
image.info["transparency"] = transparency if isinstance(transparency, int) else bytes(transparency)
|
|
78
|
+
return image
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def save_indexed(
|
|
82
|
+
image: Image.Image,
|
|
83
|
+
palette: Sequence[RGB],
|
|
84
|
+
path: str | os.PathLike[str],
|
|
85
|
+
*,
|
|
86
|
+
transparency: Transparency = 0,
|
|
87
|
+
size: int = 256,
|
|
88
|
+
) -> Path:
|
|
89
|
+
"""Apply ``palette`` and save as an indexed PNG, creating parent folders."""
|
|
90
|
+
out = Path(path)
|
|
91
|
+
out.parent.mkdir(parents=True, exist_ok=True)
|
|
92
|
+
apply_palette(image, palette, transparency=transparency, size=size)
|
|
93
|
+
image.save(out, optimize=False)
|
|
94
|
+
return out
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def force_corner_transparent(image: Image.Image) -> Image.Image:
|
|
98
|
+
"""Make the top-left pixel's color palette index 0 and mark index 0 transparent.
|
|
99
|
+
|
|
100
|
+
The old index 0 and the corner index swap places in both the pixels and
|
|
101
|
+
the palette, so the picture looks the same.
|
|
102
|
+
"""
|
|
103
|
+
if image.mode != "P":
|
|
104
|
+
raise ValueError(f"image must be in P mode, got {image.mode}")
|
|
105
|
+
corner = image.getpixel((0, 0))
|
|
106
|
+
if corner != 0:
|
|
107
|
+
lut = list(range(256))
|
|
108
|
+
lut[0], lut[corner] = corner, 0
|
|
109
|
+
palette = image.getpalette() or []
|
|
110
|
+
palette = palette + [0] * (768 - len(palette))
|
|
111
|
+
swapped = palette[:]
|
|
112
|
+
swapped[0:3], swapped[corner * 3:corner * 3 + 3] = palette[corner * 3:corner * 3 + 3], palette[0:3]
|
|
113
|
+
image = image.point(lut)
|
|
114
|
+
image.putpalette(swapped)
|
|
115
|
+
image.info["transparency"] = 0
|
|
116
|
+
return image
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def quantize_indexed(image: Image.Image, colors: int = 16, *, transparent_corner: bool = True) -> Image.Image:
|
|
120
|
+
"""Reduce an image to an adaptive palette of ``colors`` entries.
|
|
121
|
+
|
|
122
|
+
With ``transparent_corner`` the corner color becomes index 0 and
|
|
123
|
+
transparent, which suits sprites drawn on a flat background.
|
|
124
|
+
"""
|
|
125
|
+
if not 2 <= colors <= 256:
|
|
126
|
+
raise ValueError("colors must be between 2 and 256")
|
|
127
|
+
indexed = image.convert("RGB").convert("P", palette=Image.Palette.ADAPTIVE, colors=colors)
|
|
128
|
+
return force_corner_transparent(indexed) if transparent_corner else indexed
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def indexed_to_rgba(image: Image.Image, *, transparent_index: int | None = 0) -> Image.Image:
|
|
132
|
+
"""Convert a palette-mode image to RGBA, making ``transparent_index`` fully transparent."""
|
|
133
|
+
if image.mode != "P":
|
|
134
|
+
raise ValueError(f"image must be in P mode, got {image.mode}")
|
|
135
|
+
rgba = image.convert("RGB").convert("RGBA")
|
|
136
|
+
if transparent_index is not None:
|
|
137
|
+
mask = image.point(lambda v: 0 if v == transparent_index else 255, "L")
|
|
138
|
+
rgba.putalpha(mask)
|
|
139
|
+
return rgba
|
|
File without changes
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
"""Packing cells into sheets and scaling."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Any, Sequence
|
|
6
|
+
|
|
7
|
+
from PIL import Image
|
|
8
|
+
|
|
9
|
+
from .palette import RGB, apply_palette, Transparency
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def nearest_scale(image: Image.Image, factor: int) -> Image.Image:
|
|
13
|
+
"""Scale up by a whole number with nearest-neighbour sampling."""
|
|
14
|
+
if factor < 1:
|
|
15
|
+
raise ValueError("factor must be at least 1")
|
|
16
|
+
return image.resize((image.width * factor, image.height * factor), Image.Resampling.NEAREST)
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def paste_cell(sheet: Image.Image, tile: Image.Image, col: int, row: int, cell_w: int, cell_h: int) -> None:
|
|
20
|
+
"""Paste ``tile`` into grid cell (``col``, ``row``) of a sheet made of ``cell_w`` by ``cell_h`` cells.
|
|
21
|
+
|
|
22
|
+
The tile goes in the top-left of the cell. It must fit inside the cell and
|
|
23
|
+
the cell must lie inside the sheet.
|
|
24
|
+
"""
|
|
25
|
+
if col < 0 or row < 0:
|
|
26
|
+
raise ValueError("col and row must not be negative")
|
|
27
|
+
if tile.width > cell_w or tile.height > cell_h:
|
|
28
|
+
raise ValueError(f"tile {tile.size} is larger than the {cell_w}x{cell_h} cell")
|
|
29
|
+
x, y = col * cell_w, row * cell_h
|
|
30
|
+
if x + cell_w > sheet.width or y + cell_h > sheet.height:
|
|
31
|
+
raise ValueError("cell lies outside the sheet")
|
|
32
|
+
sheet.paste(tile, (x, y))
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def build_sheet(
|
|
36
|
+
tiles: Sequence[Image.Image | tuple[str, Image.Image]],
|
|
37
|
+
cols: int,
|
|
38
|
+
cell_w: int,
|
|
39
|
+
cell_h: int,
|
|
40
|
+
palette: Sequence[RGB] | None = None,
|
|
41
|
+
*,
|
|
42
|
+
fill: int = 0,
|
|
43
|
+
transparency: Transparency = 0,
|
|
44
|
+
size: int = 256,
|
|
45
|
+
) -> tuple[Image.Image, list[dict[str, Any]]]:
|
|
46
|
+
"""Pack tiles left to right, top to bottom into one sheet.
|
|
47
|
+
|
|
48
|
+
Each tile is an image or a ``(name, image)`` pair. With a ``palette`` the
|
|
49
|
+
sheet is an indexed image with that palette applied (tiles must then be
|
|
50
|
+
palette-mode images that share it). Without one the sheet is RGBA.
|
|
51
|
+
Returns the sheet and one metadata dict per tile with ``index``, ``name``,
|
|
52
|
+
``col``, ``row``, ``x``, ``y``, ``w`` and ``h``.
|
|
53
|
+
"""
|
|
54
|
+
if cols < 1:
|
|
55
|
+
raise ValueError("cols must be at least 1")
|
|
56
|
+
if not tiles:
|
|
57
|
+
raise ValueError("no tiles to pack")
|
|
58
|
+
rows = (len(tiles) + cols - 1) // cols
|
|
59
|
+
if palette is not None:
|
|
60
|
+
sheet = Image.new("P", (cols * cell_w, rows * cell_h), fill)
|
|
61
|
+
apply_palette(sheet, palette, transparency=transparency, size=size)
|
|
62
|
+
else:
|
|
63
|
+
sheet = Image.new("RGBA", (cols * cell_w, rows * cell_h), (0, 0, 0, 0))
|
|
64
|
+
meta: list[dict[str, Any]] = []
|
|
65
|
+
for i, item in enumerate(tiles):
|
|
66
|
+
name, tile = item if isinstance(item, tuple) else (f"tile_{i:03d}", item)
|
|
67
|
+
col, row = i % cols, i // cols
|
|
68
|
+
if palette is not None and tile.mode != "P":
|
|
69
|
+
raise ValueError(f"tile {name!r} must be in P mode when a palette is given")
|
|
70
|
+
paste_cell(sheet, tile, col, row, cell_w, cell_h)
|
|
71
|
+
meta.append({"index": i, "name": name, "col": col, "row": row,
|
|
72
|
+
"x": col * cell_w, "y": row * cell_h, "w": tile.width, "h": tile.height})
|
|
73
|
+
return sheet, meta
|
|
@@ -0,0 +1,253 @@
|
|
|
1
|
+
import pytest
|
|
2
|
+
from PIL import Image, ImageDraw
|
|
3
|
+
|
|
4
|
+
from uppercut_pixel_art_sheets import (
|
|
5
|
+
FONT_5X7,
|
|
6
|
+
Origin,
|
|
7
|
+
apply_palette,
|
|
8
|
+
build_sheet,
|
|
9
|
+
cut_corner_box,
|
|
10
|
+
draw_text,
|
|
11
|
+
force_corner_transparent,
|
|
12
|
+
hex_to_rgb,
|
|
13
|
+
indexed_to_rgba,
|
|
14
|
+
nearest_scale,
|
|
15
|
+
new_indexed,
|
|
16
|
+
paste_cell,
|
|
17
|
+
quantize_indexed,
|
|
18
|
+
save_indexed,
|
|
19
|
+
snap_to_bits,
|
|
20
|
+
stamp_pattern,
|
|
21
|
+
text_width,
|
|
22
|
+
)
|
|
23
|
+
|
|
24
|
+
PAL = [(0, 0, 0), (255, 0, 0), (0, 255, 0), (0, 0, 255)]
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def test_hex_to_rgb():
|
|
28
|
+
assert hex_to_rgb("#ff8000") == (255, 128, 0)
|
|
29
|
+
assert hex_to_rgb("00ff00") == (0, 255, 0)
|
|
30
|
+
with pytest.raises(ValueError):
|
|
31
|
+
hex_to_rgb("#fff")
|
|
32
|
+
with pytest.raises(ValueError):
|
|
33
|
+
hex_to_rgb("#gggggg")
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def test_snap_to_bits():
|
|
37
|
+
assert snap_to_bits((0, 255, 128)) == (0, 255, 132)
|
|
38
|
+
assert snap_to_bits((10, 10, 10), bits=1) == (0, 0, 0)
|
|
39
|
+
assert snap_to_bits((300, -5, 200), bits=8) == (255, 0, 200)
|
|
40
|
+
with pytest.raises(ValueError):
|
|
41
|
+
snap_to_bits((1, 2, 3), bits=0)
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def test_new_indexed_and_apply_palette():
|
|
45
|
+
im = new_indexed(4, 3, fill=2)
|
|
46
|
+
assert im.mode == "P" and im.size == (4, 3) and im.getpixel((0, 0)) == 2
|
|
47
|
+
apply_palette(im, PAL)
|
|
48
|
+
assert im.getpalette()[:12] == [0, 0, 0, 255, 0, 0, 0, 255, 0, 0, 0, 255]
|
|
49
|
+
assert len(im.getpalette()) == 768
|
|
50
|
+
assert im.info["transparency"] == 0
|
|
51
|
+
apply_palette(im, PAL, transparency=None)
|
|
52
|
+
assert "transparency" not in im.info
|
|
53
|
+
apply_palette(im, PAL, transparency=bytes([0, 128, 255, 255]), size=16)
|
|
54
|
+
assert im.info["transparency"] == bytes([0, 128, 255, 255])
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def test_apply_palette_errors():
|
|
58
|
+
with pytest.raises(ValueError):
|
|
59
|
+
new_indexed(2, 2, fill=300)
|
|
60
|
+
with pytest.raises(ValueError):
|
|
61
|
+
apply_palette(Image.new("RGB", (2, 2)), PAL)
|
|
62
|
+
with pytest.raises(ValueError):
|
|
63
|
+
apply_palette(new_indexed(2, 2), PAL, size=2)
|
|
64
|
+
with pytest.raises(ValueError):
|
|
65
|
+
apply_palette(new_indexed(2, 2), PAL, size=0)
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def test_save_indexed_roundtrip(tmp_path):
|
|
69
|
+
im = new_indexed(4, 4)
|
|
70
|
+
ImageDraw.Draw(im).rectangle((1, 1, 2, 2), fill=1)
|
|
71
|
+
out = save_indexed(im, PAL, tmp_path / "deep" / "a.png", size=16)
|
|
72
|
+
back = Image.open(out)
|
|
73
|
+
assert back.mode == "P"
|
|
74
|
+
assert back.getpixel((1, 1)) == 1 and back.getpixel((0, 0)) == 0
|
|
75
|
+
assert back.info["transparency"] == 0
|
|
76
|
+
assert back.convert("RGBA").getpixel((0, 0))[3] == 0
|
|
77
|
+
assert back.convert("RGBA").getpixel((1, 1)) == (255, 0, 0, 255)
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def test_force_corner_transparent_swaps_and_keeps_look():
|
|
81
|
+
im = new_indexed(3, 1)
|
|
82
|
+
apply_palette(im, PAL, transparency=None)
|
|
83
|
+
im.putpixel((0, 0), 3) # corner is blue
|
|
84
|
+
im.putpixel((1, 0), 0) # black
|
|
85
|
+
im.putpixel((2, 0), 1) # red
|
|
86
|
+
before = im.convert("RGB").tobytes()
|
|
87
|
+
out = force_corner_transparent(im)
|
|
88
|
+
assert out.getpixel((0, 0)) == 0
|
|
89
|
+
assert out.getpalette()[:3] == [0, 0, 255]
|
|
90
|
+
assert out.info["transparency"] == 0
|
|
91
|
+
assert out.convert("RGB").tobytes() == before
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def test_force_corner_transparent_already_zero_and_rgb_rejected():
|
|
95
|
+
im = apply_palette(new_indexed(2, 2), PAL, transparency=None)
|
|
96
|
+
assert force_corner_transparent(im).info["transparency"] == 0
|
|
97
|
+
with pytest.raises(ValueError):
|
|
98
|
+
force_corner_transparent(Image.new("RGB", (2, 2)))
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def test_quantize_indexed():
|
|
102
|
+
src = Image.new("RGB", (8, 8), (10, 200, 10))
|
|
103
|
+
ImageDraw.Draw(src).rectangle((2, 2, 5, 5), fill=(250, 10, 10))
|
|
104
|
+
out = quantize_indexed(src, 4)
|
|
105
|
+
assert out.mode == "P" and out.getpixel((0, 0)) == 0 and out.info["transparency"] == 0
|
|
106
|
+
assert out.getpixel((3, 3)) != 0
|
|
107
|
+
plain = quantize_indexed(src, 4, transparent_corner=False)
|
|
108
|
+
assert "transparency" not in plain.info
|
|
109
|
+
with pytest.raises(ValueError):
|
|
110
|
+
quantize_indexed(src, 1)
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def test_indexed_to_rgba():
|
|
114
|
+
im = apply_palette(new_indexed(2, 1), PAL, transparency=None)
|
|
115
|
+
im.putpixel((1, 0), 1)
|
|
116
|
+
rgba = indexed_to_rgba(im)
|
|
117
|
+
assert rgba.getpixel((0, 0))[3] == 0 and rgba.getpixel((1, 0)) == (255, 0, 0, 255)
|
|
118
|
+
opaque = indexed_to_rgba(im, transparent_index=None)
|
|
119
|
+
assert opaque.getpixel((0, 0))[3] == 255
|
|
120
|
+
with pytest.raises(ValueError):
|
|
121
|
+
indexed_to_rgba(Image.new("RGB", (1, 1)))
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def test_stamp_pattern_and_scale():
|
|
125
|
+
im = new_indexed(8, 8)
|
|
126
|
+
d = ImageDraw.Draw(im)
|
|
127
|
+
stamp_pattern(d, ("10", "01"), 1, 1, 3)
|
|
128
|
+
assert im.getpixel((1, 1)) == 3 and im.getpixel((2, 2)) == 3 and im.getpixel((2, 1)) == 0
|
|
129
|
+
big = new_indexed(8, 8)
|
|
130
|
+
stamp_pattern(ImageDraw.Draw(big), ("1",), 2, 2, 1, scale=3)
|
|
131
|
+
assert {big.getpixel((x, y)) for x in range(2, 5) for y in range(2, 5)} == {1}
|
|
132
|
+
assert big.getpixel((5, 5)) == 0
|
|
133
|
+
custom = new_indexed(4, 4)
|
|
134
|
+
stamp_pattern(ImageDraw.Draw(custom), ("#.",), 0, 0, 2, ink="#")
|
|
135
|
+
assert custom.getpixel((0, 0)) == 2 and custom.getpixel((1, 0)) == 0
|
|
136
|
+
with pytest.raises(ValueError):
|
|
137
|
+
stamp_pattern(ImageDraw.Draw(custom), ("1",), 0, 0, 1, scale=0)
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def test_font_is_complete_and_rectangular():
|
|
141
|
+
assert all(len(p) == 7 and all(len(r) == 5 for r in p) for p in FONT_5X7.values())
|
|
142
|
+
for ch in "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 .:?!-":
|
|
143
|
+
assert ch in FONT_5X7
|
|
144
|
+
assert len({FONT_5X7[c] for c in "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"}) == 36
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def test_draw_text_indexed_and_rgb():
|
|
148
|
+
im = new_indexed(40, 10)
|
|
149
|
+
adv = draw_text(ImageDraw.Draw(im), "ab", 1, 1, 2)
|
|
150
|
+
assert adv == 12
|
|
151
|
+
assert 2 in set(im.tobytes())
|
|
152
|
+
assert im.getpixel((0, 0)) == 0
|
|
153
|
+
rgb = Image.new("RGB", (60, 20))
|
|
154
|
+
adv2 = draw_text(ImageDraw.Draw(rgb), "A", 0, 0, (255, 0, 0), scale=2, spacing=6)
|
|
155
|
+
assert adv2 == 12
|
|
156
|
+
assert rgb.getpixel((2, 0)) == (255, 0, 0) and rgb.getpixel((3, 1)) == (255, 0, 0) # top bar of A, scaled
|
|
157
|
+
assert rgb.getpixel((0, 0)) == (0, 0, 0)
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def test_draw_text_unknown_char_draws_question_mark_and_case_folds():
|
|
161
|
+
a, b = new_indexed(20, 10), new_indexed(20, 10)
|
|
162
|
+
draw_text(ImageDraw.Draw(a), "☃", 0, 0, 1)
|
|
163
|
+
draw_text(ImageDraw.Draw(b), "?", 0, 0, 1)
|
|
164
|
+
assert a.tobytes() == b.tobytes()
|
|
165
|
+
c, d = new_indexed(20, 10), new_indexed(20, 10)
|
|
166
|
+
draw_text(ImageDraw.Draw(c), "q", 0, 0, 1)
|
|
167
|
+
draw_text(ImageDraw.Draw(d), "Q", 0, 0, 1)
|
|
168
|
+
assert c.tobytes() == d.tobytes()
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def test_text_width():
|
|
172
|
+
assert text_width("") == 0
|
|
173
|
+
assert text_width("A") == 5
|
|
174
|
+
assert text_width("ABC") == 17
|
|
175
|
+
assert text_width("ABC", scale=2, spacing=7) == (14 + 5) * 2
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
def test_cut_corner_box():
|
|
179
|
+
im = new_indexed(10, 10)
|
|
180
|
+
cut_corner_box(ImageDraw.Draw(im), (1, 1, 8, 8), 2, outline=3)
|
|
181
|
+
assert im.getpixel((1, 1)) == 0 # corner cut
|
|
182
|
+
assert im.getpixel((2, 1)) == 3 and im.getpixel((4, 4)) == 2
|
|
183
|
+
with pytest.raises(ValueError):
|
|
184
|
+
cut_corner_box(ImageDraw.Draw(im), (1, 1, 2, 8), 2)
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
def test_origin_offsets_every_call():
|
|
188
|
+
im = new_indexed(20, 20)
|
|
189
|
+
o = Origin(ImageDraw.Draw(im), 10, 5)
|
|
190
|
+
o.point((0, 0), 1)
|
|
191
|
+
o.rect((1, 1, 2, 2), fill=2)
|
|
192
|
+
o.line([(0, 5), (3, 5)], fill=3)
|
|
193
|
+
o.ellipse((4, 8, 6, 10), fill=1)
|
|
194
|
+
o.polygon([(8, 0), (9, 0), (9, 1)], fill=2)
|
|
195
|
+
o.pattern(("1",), 5, 5, 3)
|
|
196
|
+
assert o.text("A", 0, 10, 1) == 6
|
|
197
|
+
assert im.getpixel((10, 5)) == 1
|
|
198
|
+
assert im.getpixel((11, 6)) == 2
|
|
199
|
+
assert im.getpixel((11, 10)) == 3
|
|
200
|
+
assert im.getpixel((15, 10)) == 3
|
|
201
|
+
assert im.getpixel((0, 0)) == 0
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
def test_nearest_scale():
|
|
205
|
+
im = Image.new("RGB", (2, 1))
|
|
206
|
+
im.putpixel((0, 0), (255, 0, 0))
|
|
207
|
+
im.putpixel((1, 0), (0, 0, 255))
|
|
208
|
+
big = nearest_scale(im, 3)
|
|
209
|
+
assert big.size == (6, 3)
|
|
210
|
+
assert big.getpixel((2, 2)) == (255, 0, 0) and big.getpixel((3, 0)) == (0, 0, 255)
|
|
211
|
+
with pytest.raises(ValueError):
|
|
212
|
+
nearest_scale(im, 0)
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
def test_paste_cell_and_errors():
|
|
216
|
+
sheet = Image.new("RGB", (20, 10))
|
|
217
|
+
paste_cell(sheet, Image.new("RGB", (4, 4), "white"), 1, 0, 10, 10)
|
|
218
|
+
assert sheet.getpixel((10, 0)) == (255, 255, 255) and sheet.getpixel((14, 0)) == (0, 0, 0)
|
|
219
|
+
with pytest.raises(ValueError):
|
|
220
|
+
paste_cell(sheet, Image.new("RGB", (11, 4)), 0, 0, 10, 10)
|
|
221
|
+
with pytest.raises(ValueError):
|
|
222
|
+
paste_cell(sheet, Image.new("RGB", (4, 4)), 2, 0, 10, 10)
|
|
223
|
+
with pytest.raises(ValueError):
|
|
224
|
+
paste_cell(sheet, Image.new("RGB", (4, 4)), -1, 0, 10, 10)
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
def test_build_sheet_indexed_with_metadata(tmp_path):
|
|
228
|
+
def cell(color):
|
|
229
|
+
im = new_indexed(4, 4, color)
|
|
230
|
+
return im
|
|
231
|
+
|
|
232
|
+
tiles = [("a", cell(1)), ("b", cell(2)), cell(3)]
|
|
233
|
+
sheet, meta = build_sheet(tiles, 2, 4, 4, PAL, size=16)
|
|
234
|
+
assert sheet.mode == "P" and sheet.size == (8, 8)
|
|
235
|
+
assert sheet.getpixel((0, 0)) == 1 and sheet.getpixel((4, 0)) == 2 and sheet.getpixel((0, 4)) == 3
|
|
236
|
+
assert sheet.getpixel((7, 7)) == 0
|
|
237
|
+
assert [m["name"] for m in meta] == ["a", "b", "tile_002"]
|
|
238
|
+
assert meta[2] == {"index": 2, "name": "tile_002", "col": 0, "row": 1, "x": 0, "y": 4, "w": 4, "h": 4}
|
|
239
|
+
out = save_indexed(sheet, PAL, tmp_path / "s.png", size=16)
|
|
240
|
+
assert Image.open(out).getpixel((4, 0)) == 2
|
|
241
|
+
|
|
242
|
+
|
|
243
|
+
def test_build_sheet_rgba_and_errors():
|
|
244
|
+
sheet, meta = build_sheet([Image.new("RGBA", (2, 2), (9, 9, 9, 255))], 3, 2, 2)
|
|
245
|
+
assert sheet.mode == "RGBA" and sheet.size == (6, 2) and len(meta) == 1
|
|
246
|
+
with pytest.raises(ValueError):
|
|
247
|
+
build_sheet([], 2, 4, 4)
|
|
248
|
+
with pytest.raises(ValueError):
|
|
249
|
+
build_sheet([new_indexed(2, 2)], 0, 4, 4)
|
|
250
|
+
with pytest.raises(ValueError):
|
|
251
|
+
build_sheet([Image.new("RGB", (2, 2))], 1, 4, 4, PAL)
|
|
252
|
+
with pytest.raises(ValueError):
|
|
253
|
+
build_sheet([new_indexed(5, 2)], 1, 4, 4, PAL)
|