Xpict (Python)
Xpict is a Pillow-based library for building declarative templates that generate standardized images from data, whether static or dynamic. It supports conditional rendering, axes computed at runtime and dynamic text. This is the Python port of the Node.js xpict library.
Contents
- Installation
- Quick start
- How it works
- Template
- Dynamic values and
when - Layers
- Fonts
- Colors
- Transformations and effects
- Custom layers
- Errors
- Development
- Differences from the Node.js version
📦 Installation
poetry add xpict.py
# or
pip install xpict.py
Requires Python 3.9+ and Pillow 11.2+ (with FreeType support, which the official wheels include).
🚀 Quick start
import xpict
poppins = xpict.utils.font(name="poppins", file_path="Poppins-Bold.ttf", color="#ffffff")
template = xpict.template(
config={"width": 1280, "height": 720, "fill": "#020817"}, # fill is optional
layers=[
xpict.text(
text=lambda ctx: f"Hello, {ctx.data['name']}!",
x=640, y=360,
align="center", baseline="middle",
font=poppins(size=60),
stroke={"width": 4, "fill": "#000000"},
),
],
)
image = template.render({"name": "World"}) # PIL.Image.Image (RGBA)
image.save("out.png")
A template is built once and can be rendered any number of times with different data.
How it works
- A template is a list of layers.
template.render(data)creates an RGBA canvas and draws each layer on top of the previous ones, in list order (later layers cover earlier ones). - Layers are plain Python objects.
xpict.text(...),xpict.rectangle(...)and friends are just aliases for the layer classes (TextLayer,RectangleLayer, ...), soxpict.rectangle(...)andxpict.RectangleLayer(...)are the same thing. Use whichever reads better. - Almost every value can be a function. Wherever a layer takes a coordinate, size or text, you can pass a fixed value or a function of a
LayerContext. The function is evaluated at render time, so one template adapts to any data. - Coordinates are relative to a moving origin. The origin is
(0, 0)at the top-left of the canvas.groupandrepeatshift the origin for the layers inside them (see Group).xgrows to the right andygrows downward. - The result is a regular
PIL.Image.ImageinRGBAmode, so you can keep processing it with Pillow, or call.save(),.convert("RGB"), etc.
Shapes (rectangles, circles, lines) are drawn with 4x supersampling for smooth edges, and every color is alpha-blended with what is already on the canvas, so semi-transparent fills behave as expected.
Template
xpict.template(...) (alias of xpict.Template) takes layers plus one of two ways to define the canvas.
Using config (width, height and optional fill):
xpict.template(
config={"width": 1280, "height": 720, "fill": "#020817"},
layers=[...],
)
config may be a dict or an xpict.TemplateConfig(width, height, fill=None). Without fill, the canvas starts fully transparent.
Using an image as the background:
xpict.template(image_path="path/to/background.png", layers=[...])
The canvas takes the size of the image, the image is drawn first, and the layers are drawn over it. The file is read on every render() call.
render(data=None) returns a new image each time. data can be anything (a dict, a dataclass, a pydantic model...); Xpict never inspects it, it only hands it to your functions.
If neither config nor image_path is given, render() raises XpictError.
Dynamic values and when
Every dynamic value is a function that receives one argument, a LayerContext:
| Attribute | Meaning |
|---|---|
ctx.data |
The object passed to template.render(data). |
ctx.index |
0 at the top level. Inside a repeat, the index of the current item. |
ctx.template_size |
A TemplateSize with .width and .height of the canvas (handy for centering). |
x=lambda ctx: ctx.index * 110
y=lambda ctx: ctx.template_size.height - 40
text=lambda ctx: ctx.data["title"].upper()
The parameters that accept a value or a function are: x, y, width, height (rectangles and images), line coordinates and width, text, the image src, the x/y of group and repeat.
Every layer also accepts when, a function returning a boolean. If it is omitted the layer always renders; if it returns falsy the layer (and, for groups, everything inside it) is skipped:
xpict.text(..., when=lambda ctx: ctx.data.get("subtitle"))
when is evaluated with the same ctx the layer would receive, so inside a repeat it can depend on ctx.index.
Layers
Text
xpict.text(
text="Hello World", # str or function
font=poppins(size=60), # see Fonts
x=640, y=360,
align="center", # optional: left (default) | center | right
baseline="middle", # optional: top | hanging | middle | alphabetic (default) | ideographic | bottom
stroke={"width": 4, "fill": "#000000"}, # optional
rotation=-20, # optional, degrees
)
(x, y)is the anchor point of the text, interpreted throughalignandbaseline. Withalign="center", baseline="middle"it is the center of the text.alignandbaselineaccept plain strings or thexpict.TextAlign/xpict.TextBaselineenums.strokedraws an outline behind the fill.widthis the full line width as on an HTML canvas (the outline extendswidth / 2outside the glyph). Accepts a dict orxpict.Stroke(fill=..., width=...).rotationis in degrees, clockwise for positive values, around the anchor point.- Text color comes from the font (
font(size=..., color=...)); it defaults to black. - An empty string renders nothing.
- Text is drawn on a single line; use
xpict.wrap_text(text, max_chars)to split a long string into lines and render each one with its own layer (for example inside arepeat).
wrap_text(text, max_width) splits on spaces and returns a list of lines of roughly max_width characters (it counts characters, not pixels). Each returned line keeps a trailing space.
Image
xpict.image(
src="path/to/image.png", # path, bytes, PIL.Image, or a function returning one of them
x=0, y=0,
width=200, # optional
height=100, # optional
flip_x=False, flip_y=False, # optional
rotate=45, # optional, degrees clockwise
transform=[...], # optional, see "Transformations and effects"
)
-
Sizing: with both
widthandheightthe image is resized to exactly that size. With only one, the other is computed to keep the aspect ratio. With neither, the original size is used. Resizing uses Lanczos resampling. -
Order of operations: load → resize → flips → rotation →
transformfunctions → composite onto the canvas at(x, y). -
Rotation happens inside the image's own frame (like the Node version): the image is rotated around its center and not enlarged, so corners that leave the frame are clipped.
-
Transparency in the source is preserved.
-
A dynamic
srclets one template show a different image per render or perrepeatitem:src=lambda ctx: ctx.data["avatar_path"]
Rectangle
xpict.rectangle(x=0, y=0, width=150, height=50, fill="#ffffff", border_radius=5)
(x, y) is the top-left corner. border_radius is optional and is clamped to half of the smaller side, so a large value produces a pill shape instead of an artifact.
Circle
xpict.circle(x=100, y=100, radius=50, fill="#ffffff")
(x, y) is the center of the circle.
Line
xpict.line(from_=(0, 0), to=(0, 50), color="#ffffff", width=1)
The start point parameter is named from_ because from is a Python keyword. The points are (x, y) tuples whose members can also be functions. Lines have round caps.
Group
Groups layers that share a coordinate system, and optionally offsets all of them:
xpict.group(
x=50, y=50,
layers=[
xpict.rectangle(x=0, y=0, width=200, height=80, fill="#0F172A"),
xpict.text(text="Card", x=10, y=40, font=poppins(size=24)), # drawn at (60, 90)
],
)
The group's x/y are added to the current origin while its children render, then restored. Groups can be nested, and the offsets accumulate. A group's when skips all of its children; each child's own when is also respected.
Repeat
Generates one layer per item of a list, which is the way to handle variable-length data:
xpict.repeat(
each=lambda ctx: ctx.data["images"], # returns a list
x=lambda ctx: ctx.index * 50, # offset for item `ctx.index`
y=lambda ctx: ctx.index * 50,
layer=lambda item, info: xpict.image( # returns ONE layer for this item
src=item, x=0, y=0,
),
)
each(ctx)returns the list of items. An empty list (orNone) renders nothing.- For every item, the origin is shifted by
(x, y)(evaluated withctx.indexset to the item's index), thenlayer(item, info)is called.info.indexandinfo.lengthare the item's position and the list size. The layer is rendered and the origin is restored. - Inside the produced layer,
ctx.indexis the item's index. Return anxpict.group(...)to render several layers per item. - Use
info.lengthto special-case, for example, the last item.
Fonts
poppins = xpict.utils.font(
name="poppins",
file_path="Poppins-Bold.ttf", # optional
color="#ffffff", # optional default color
)
poppins(size=60) # -> Font(size=60, name="poppins", color="#ffffff")
poppins(size=60, color="#facc15") # override the color for this use
font(...)registersname→file_pathin a global registry (re-registering a name replaces it) and returns a factory. Call the factory withsize(required) and optionallycolor/weightto get aFontto pass toxpict.text(font=...).- If
file_pathdoes not exist,FileNotFoundErroris raised immediately. - If a name is not registered, Xpict tries to find a system font with that name (
nameandname.ttf, using Pillow's font lookup), and finally falls back to Pillow's built-in font so text always renders. - Loaded fonts are cached per
(name, size). weightis stored on theFontbut does not change the rendering. To use several weights, register one file per weight under different names (poppins-bold,poppins-light, ...).
Colors
Anywhere a color is expected (fill, color, stroke.fill, template fill) you can use:
- Hex:
#rgb,#rrggbb,#rrggbbaa - CSS names:
"red","rebeccapurple", ... and"transparent" rgb(255, 0, 0)/rgba(255, 0, 0, 0.5)(alpha from 0 to 1, or a percentage)- Tuples:
(r, g, b)or(r, g, b, a)with 0-255 values
An invalid color raises XpictError.
Transformations and effects
The image layer's transform is a list of functions applied in order after the image has been resized, flipped and rotated. Each one receives a TransformOptions with:
| Attribute | Meaning |
|---|---|
options.image |
The current PIL.Image (RGBA), at its final size. |
options.data |
The data passed to render(). |
options.index |
The current index (see repeat). |
A transform may return a new image (which replaces the current one) or return None after modifying options.image in place:
from PIL import ImageEnhance
def brighten(options):
return ImageEnhance.Brightness(options.image).enhance(1.4)
xpict.image(
src="photo.png", x=0, y=0,
transform=[
xpict.effects.blur(2.5),
xpict.effects.grayscale(50),
brighten,
lambda opts: opts.image.rotate(10),
],
)
Built-in effects (available as xpict.effects.*). They are alpha-aware, so transparent regions do not bleed dark halos into the image:
| Effect | Description |
|---|---|
blur(radius) |
Gaussian blur; radius is the standard deviation in pixels. radius <= 0 does nothing. |
box_blur(radius) |
Box blur using a window of 2 * radius + 1 pixels; radius is truncated to an integer. radius <= 0 does nothing. |
grayscale(amount=100) |
Desaturates the image; amount is a percentage from 0 (unchanged) to 100 (fully gray). |
Custom layers
Subclass xpict.Layer, implement render(options) and draw on options.context.image (a PIL.Image). Add options.context.offset_x / offset_y to your coordinates so your layer cooperates with group and repeat:
from PIL import ImageDraw
import xpict
from xpict.context import resolve
from xpict.layers import RenderOptions
class DotLayer(xpict.Layer):
def __init__(self, x, y, when=None):
super().__init__(when)
self.x, self.y = x, y
def render(self, options: RenderOptions) -> None:
ctx = options.layer_context()
rc = options.context
x = rc.offset_x + resolve(self.x, ctx)
y = rc.offset_y + resolve(self.y, ctx)
ImageDraw.Draw(rc.image).point((x, y), fill="white")
resolve(value, ctx) returns value(ctx) for callables and the value itself otherwise. Layer.should_render(ctx) (which evaluates when) is called by the template, group and repeat before render, so you do not need to call it yourself.
Errors
All Xpict failures raise xpict.XpictError:
- Missing
config/image_pathon a template. - A background image that cannot be loaded.
- An invalid color.
- Any failure while rendering an image layer (missing file, unsupported format, an exception inside a
transform...). The message includes the image path, and the original exception is chained (__cause__).
A missing font file raises FileNotFoundError when you call font(...).
Development
poetry install
poetry run pytest
poetry run python examples/basic.py # writes examples/output.png
Project layout:
src/xpict/
__init__.py public API and factory aliases
core.py Template, TemplateConfig
context.py LayerContext, RenderContext, resolve()
drawing.py color parsing, supersampled shapes, safe compositing
layers/ one module per layer
effects/ blur, box_blur, grayscale
utils/ font registry, wrap_text
Differences from the Node.js version
- The API is synchronous;
render()returns aPIL.Imageinstead of aCanvas. - Dynamic functions receive a single
LayerContextinstead of a destructured object, and options usesnake_case(border_radius,flip_x,from_, ...). image_pathis actually drawn as the background.- Image transforms operate on a
PIL.Image(returned or modified in place) instead of a canvas context. - Font
weightis accepted but has no effect; register one font file per weight instead. - Text
baselinevalues map to Pillow's text anchors, so vertical placement can differ from the canvas by a few pixels. whenis evaluated with the realindexinsidegroupandrepeat, including for the layers arepeatproduces.
📝 License
MIT.
Metadata
Release files for xpict.py 0.1.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| xpict_py-0.1.0.tar.gz | 21.4 kB | Without provenance | Details for xpict_py-0.1.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| xpict_py-0.1.0-py3-none-any.whl | Python 3 | none | any | Details for xpict_py-0.1.0-py3-none-any.whl |
Total release size: 43.9 kB
Release files / xpict_py-0.1.0.tar.gz
| Download URL | xpict_py-0.1.0.tar.gz |
|---|---|
| Size | 21.4 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
0b8c081ffe64fdffd568b7cc3312c6433e1a4bc70aa7b7f6d3c7bff66ecbef8a
|
|
BLAKE2b-256 checksum How to use checksums |
6c14873e1fce4a6b9d7c61998ac8826c97141ccd611c0fbbc3e1b80a7693d660
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
poetry/2.5.1 CPython/3.12.10 Windows/10
|
Release files / xpict_py-0.1.0-py3-none-any.whl
| Download URL | xpict_py-0.1.0-py3-none-any.whl |
|---|---|
| Size | 22.5 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
83d70e840cb833a773f56d35c494ed3070e87b1f51b23a1cb529a96a7e7d1e3e
|
|
BLAKE2b-256 checksum How to use checksums |
9b9858cd9a63b16f17f065dce370c25659467b15edceab035062ee9baa283f65
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
poetry/2.5.1 CPython/3.12.10 Windows/10
|
Security for xpict.py 0.1.0
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.