Skip to content

Imaging and Composition API Reference

purrint.imaging.ImageOptions dataclass

How to turn a picture into dots.

  • rotate: "auto" turns landscape pictures 90° so they use the length of the paper; or an angle (0, 90, 180, 270) applied clockwise.
  • dither: floyd (photos), atkinson (crisper photos), bayer (ordered pattern), halftone (newspaper dots), threshold (text/line art), none (grayscale printers only).
  • brightness / contrast: -100..100. gamma: >1 darkens mid-tones, <1 lightens them.
  • threshold: 0..255 cut-off used by threshold dithering.
Source code in src/purrint/imaging.py
@dataclass(frozen=True)
class ImageOptions:
    """How to turn a picture into dots.

    * ``rotate``: ``"auto"`` turns landscape pictures 90° so they use the length of the paper;
      or an angle (0, 90, 180, 270) applied clockwise.
    * ``dither``: ``floyd`` (photos), ``atkinson`` (crisper photos), ``bayer`` (ordered pattern),
      ``halftone`` (newspaper dots), ``threshold`` (text/line art), ``none`` (grayscale printers only).
    * ``brightness`` / ``contrast``: -100..100. ``gamma``: >1 darkens mid-tones, <1 lightens them.
    * ``threshold``: 0..255 cut-off used by ``threshold`` dithering.
    """

    rotate: Union[str, int] = "auto"
    dither: str = "floyd"
    brightness: int = 0
    contrast: int = 0
    gamma: float = 1.0
    sharpen: bool = False
    invert: bool = False
    threshold: int = 128
    autocontrast: bool = False
    max_height: Optional[int] = None

purrint.imaging.prepare(source, width=384, options=ImageOptions(), gray=False)

Full pipeline. Returns mode "1" (dots) or, with gray=True, a 16-level mode "L" image.

Source code in src/purrint/imaging.py
def prepare(
    source: ImageSource,
    width: int = 384,
    options: ImageOptions = ImageOptions(),
    gray: bool = False,
) -> Image.Image:
    """Full pipeline. Returns mode ``"1"`` (dots) or, with ``gray=True``, a 16-level mode ``"L"`` image."""
    img = load_image(source)
    img = _flatten(img)
    img = _orient(img, options.rotate)
    img = fit_width(img, width, options.max_height)
    img = adjust_tone(img, options)
    if gray:
        return quantize_gray16(img)
    return dither(img, options.dither, options.threshold)

purrint.imaging.preview(img, paper_margin=12)

An RGB picture of how the job looks on paper (useful for dry runs and UIs).

Source code in src/purrint/imaging.py
def preview(img: Image.Image, paper_margin: int = 12) -> Image.Image:
    """An RGB picture of how the job looks on paper (useful for dry runs and UIs)."""
    base = img.convert("L")
    paper = Image.new("RGB", (base.width + 2 * paper_margin, base.height + 2 * paper_margin), (250, 249, 245))
    tinted = ImageOps.colorize(base, black=(25, 25, 30), white=(250, 249, 245))
    paper.paste(tinted, (paper_margin, paper_margin))
    return paper

purrint.imaging.stack(images, gap=0)

Join images vertically (all must share the same width).

Source code in src/purrint/imaging.py
def stack(images: Sequence[Image.Image], gap: int = 0) -> Image.Image:
    """Join images vertically (all must share the same width)."""
    if not images:
        raise ValueError("nothing to stack")
    width = images[0].width
    mode = "L" if any(i.mode == "L" for i in images) else "1"
    height = sum(i.height for i in images) + gap * (len(images) - 1)
    out = Image.new(mode, (width, height), 255)
    y = 0
    for i in images:
        if i.width != width:
            raise ValueError("all images must have the same width")
        out.paste(i.convert(mode), (0, y))
        y += i.height + gap
    return out

purrint.text.render_text(text, width=384, *, font=None, size=26, bold=False, mono=False, align='left', line_spacing=1.2, padding=4, invert=False, underline=False)

Lay out text across width dots and return a mode "1" image.

align is left, center or right. Long lines wrap on spaces; \n starts a new line.

Source code in src/purrint/text.py
def render_text(
    text: str,
    width: int = 384,
    *,
    font: FontLike = None,
    size: int = 26,
    bold: bool = False,
    mono: bool = False,
    align: str = "left",
    line_spacing: float = 1.2,
    padding: int = 4,
    invert: bool = False,
    underline: bool = False,
) -> Image.Image:
    """Lay out ``text`` across ``width`` dots and return a mode ``"1"`` image.

    ``align`` is ``left``, ``center`` or ``right``. Long lines wrap on spaces; ``\\n`` starts a new line.
    """
    if align not in ("left", "center", "right"):
        raise ValueError("align must be 'left', 'center' or 'right'")
    f = get_font(font, size, bold=bold, mono=mono)
    inner = max(8, width - 2 * padding)
    lines = _wrap(str(text), f, inner)
    ascent, descent = f.getmetrics()
    line_h = max(1, int(round((ascent + descent) * line_spacing)))
    height = max(1, line_h * len(lines) + 2 * padding)
    img = Image.new("L", (width, height), 255)
    draw = ImageDraw.Draw(img)
    fake_bold = bold and font is None and _find_font_file(_CANDIDATES_BOLD) is None
    for i, ln in enumerate(lines):
        w = f.getlength(ln)
        if align == "center":
            x = (width - w) / 2
        elif align == "right":
            x = width - padding - w
        else:
            x = padding
        y = padding + i * line_h
        draw.text((x, y), ln, font=f, fill=0)
        if fake_bold:
            draw.text((x + 1, y), ln, font=f, fill=0)
        if underline and ln:
            uy = y + ascent + max(1, size // 12)
            draw.line((x, uy, x + w, uy), fill=0, width=max(1, size // 14))
    if invert:
        img = img.point(lambda v: 255 - v)
    return img.point(lambda v: 255 if v >= 140 else 0).convert("1", dither=Image.Dither.NONE)

purrint.text.render_qr(data, width=384, *, size=None, border=2, error_correction='M', caption=None, caption_size=22)

A centred QR code (requires pip install purrint[qr]). size is the QR side in dots.

Source code in src/purrint/text.py
def render_qr(
    data: str,
    width: int = 384,
    *,
    size: Optional[int] = None,
    border: int = 2,
    error_correction: str = "M",
    caption: Optional[str] = None,
    caption_size: int = 22,
) -> Image.Image:
    """A centred QR code (requires ``pip install purrint[qr]``). ``size`` is the QR side in dots."""
    try:
        import qrcode
        from qrcode.constants import ERROR_CORRECT_H, ERROR_CORRECT_L, ERROR_CORRECT_M, ERROR_CORRECT_Q
    except ImportError as exc:  # pragma: no cover - optional dependency
        raise ImportError("QR codes need the optional dependency: pip install purrint[qr]") from exc

    levels = {"L": ERROR_CORRECT_L, "M": ERROR_CORRECT_M, "Q": ERROR_CORRECT_Q, "H": ERROR_CORRECT_H}
    qr = qrcode.QRCode(error_correction=levels.get(error_correction.upper(), ERROR_CORRECT_M), border=border, box_size=1)
    qr.add_data(data)
    qr.make(fit=True)
    matrix = qr.get_matrix()
    modules = len(matrix)
    side = min(width, size or int(width * 0.8))
    scale = max(1, side // modules)
    side = scale * modules
    code = Image.new("L", (modules, modules), 255)
    code.putdata([0 if cell else 255 for row in matrix for cell in row])
    code = code.resize((side, side), Image.Resampling.NEAREST)
    canvas = Image.new("L", (width, side), 255)
    canvas.paste(code, ((width - side) // 2, 0))
    out = canvas.convert("1", dither=Image.Dither.NONE)
    if caption:
        from .imaging import stack

        out = stack([out, render_text(caption, width, size=caption_size, align="center")])
    return out

purrint.text.render_separator(width=384, height=12, style='dashed')

A horizontal rule: solid, dashed or dotted.

Source code in src/purrint/text.py
def render_separator(width: int = 384, height: int = 12, style: str = "dashed") -> Image.Image:
    """A horizontal rule: ``solid``, ``dashed`` or ``dotted``."""
    img = Image.new("L", (width, height), 255)
    draw = ImageDraw.Draw(img)
    y = height // 2
    if style == "solid":
        draw.line((0, y, width, y), fill=0, width=2)
    else:
        step, dash = (12, 7) if style == "dashed" else (6, 2)
        for x in range(0, width, step):
            draw.line((x, y, min(width, x + dash), y), fill=0, width=2)
    return img.convert("1", dither=Image.Dither.NONE)