color_tools.png_writer

Minimal PNG writer for repeated-row RGB images.

Encodes solid, block, gradient, and equal-width swatch rows as PNG files. Uses only the standard library (zlib and struct), so it works without Pillow or numpy.

This module belongs to the base package, not the optional image package. It must not import Pillow, NumPy, or modules that require them.

Output format: 8-bit RGB (truecolor), no alpha, no interlacing, scanline filter “None”, with an sRGB chunk marking the pixels as sRGB.

Example:

>>> from color_tools.png_writer import SimplePNGWriter
>>> writer = SimplePNGWriter(
...     [(255, 0, 0), (0, 255, 0), (0, 0, 255)],
...     swatch_width=32,
...     swatch_height=32,
... )
>>> writer.width, writer.height
(96, 32)
>>> writer.save("rgb_swatches.png")
>>> png_bytes = writer.to_bytes()
class color_tools.png_writer.SimplePNGWriter(colors, swatch_width=1, swatch_height=1)[source]

Bases: object

Write a repeated horizontal RGB row as a PNG.

Direct construction creates an equal-width strip: the image is len(colors) * swatch_width pixels wide and swatch_height pixels tall. The named constructors create solid, deterministic block, or encoded- sRGB gradient rows. Every row in the resulting image is identical.

Variables:
  • colors – Immutable validated (R, G, B) tuples, in left-to-right order

  • swatch_width – Direct-constructor swatch width; 1 for generated rows

  • swatch_height – Image height

  • width – Total image width in pixels

  • height – Total image height in pixels

Parameters:
  • colors (Sequence[RGB | list[int]])

  • swatch_width (int)

  • swatch_height (int)

classmethod from_solid(color, width, height)[source]

Create a solid-color image with the requested dimensions.

Return type:

SimplePNGWriter

Parameters:
classmethod from_blocks(colors, width, height)[source]

Create source-order vertical color blocks spanning the requested width.

Block widths differ by at most one pixel. Remainder pixels are assigned to the earliest blocks, and every component receives at least one pixel.

Return type:

SimplePNGWriter

Parameters:
classmethod from_gradient(colors, width, height)[source]

Create an encoded-sRGB gradient through equally spaced color stops.

Return type:

SimplePNGWriter

Parameters:
to_bytes()[source]

Encode the image and return the complete PNG file as bytes.

Return type:

bytes

save(path)[source]

Write the PNG to a file, creating missing parent directories.

Parameters:

path (str | Path) – Destination file path (overwritten if it exists)

Raises:

OSError – If creating directories or writing the file fails.

Return type:

None