nanohex 2.0.1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,34 @@
1
+ # Changelog
2
+
3
+ ## [2.0.1] - 2026-12-05
4
+
5
+ ### Fixed
6
+ - Fixed image encoding on Pillow versions that do not provide `Image.get_flattened_data()`.
7
+ - Read indexed pixel data through `Image.tobytes()`, which is compatible with the supported Pillow API.
8
+ - Updated automated tests to avoid the same unsupported image-data method.
9
+ - Removed generated build artifacts from the release source archive.
10
+
11
+
12
+ ## [2.0.0] - 2026-11-16
13
+
14
+ ### Added
15
+ - Installable Python project metadata and `nanohex` command entry point.
16
+ - Dedicated NHX v2 format specification.
17
+ - Unified command-line interface for image encoding and decoding.
18
+ - Configurable dimensions, palette size, and decode scaling.
19
+ - Strict NHX structure and pixel-data validation.
20
+ - White-background compositing for transparent source images.
21
+ - Automated tests for round trips, sample-file decoding, scaling, malformed input, and legacy uncompressed rows.
22
+ - Formal format specification and compatibility notes in the README.
23
+
24
+ ### Fixed
25
+ - Corrected palette extraction so only palette entries actually referenced by image pixels are written.
26
+ - Removed the invalid `len(max_color)` palette-trimming operation.
27
+ - Replaced fragile section indexing and unchecked run expansion with validated parsing.
28
+ - Avoided crashes on empty data, invalid hexadecimal indices, missing sections, and inconsistent row dimensions.
29
+ - Decoder now saves an output image rather than relying on an interactive image viewer.
30
+
31
+ ### Compatibility
32
+ - Retains the original `@size`, `@palette`, and `@data` sections.
33
+ - Retains single-hex-digit palette indices and colon-separated `INDEX*COUNT` runs.
34
+ - Continues to accept legacy uncompressed hexadecimal pixel rows.
nanohex-2.0.1/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 NanoHex contributors
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,6 @@
1
+ include README.md
2
+ include LICENSE
3
+ include CHANGELOG.md
4
+ recursive-include docs *.md
5
+ recursive-include examples *.nhx
6
+ recursive-include tests *.py
nanohex-2.0.1/PKG-INFO ADDED
@@ -0,0 +1,162 @@
1
+ Metadata-Version: 2.4
2
+ Name: nanohex
3
+ Version: 2.0.1
4
+ Summary: A lightweight palette-based image format using hexadecimal pixel indices and row-wise run-length encoding
5
+ Author: Ashutosh Acharya
6
+ License: MIT License
7
+
8
+ Copyright (c) 2026 NanoHex contributors
9
+
10
+ Permission is hereby granted, free of charge, to any person obtaining a copy
11
+ of this software and associated documentation files (the "Software"), to deal
12
+ in the Software without restriction, including without limitation the rights
13
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
14
+ copies of the Software, and to permit persons to whom the Software is
15
+ furnished to do so, subject to the following conditions:
16
+
17
+ The above copyright notice and this permission notice shall be included in all
18
+ copies or substantial portions of the Software.
19
+
20
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
21
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
22
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
23
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
24
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
25
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
26
+ SOFTWARE.
27
+
28
+ Project-URL: Homepage, https://github.com/Ashutosh-377/NanoHex
29
+ Project-URL: Repository, https://github.com/Ashutosh-377/NanoHex
30
+ Project-URL: Issues, https://github.com/Ashutosh-377/NanoHex/issues
31
+ Keywords: image-format,image-encoding,image-decoding,rle,palette,pillow
32
+ Classifier: Development Status :: 4 - Beta
33
+ Classifier: Intended Audience :: Developers
34
+ Classifier: License :: OSI Approved :: MIT License
35
+ Classifier: Operating System :: OS Independent
36
+ Classifier: Programming Language :: Python :: 3
37
+ Classifier: Programming Language :: Python :: 3.10
38
+ Classifier: Programming Language :: Python :: 3.11
39
+ Classifier: Programming Language :: Python :: 3.12
40
+ Classifier: Programming Language :: Python :: 3.13
41
+ Classifier: Topic :: Multimedia :: Graphics
42
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
43
+ Requires-Python: >=3.10
44
+ Description-Content-Type: text/markdown
45
+ License-File: LICENSE
46
+ Requires-Dist: Pillow>=9.1.0
47
+ Dynamic: license-file
48
+
49
+ # NanoHex v2.0.1
50
+
51
+ NanoHex is a small palette-based raster image format. It stores a canvas size, a hexadecimal RGB palette, and pixel rows encoded with run-length encoding (RLE).
52
+
53
+ ## Features
54
+
55
+ - Configurable output dimensions (nearest-neighbour resizing).
56
+ - Adaptive palette quantisation with 1–16 colours.
57
+ - One hexadecimal digit per palette index.
58
+ - Row-wise RLE to represent repeated pixels compactly.
59
+ - Decoder validation for malformed sections, dimensions, colours, runs, and palette references.
60
+ - PNG (and other Pillow-supported image formats) input/output.
61
+ - Transparent input pixels are composited onto white; NHX v2 stores RGB colours only.
62
+
63
+ ## Requirements
64
+
65
+ - Python 3.10+
66
+ - Pillow 9.1+
67
+
68
+ Install NanoHex from PyPI:
69
+
70
+ ```bash
71
+ python -m pip install nanohex
72
+ ```
73
+
74
+ Alternatively, install from a source checkout:
75
+
76
+ ```bash
77
+ python -m pip install .
78
+ ```
79
+
80
+ ## Usage
81
+
82
+ Encode an image into a 32×32 NHX file using up to 16 colours:
83
+
84
+ ```bash
85
+ python -m pip install .
86
+ python -m nanohex encode input.png output.nhx
87
+ ```
88
+
89
+ Choose dimensions and palette size:
90
+
91
+ ```bash
92
+ python -m nanohex encode input.png output.nhx --width 64 --height 64 --colors 12
93
+ ```
94
+
95
+ Decode an NHX file:
96
+
97
+ ```bash
98
+ python -m nanohex decode output.nhx decoded.png
99
+ ```
100
+
101
+ Enlarge the decoded image by an integer factor using nearest-neighbour scaling:
102
+
103
+ ```bash
104
+ python -m nanohex decode output.nhx decoded.png --scale 10
105
+ ```
106
+
107
+ ## NHX file structure
108
+
109
+ An NHX file is UTF-8 text with three required sections, in any order:
110
+
111
+ ```text
112
+ @size
113
+ h=8
114
+ w=8
115
+
116
+ @palette
117
+ #FFFFFF
118
+ #000000
119
+ #af0000
120
+
121
+ @data
122
+ 0*8
123
+ 0*5:2*3
124
+ 1*3:2*5
125
+ ...
126
+ ```
127
+
128
+ ### `@size`
129
+
130
+ Defines positive integer canvas dimensions with `w` (width) and `h` (height). The decoder currently limits each dimension to 10,000 and the total canvas to 25 million pixels.
131
+
132
+ ### `@palette`
133
+
134
+ Contains 1–16 RGB colours in `#RRGGBB` notation. Palette entries are addressed by a single hexadecimal digit: `0`–`9`, `A`–`F`.
135
+
136
+ ### `@data`
137
+
138
+ Contains exactly `h` non-empty rows. Each row must expand to exactly `w` pixels. Runs use `INDEX*COUNT`, separated by colons. For example, `A*4:0*2` means four pixels using palette entry `A`, followed by two pixels using entry `0`.
139
+
140
+ For compatibility with earlier NanoHex files, rows containing an uncompressed sequence of hexadecimal indices are also accepted (for example, `0110`).
141
+
142
+ ## Compatibility and limitations
143
+
144
+ - v2.0.1 preserves the original `@size`, `@palette`, and `@data` layout and the original one-digit palette-index/RLE representation.
145
+ - Existing files using up to 16 palette entries and valid row data remain readable.
146
+ - Alpha/transparency is not represented in NHX; the encoder composites transparent pixels onto white.
147
+ - Animation, metadata, arbitrary colour profiles, and palettes larger than 16 colours are not supported.
148
+ - Encoding resizes to the requested dimensions before quantisation; decoding reconstructs the stored dimensions.
149
+
150
+ The full format definition is available in [docs/NHX_FORMAT.md](docs/NHX_FORMAT.md).
151
+
152
+ ## Tests
153
+
154
+ Run the test suite from the repository root:
155
+
156
+ ```bash
157
+ python -m unittest discover -s tests -v
158
+ ```
159
+
160
+ ## License
161
+
162
+ MIT. See [LICENSE](LICENSE).
@@ -0,0 +1,114 @@
1
+ # NanoHex v2.0.1
2
+
3
+ NanoHex is a small palette-based raster image format. It stores a canvas size, a hexadecimal RGB palette, and pixel rows encoded with run-length encoding (RLE).
4
+
5
+ ## Features
6
+
7
+ - Configurable output dimensions (nearest-neighbour resizing).
8
+ - Adaptive palette quantisation with 1–16 colours.
9
+ - One hexadecimal digit per palette index.
10
+ - Row-wise RLE to represent repeated pixels compactly.
11
+ - Decoder validation for malformed sections, dimensions, colours, runs, and palette references.
12
+ - PNG (and other Pillow-supported image formats) input/output.
13
+ - Transparent input pixels are composited onto white; NHX v2 stores RGB colours only.
14
+
15
+ ## Requirements
16
+
17
+ - Python 3.10+
18
+ - Pillow 9.1+
19
+
20
+ Install NanoHex from PyPI:
21
+
22
+ ```bash
23
+ python -m pip install nanohex
24
+ ```
25
+
26
+ Alternatively, install from a source checkout:
27
+
28
+ ```bash
29
+ python -m pip install .
30
+ ```
31
+
32
+ ## Usage
33
+
34
+ Encode an image into a 32×32 NHX file using up to 16 colours:
35
+
36
+ ```bash
37
+ python -m pip install .
38
+ python -m nanohex encode input.png output.nhx
39
+ ```
40
+
41
+ Choose dimensions and palette size:
42
+
43
+ ```bash
44
+ python -m nanohex encode input.png output.nhx --width 64 --height 64 --colors 12
45
+ ```
46
+
47
+ Decode an NHX file:
48
+
49
+ ```bash
50
+ python -m nanohex decode output.nhx decoded.png
51
+ ```
52
+
53
+ Enlarge the decoded image by an integer factor using nearest-neighbour scaling:
54
+
55
+ ```bash
56
+ python -m nanohex decode output.nhx decoded.png --scale 10
57
+ ```
58
+
59
+ ## NHX file structure
60
+
61
+ An NHX file is UTF-8 text with three required sections, in any order:
62
+
63
+ ```text
64
+ @size
65
+ h=8
66
+ w=8
67
+
68
+ @palette
69
+ #FFFFFF
70
+ #000000
71
+ #af0000
72
+
73
+ @data
74
+ 0*8
75
+ 0*5:2*3
76
+ 1*3:2*5
77
+ ...
78
+ ```
79
+
80
+ ### `@size`
81
+
82
+ Defines positive integer canvas dimensions with `w` (width) and `h` (height). The decoder currently limits each dimension to 10,000 and the total canvas to 25 million pixels.
83
+
84
+ ### `@palette`
85
+
86
+ Contains 1–16 RGB colours in `#RRGGBB` notation. Palette entries are addressed by a single hexadecimal digit: `0`–`9`, `A`–`F`.
87
+
88
+ ### `@data`
89
+
90
+ Contains exactly `h` non-empty rows. Each row must expand to exactly `w` pixels. Runs use `INDEX*COUNT`, separated by colons. For example, `A*4:0*2` means four pixels using palette entry `A`, followed by two pixels using entry `0`.
91
+
92
+ For compatibility with earlier NanoHex files, rows containing an uncompressed sequence of hexadecimal indices are also accepted (for example, `0110`).
93
+
94
+ ## Compatibility and limitations
95
+
96
+ - v2.0.1 preserves the original `@size`, `@palette`, and `@data` layout and the original one-digit palette-index/RLE representation.
97
+ - Existing files using up to 16 palette entries and valid row data remain readable.
98
+ - Alpha/transparency is not represented in NHX; the encoder composites transparent pixels onto white.
99
+ - Animation, metadata, arbitrary colour profiles, and palettes larger than 16 colours are not supported.
100
+ - Encoding resizes to the requested dimensions before quantisation; decoding reconstructs the stored dimensions.
101
+
102
+ The full format definition is available in [docs/NHX_FORMAT.md](docs/NHX_FORMAT.md).
103
+
104
+ ## Tests
105
+
106
+ Run the test suite from the repository root:
107
+
108
+ ```bash
109
+ python -m unittest discover -s tests -v
110
+ ```
111
+
112
+ ## License
113
+
114
+ MIT. See [LICENSE](LICENSE).
@@ -0,0 +1,51 @@
1
+ # NHX text format — version 2
2
+
3
+ This document specifies the text representation read and written by NanoHex 2.0.0.
4
+
5
+ ## Encoding model
6
+
7
+ An NHX image consists of a rectangular raster, an ordered RGB palette, and one row of palette indices per raster row. Each palette index is a single hexadecimal digit, so the format supports at most 16 palette entries.
8
+
9
+ ## Grammar
10
+
11
+ The file is UTF-8 text. The three section headers are mandatory and occur exactly once; section order is not significant. Blank lines are ignored.
12
+
13
+ ```text
14
+ @size
15
+ h=<positive integer>
16
+ w=<positive integer>
17
+
18
+ @palette
19
+ #RRGGBB
20
+ ...
21
+
22
+ @data
23
+ <row>
24
+ ...
25
+ ```
26
+
27
+ - `@size`: exactly one `h` and one `w` value.
28
+ - `@palette`: 1–16 six-digit RGB colours, each prefixed by `#`.
29
+ - `@data`: exactly `h` non-empty rows, each expanding to exactly `w` palette indices.
30
+
31
+ ## Pixel rows
32
+
33
+ A row is a colon-separated sequence of runs. A run is:
34
+
35
+ ```text
36
+ <hexadecimal palette index>*<positive decimal count>
37
+ ```
38
+
39
+ Example: `0*5:A*2:1*1` expands to `00000AA1`.
40
+
41
+ For backward compatibility, a row may instead be a contiguous sequence of hexadecimal palette indices, such as `00AA1`. Mixed plain and run tokens are accepted as colon-separated tokens, provided each token is valid.
42
+
43
+ Indices are case-insensitive on input. Encoders emit uppercase hexadecimal indices and positive decimal run lengths.
44
+
45
+ ## Decoder validation limits
46
+
47
+ NanoHex 2.0.0 rejects invalid/missing/duplicate sections, invalid RGB colours, invalid palette indices, non-positive or excessive run lengths, incorrect row widths/counts, and invalid dimensions. Width and height are each limited to 10,000; the total canvas is limited to 25,000,000 pixels.
48
+
49
+ ## Colour and image semantics
50
+
51
+ The format stores RGB only. Alpha is not stored; the v2 encoder composites transparent source pixels onto opaque white before resizing and quantisation. Image resizing uses nearest-neighbour sampling. Decoding reconstructs the stored pixel dimensions; optional integer enlargement is a decoder presentation option and does not alter the NHX file.
@@ -0,0 +1,18 @@
1
+ @size
2
+ h=8
3
+ w=8
4
+
5
+ @palette
6
+ #FFFFFF
7
+ #000000
8
+ #af0000
9
+
10
+ @data
11
+ 0*8
12
+ 0*5:2*3
13
+ 1*3:2*5
14
+ 0*8
15
+ 0*5:2*3
16
+ 1*3:2*5
17
+ 0*8
18
+ 0*5:2*3
@@ -0,0 +1,42 @@
1
+ [build-system]
2
+ requires = ["setuptools>=68", "wheel"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "nanohex"
7
+ version = "2.0.1"
8
+ description = "A lightweight palette-based image format using hexadecimal pixel indices and row-wise run-length encoding"
9
+ readme = "README.md"
10
+ requires-python = ">=3.10"
11
+ license = {file = "LICENSE"}
12
+ authors = [{name = "Ashutosh Acharya"}]
13
+ keywords = ["image-format", "image-encoding", "image-decoding", "rle", "palette", "pillow"]
14
+ classifiers = [
15
+ "Development Status :: 4 - Beta",
16
+ "Intended Audience :: Developers",
17
+ "License :: OSI Approved :: MIT License",
18
+ "Operating System :: OS Independent",
19
+ "Programming Language :: Python :: 3",
20
+ "Programming Language :: Python :: 3.10",
21
+ "Programming Language :: Python :: 3.11",
22
+ "Programming Language :: Python :: 3.12",
23
+ "Programming Language :: Python :: 3.13",
24
+ "Topic :: Multimedia :: Graphics",
25
+ "Topic :: Software Development :: Libraries :: Python Modules",
26
+ ]
27
+ dependencies = ["Pillow>=9.1.0"]
28
+
29
+ [project.urls]
30
+ Homepage = "https://github.com/Ashutosh-377/NanoHex"
31
+ Repository = "https://github.com/Ashutosh-377/NanoHex"
32
+ Issues = "https://github.com/Ashutosh-377/NanoHex/issues"
33
+
34
+ [project.scripts]
35
+ nanohex = "nanohex:main"
36
+
37
+ [tool.setuptools]
38
+ package-dir = {"" = "src"}
39
+ include-package-data = true
40
+
41
+ [tool.setuptools.packages.find]
42
+ where = ["src"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,220 @@
1
+ """NanoHex v2: palette-based image encoding with row-wise run-length encoding."""
2
+ from __future__ import annotations
3
+
4
+ import argparse
5
+ import re
6
+ from pathlib import Path
7
+ from typing import Iterable
8
+
9
+ from PIL import Image
10
+
11
+ _HEX_INDEX = re.compile(r"^[0-9A-Fa-f]$")
12
+ _HEX_COLOR = re.compile(r"^#[0-9A-Fa-f]{6}$")
13
+
14
+
15
+ class NanoHexError(ValueError):
16
+ """Raised when an NHX file or image cannot be processed."""
17
+
18
+
19
+ def _run_length_encode(row: Iterable[int]) -> str:
20
+ values = list(row)
21
+ if not values:
22
+ raise NanoHexError("Cannot encode an empty image row")
23
+ runs: list[str] = []
24
+ current = values[0]
25
+ count = 1
26
+ for value in values[1:]:
27
+ if value == current:
28
+ count += 1
29
+ else:
30
+ runs.append(f"{current:X}*{count}")
31
+ current, count = value, 1
32
+ runs.append(f"{current:X}*{count}")
33
+ return ":".join(runs)
34
+
35
+
36
+ def encode_image(input_path: str | Path, output_path: str | Path,
37
+ width: int = 32, height: int = 32, max_colors: int = 16) -> Path:
38
+ """Convert an image to NHX. Alpha is composited onto white before encoding."""
39
+ if width < 1 or height < 1:
40
+ raise NanoHexError("Width and height must be positive integers")
41
+ if not 1 <= max_colors <= 16:
42
+ raise NanoHexError("max_colors must be between 1 and 16 (NHX uses one hex digit per index)")
43
+
44
+ source = Path(input_path)
45
+ destination = Path(output_path)
46
+ try:
47
+ with Image.open(source) as opened:
48
+ rgba = opened.convert("RGBA")
49
+ background = Image.new("RGBA", rgba.size, (255, 255, 255, 255))
50
+ flattened = Image.alpha_composite(background, rgba).convert("RGB")
51
+ resized = flattened.resize((width, height), Image.Resampling.NEAREST)
52
+ quantized = resized.quantize(colors=max_colors, method=Image.Quantize.MEDIANCUT)
53
+ indices = list(quantized.tobytes())
54
+ raw_palette = quantized.getpalette()
55
+ except (OSError, ValueError) as exc:
56
+ raise NanoHexError(f"Could not read or process image '{source}': {exc}") from exc
57
+
58
+ used_indices = sorted(set(indices))
59
+ if not used_indices:
60
+ raise NanoHexError("The input image contains no pixels")
61
+ palette: list[str] = []
62
+ remap: dict[int, int] = {}
63
+ for new_index, old_index in enumerate(used_indices):
64
+ offset = old_index * 3
65
+ rgb = raw_palette[offset:offset + 3]
66
+ if len(rgb) != 3:
67
+ raise NanoHexError("Image palette is incomplete")
68
+ palette.append("#{:02X}{:02X}{:02X}".format(*rgb))
69
+ remap[old_index] = new_index
70
+
71
+ rows: list[str] = []
72
+ for y in range(height):
73
+ row_indices = [remap[value] for value in indices[y * width:(y + 1) * width]]
74
+ rows.append(_run_length_encode(row_indices))
75
+
76
+ destination.parent.mkdir(parents=True, exist_ok=True)
77
+ content = ["@size", f"h={height}", f"w={width}", "", "@palette", *palette, "", "@data", *rows]
78
+ destination.write_text("\n".join(content) + "\n", encoding="utf-8", newline="\n")
79
+ return destination
80
+
81
+
82
+ def _parse_sections(text: str) -> tuple[int, int, list[str], list[str]]:
83
+ lines = text.splitlines()
84
+ sections: dict[str, list[str]] = {}
85
+ current: str | None = None
86
+ for line_number, raw in enumerate(lines, start=1):
87
+ line = raw.strip()
88
+ if line.startswith("@"):
89
+ if line not in ("@size", "@palette", "@data"):
90
+ raise NanoHexError(f"Line {line_number}: unknown section '{line}'")
91
+ if line in sections:
92
+ raise NanoHexError(f"Line {line_number}: duplicate section '{line}'")
93
+ current = line
94
+ sections[current] = []
95
+ elif current is not None:
96
+ if line:
97
+ sections[current].append(line)
98
+ elif line:
99
+ raise NanoHexError(f"Line {line_number}: content found before first section")
100
+
101
+ missing = [name for name in ("@size", "@palette", "@data") if name not in sections]
102
+ if missing:
103
+ raise NanoHexError("Missing required section(s): " + ", ".join(missing))
104
+
105
+ dimensions: dict[str, int] = {}
106
+ for entry in sections["@size"]:
107
+ if "=" not in entry:
108
+ raise NanoHexError(f"Invalid size entry '{entry}'; expected key=value")
109
+ key, value = (part.strip() for part in entry.split("=", 1))
110
+ if key not in ("w", "h") or key in dimensions:
111
+ raise NanoHexError(f"Invalid or duplicate size key '{key}'")
112
+ try:
113
+ dimensions[key] = int(value)
114
+ except ValueError as exc:
115
+ raise NanoHexError(f"Invalid integer for size '{key}': {value}") from exc
116
+ if set(dimensions) != {"w", "h"}:
117
+ raise NanoHexError("@size must define both w and h")
118
+ width, height = dimensions["w"], dimensions["h"]
119
+ if not (1 <= width <= 10000 and 1 <= height <= 10000):
120
+ raise NanoHexError("Canvas dimensions must be between 1 and 10000")
121
+ if width * height > 25_000_000:
122
+ raise NanoHexError("Canvas exceeds the 25-million-pixel safety limit")
123
+
124
+ palette = [entry.upper() for entry in sections["@palette"]]
125
+ if not 1 <= len(palette) <= 16:
126
+ raise NanoHexError("Palette must contain between 1 and 16 colours")
127
+ for color in palette:
128
+ if not _HEX_COLOR.fullmatch(color):
129
+ raise NanoHexError(f"Invalid palette colour '{color}'; expected #RRGGBB")
130
+
131
+ rows: list[str] = []
132
+ for row_number, line in enumerate(sections["@data"], start=1):
133
+ decoded = ""
134
+ for token in line.split(":"):
135
+ token = token.strip()
136
+ if not token:
137
+ raise NanoHexError(f"Data row {row_number}: empty run between separators")
138
+ if "*" in token:
139
+ if token.count("*") != 1:
140
+ raise NanoHexError(f"Data row {row_number}: malformed run '{token}'")
141
+ index, count_text = (part.strip() for part in token.split("*", 1))
142
+ if not _HEX_INDEX.fullmatch(index):
143
+ raise NanoHexError(f"Data row {row_number}: invalid palette index '{index}'")
144
+ try:
145
+ count = int(count_text)
146
+ except ValueError as exc:
147
+ raise NanoHexError(f"Data row {row_number}: invalid run length '{count_text}'") from exc
148
+ if count < 1 or count > width:
149
+ raise NanoHexError(f"Data row {row_number}: run length must be between 1 and {width}")
150
+ decoded += index.upper() * count
151
+ else:
152
+ if not token or any(not _HEX_INDEX.fullmatch(char) for char in token):
153
+ raise NanoHexError(f"Data row {row_number}: invalid pixel sequence '{token}'")
154
+ decoded += token.upper()
155
+ if len(decoded) > width:
156
+ raise NanoHexError(f"Data row {row_number}: expands beyond declared width {width}")
157
+ if len(decoded) != width:
158
+ raise NanoHexError(f"Data row {row_number}: expected {width} pixels, got {len(decoded)}")
159
+ for char in decoded:
160
+ if int(char, 16) >= len(palette):
161
+ raise NanoHexError(f"Data row {row_number}: palette index {char} is out of range")
162
+ rows.append(decoded)
163
+
164
+ if len(rows) != height:
165
+ raise NanoHexError(f"Expected {height} data rows, got {len(rows)}")
166
+ return width, height, palette, rows
167
+
168
+
169
+ def decode_image(input_path: str | Path, output_path: str | Path,
170
+ scale: int = 1) -> Path:
171
+ """Decode an NHX file and save an RGB image."""
172
+ if scale < 1:
173
+ raise NanoHexError("Scale must be a positive integer")
174
+ source, destination = Path(input_path), Path(output_path)
175
+ try:
176
+ text = source.read_text(encoding="utf-8")
177
+ except OSError as exc:
178
+ raise NanoHexError(f"Could not read NHX file '{source}': {exc}") from exc
179
+ width, height, palette, rows = _parse_sections(text)
180
+ rgb_palette = [tuple(bytes.fromhex(color[1:])) for color in palette]
181
+ pixels = [rgb_palette[int(index, 16)] for row in rows for index in row]
182
+ image = Image.new("RGB", (width, height))
183
+ image.putdata(pixels)
184
+ if scale != 1:
185
+ image = image.resize((width * scale, height * scale), Image.Resampling.NEAREST)
186
+ destination.parent.mkdir(parents=True, exist_ok=True)
187
+ try:
188
+ image.save(destination)
189
+ except OSError as exc:
190
+ raise NanoHexError(f"Could not save decoded image '{destination}': {exc}") from exc
191
+ return destination
192
+
193
+
194
+ def main() -> int:
195
+ parser = argparse.ArgumentParser(prog="nanohex", description="Encode and decode NanoHex (.nhx) images")
196
+ commands = parser.add_subparsers(dest="command", required=True)
197
+ enc = commands.add_parser("encode", help="Convert an image to NHX")
198
+ enc.add_argument("input", help="Input image path")
199
+ enc.add_argument("output", help="Output .nhx path")
200
+ enc.add_argument("--width", type=int, default=32)
201
+ enc.add_argument("--height", type=int, default=32)
202
+ enc.add_argument("--colors", type=int, default=16, help="Maximum palette colours (1-16)")
203
+ dec = commands.add_parser("decode", help="Convert NHX to an image")
204
+ dec.add_argument("input", help="Input .nhx path")
205
+ dec.add_argument("output", help="Output image path, e.g. decoded.png")
206
+ dec.add_argument("--scale", type=int, default=1, help="Nearest-neighbour integer enlargement")
207
+ args = parser.parse_args()
208
+ try:
209
+ if args.command == "encode":
210
+ result = encode_image(args.input, args.output, args.width, args.height, args.colors)
211
+ else:
212
+ result = decode_image(args.input, args.output, args.scale)
213
+ except NanoHexError as exc:
214
+ parser.exit(2, f"nanohex: error: {exc}\n")
215
+ print(f"Created {result}")
216
+ return 0
217
+
218
+
219
+ if __name__ == "__main__":
220
+ raise SystemExit(main())
@@ -0,0 +1,3 @@
1
+ from . import main
2
+
3
+ raise SystemExit(main())
@@ -0,0 +1,162 @@
1
+ Metadata-Version: 2.4
2
+ Name: nanohex
3
+ Version: 2.0.1
4
+ Summary: A lightweight palette-based image format using hexadecimal pixel indices and row-wise run-length encoding
5
+ Author: Ashutosh Acharya
6
+ License: MIT License
7
+
8
+ Copyright (c) 2026 NanoHex contributors
9
+
10
+ Permission is hereby granted, free of charge, to any person obtaining a copy
11
+ of this software and associated documentation files (the "Software"), to deal
12
+ in the Software without restriction, including without limitation the rights
13
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
14
+ copies of the Software, and to permit persons to whom the Software is
15
+ furnished to do so, subject to the following conditions:
16
+
17
+ The above copyright notice and this permission notice shall be included in all
18
+ copies or substantial portions of the Software.
19
+
20
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
21
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
22
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
23
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
24
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
25
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
26
+ SOFTWARE.
27
+
28
+ Project-URL: Homepage, https://github.com/Ashutosh-377/NanoHex
29
+ Project-URL: Repository, https://github.com/Ashutosh-377/NanoHex
30
+ Project-URL: Issues, https://github.com/Ashutosh-377/NanoHex/issues
31
+ Keywords: image-format,image-encoding,image-decoding,rle,palette,pillow
32
+ Classifier: Development Status :: 4 - Beta
33
+ Classifier: Intended Audience :: Developers
34
+ Classifier: License :: OSI Approved :: MIT License
35
+ Classifier: Operating System :: OS Independent
36
+ Classifier: Programming Language :: Python :: 3
37
+ Classifier: Programming Language :: Python :: 3.10
38
+ Classifier: Programming Language :: Python :: 3.11
39
+ Classifier: Programming Language :: Python :: 3.12
40
+ Classifier: Programming Language :: Python :: 3.13
41
+ Classifier: Topic :: Multimedia :: Graphics
42
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
43
+ Requires-Python: >=3.10
44
+ Description-Content-Type: text/markdown
45
+ License-File: LICENSE
46
+ Requires-Dist: Pillow>=9.1.0
47
+ Dynamic: license-file
48
+
49
+ # NanoHex v2.0.1
50
+
51
+ NanoHex is a small palette-based raster image format. It stores a canvas size, a hexadecimal RGB palette, and pixel rows encoded with run-length encoding (RLE).
52
+
53
+ ## Features
54
+
55
+ - Configurable output dimensions (nearest-neighbour resizing).
56
+ - Adaptive palette quantisation with 1–16 colours.
57
+ - One hexadecimal digit per palette index.
58
+ - Row-wise RLE to represent repeated pixels compactly.
59
+ - Decoder validation for malformed sections, dimensions, colours, runs, and palette references.
60
+ - PNG (and other Pillow-supported image formats) input/output.
61
+ - Transparent input pixels are composited onto white; NHX v2 stores RGB colours only.
62
+
63
+ ## Requirements
64
+
65
+ - Python 3.10+
66
+ - Pillow 9.1+
67
+
68
+ Install NanoHex from PyPI:
69
+
70
+ ```bash
71
+ python -m pip install nanohex
72
+ ```
73
+
74
+ Alternatively, install from a source checkout:
75
+
76
+ ```bash
77
+ python -m pip install .
78
+ ```
79
+
80
+ ## Usage
81
+
82
+ Encode an image into a 32×32 NHX file using up to 16 colours:
83
+
84
+ ```bash
85
+ python -m pip install .
86
+ python -m nanohex encode input.png output.nhx
87
+ ```
88
+
89
+ Choose dimensions and palette size:
90
+
91
+ ```bash
92
+ python -m nanohex encode input.png output.nhx --width 64 --height 64 --colors 12
93
+ ```
94
+
95
+ Decode an NHX file:
96
+
97
+ ```bash
98
+ python -m nanohex decode output.nhx decoded.png
99
+ ```
100
+
101
+ Enlarge the decoded image by an integer factor using nearest-neighbour scaling:
102
+
103
+ ```bash
104
+ python -m nanohex decode output.nhx decoded.png --scale 10
105
+ ```
106
+
107
+ ## NHX file structure
108
+
109
+ An NHX file is UTF-8 text with three required sections, in any order:
110
+
111
+ ```text
112
+ @size
113
+ h=8
114
+ w=8
115
+
116
+ @palette
117
+ #FFFFFF
118
+ #000000
119
+ #af0000
120
+
121
+ @data
122
+ 0*8
123
+ 0*5:2*3
124
+ 1*3:2*5
125
+ ...
126
+ ```
127
+
128
+ ### `@size`
129
+
130
+ Defines positive integer canvas dimensions with `w` (width) and `h` (height). The decoder currently limits each dimension to 10,000 and the total canvas to 25 million pixels.
131
+
132
+ ### `@palette`
133
+
134
+ Contains 1–16 RGB colours in `#RRGGBB` notation. Palette entries are addressed by a single hexadecimal digit: `0`–`9`, `A`–`F`.
135
+
136
+ ### `@data`
137
+
138
+ Contains exactly `h` non-empty rows. Each row must expand to exactly `w` pixels. Runs use `INDEX*COUNT`, separated by colons. For example, `A*4:0*2` means four pixels using palette entry `A`, followed by two pixels using entry `0`.
139
+
140
+ For compatibility with earlier NanoHex files, rows containing an uncompressed sequence of hexadecimal indices are also accepted (for example, `0110`).
141
+
142
+ ## Compatibility and limitations
143
+
144
+ - v2.0.1 preserves the original `@size`, `@palette`, and `@data` layout and the original one-digit palette-index/RLE representation.
145
+ - Existing files using up to 16 palette entries and valid row data remain readable.
146
+ - Alpha/transparency is not represented in NHX; the encoder composites transparent pixels onto white.
147
+ - Animation, metadata, arbitrary colour profiles, and palettes larger than 16 colours are not supported.
148
+ - Encoding resizes to the requested dimensions before quantisation; decoding reconstructs the stored dimensions.
149
+
150
+ The full format definition is available in [docs/NHX_FORMAT.md](docs/NHX_FORMAT.md).
151
+
152
+ ## Tests
153
+
154
+ Run the test suite from the repository root:
155
+
156
+ ```bash
157
+ python -m unittest discover -s tests -v
158
+ ```
159
+
160
+ ## License
161
+
162
+ MIT. See [LICENSE](LICENSE).
@@ -0,0 +1,16 @@
1
+ CHANGELOG.md
2
+ LICENSE
3
+ MANIFEST.in
4
+ README.md
5
+ pyproject.toml
6
+ docs/NHX_FORMAT.md
7
+ examples/test.nhx
8
+ src/nanohex/__init__.py
9
+ src/nanohex/__main__.py
10
+ src/nanohex.egg-info/PKG-INFO
11
+ src/nanohex.egg-info/SOURCES.txt
12
+ src/nanohex.egg-info/dependency_links.txt
13
+ src/nanohex.egg-info/entry_points.txt
14
+ src/nanohex.egg-info/requires.txt
15
+ src/nanohex.egg-info/top_level.txt
16
+ tests/test_nanohex.py
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ nanohex = nanohex:main
@@ -0,0 +1 @@
1
+ Pillow>=9.1.0
@@ -0,0 +1 @@
1
+ nanohex
@@ -0,0 +1,76 @@
1
+ import tempfile
2
+ import unittest
3
+ from pathlib import Path
4
+
5
+ from PIL import Image
6
+
7
+ from nanohex import NanoHexError, decode_image, encode_image
8
+
9
+
10
+ class NanoHexTests(unittest.TestCase):
11
+ def setUp(self):
12
+ self.temp = tempfile.TemporaryDirectory()
13
+ self.root = Path(self.temp.name)
14
+
15
+ def tearDown(self):
16
+ self.temp.cleanup()
17
+
18
+ def test_round_trip_preserves_quantized_pixels(self):
19
+ source = self.root / "source.png"
20
+ nhx = self.root / "image.nhx"
21
+ output = self.root / "decoded.png"
22
+ image = Image.new("RGB", (4, 3))
23
+ image.putdata([
24
+ (255, 0, 0), (255, 0, 0), (0, 255, 0), (0, 255, 0),
25
+ (0, 0, 255), (0, 0, 255), (255, 255, 255), (255, 255, 255),
26
+ (20, 20, 20), (20, 20, 20), (80, 80, 80), (80, 80, 80),
27
+ ])
28
+ image.save(source)
29
+ encode_image(source, nhx, width=4, height=3, max_colors=6)
30
+ decode_image(nhx, output)
31
+ with Image.open(output) as decoded:
32
+ self.assertEqual(decoded.size, (4, 3))
33
+ self.assertEqual(decoded.tobytes(), image.tobytes())
34
+
35
+ def test_existing_sample_decodes(self):
36
+ sample = Path(__file__).parents[1] / "examples" / "test.nhx"
37
+ output = self.root / "sample.png"
38
+ decode_image(sample, output)
39
+ with Image.open(output) as decoded:
40
+ self.assertEqual(decoded.size, (8, 8))
41
+
42
+ def test_scaled_decode(self):
43
+ sample = Path(__file__).parents[1] / "examples" / "test.nhx"
44
+ output = self.root / "scaled.png"
45
+ decode_image(sample, output, scale=3)
46
+ with Image.open(output) as decoded:
47
+ self.assertEqual(decoded.size, (24, 24))
48
+
49
+ def test_transparency_is_composited_onto_white(self):
50
+ source = self.root / "transparent.png"
51
+ nhx = self.root / "transparent.nhx"
52
+ output = self.root / "transparent-decoded.png"
53
+ image = Image.new("RGBA", (1, 1), (0, 0, 0, 0))
54
+ image.save(source)
55
+ encode_image(source, nhx, width=1, height=1, max_colors=1)
56
+ decode_image(nhx, output)
57
+ with Image.open(output) as decoded:
58
+ self.assertEqual(decoded.getpixel((0, 0)), (255, 255, 255))
59
+
60
+ def test_rejects_bad_dimensions(self):
61
+ source = self.root / "bad.nhx"
62
+ source.write_text("@size\nh=2\nw=2\n\n@palette\n#FFFFFF\n\n@data\n0*2\n")
63
+ with self.assertRaises(NanoHexError):
64
+ decode_image(source, self.root / "bad.png")
65
+
66
+ def test_supports_legacy_uncompressed_rows(self):
67
+ source = self.root / "legacy.nhx"
68
+ source.write_text("@size\nh=1\nw=4\n\n@palette\n#000000\n#FFFFFF\n\n@data\n0110\n")
69
+ output = self.root / "legacy.png"
70
+ decode_image(source, output)
71
+ with Image.open(output) as decoded:
72
+ self.assertEqual(decoded.tobytes(), bytes([0, 0, 0, 255, 255, 255, 255, 255, 255, 0, 0, 0]))
73
+
74
+
75
+ if __name__ == "__main__":
76
+ unittest.main()