How Large Language Models Draw Stroke by Stroke with Code Instead of Image Models
This article explores an alternative to diffusion-based image generation in which a large language model produces images not as pixels but as executable drawing programs, painting stroke by stroke on a virtual canvas. It breaks down the technical principles, key mechanisms, and engineering implementation of this paradigm: how a stroke is encoded as a structured instruction, how physics approximations model the brush, paint, and canvas, how an iterative generate-render-evaluate-refine loop lets the model check its own work, and how a reusable style vector yields a consistent artistic personality. It then compares the cost and benefits of code-based painting versus diffusion models, outlines applicable scenarios and implementation steps, and closes with a troubleshooting checklist for common mistakes.
Introduction: When Image Generation No Longer Relies on Image Models
In recent years, mainstream image generation has been built almost entirely on diffusion models, which “sculpt” an image out of random noise through gradual denoising. But there is a fundamentally different technical direction: instead of generating pixels directly, a large language model writes code that simulates a real paintbrush and draws the picture stroke by stroke on a virtual canvas.
The core disruption of this approach is that the model’s output is no longer a two-dimensional pixel matrix but an executable drawing program. The position of every stroke, the brush shape, the wetness of the paint, and the fact that a mark cannot be undone once it lands are all decomposed into structured instructions, which the model plans, executes, observes, and refines on its own. This article dissects the paradigm in full, from technical principles and key mechanisms to engineering implementation and applicability boundaries, and adds a common-mistakes and troubleshooting checklist at the end.
1. From Generating Images to Orchestrating Brush Strokes
The essence of traditional text-to-image (diffusion models) is solving the problem in pixel space: given a text condition, the model iteratively denoises a noise image until a finished picture emerges. Its strengths are speed and fine detail, but it has several inherent problems:
- The process is not controllable: the intermediate steps are hard to intervene in, and details such as fingers, text, and physical structures tend to contain structural errors;
- No intermediate state: it cannot work like a painter who “first sketches, then colors, then refines the edges” — everything happens inside the latent space;
- Not explainable: it cannot answer “why did this stroke land here.”
The “code painting” paradigm takes a completely different approach, which can be summarized as a four-step closed loop:
- Plan: the model first determines the composition, object placement, and light-and-shadow relationships at the “thought” level;
- Generate brush-stroke instructions: the model breaks the picture down into a series of strokes, each carrying parameters such as color, width, path points, and wobble amplitude;
- Render: a local drawing engine (based on coordinates and paths) actually “paints” the strokes onto the canvas;
- Perceive & Refine: the model looks back at the rendered result, identifies problems (such as messy lines or distorted proportions), and appends new strokes to cover or patch them.
The key insight of this loop is this: the seemingly continuous, artistic act of “drawing” is modeled as a discrete, recordable, and traceable sequence of decisions. Each stroke is an explicit decision by the model rather than the product of a black-box inference.
2. How Are Strokes Turned into Instructions? What Does a Single Stroke Contain?
To make a model “know how to draw,” you first have to translate the human act of painting into a machine-readable structure. In terms of data structure, a stroke usually contains the following fields:
@dataclassclass BrushStroke:color: str # Color, e.g. "#30346a"width: float # Brush width (pixels)points: list # Path point coordinates [(x, y), ...]wobble: float # Wobble amplitude, simulating hand instabilityopacity: float # Opacity / paint wetnesstexture: str # Brush texture type: round / flat / dry / wet
A few of these details really reflect the “realism” thinking:
- Deliberately added wobble: real humans cannot draw an absolutely straight line. Intentionally adding about 5–7 pixels of lateral sway to the path points actually makes the line closer to a hand-drawn feel. The case cited in this article (source noted at the end) mentions that a single stroke’s path points carry 5 slight wobble points swaying about 7 pixels, deliberately simulating the natural instability of the arm.
- Paint wetness and opacity: combining
opacityandtexturecan simulate wet-on-wet painting (colors bleeding into each other) and dry painting (crisp stroke edges with a “flying white” effect). - No undo: once a stroke lands on the canvas it is fixed, and the model can only correct by “overpainting a new stroke over the old one.” This matches the physical constraint of real painting and forces the model to have a “plan first” capability.
To make the example actually runnable, here is a minimal rendering core based on Python Pillow (first run pip install pillow):
from PIL import Image, ImageDrawimport mathdef render_stroke(draw: ImageDraw.ImageDraw, stroke):pts = stroke.pointsfor i in range(len(pts) - 1):x0, y0 = pts[i]x1, y1 = pts[i + 1]# Interpolate along the line to simulate continuous brush movementsteps = max(int(math.hypot(x1 - x0, y1 - y0) / max(stroke.width * 0.25, 1)), 1)for s in range(steps):t = s / stepsx = x0 + (x1 - x0) * ty = y0 + (y1 - y0) * t# Add a slight wobble to mimic hand-drawn instabilitywob = stroke.wobble * math.sin(s * 0.7)r = stroke.width / 2draw.ellipse([x - r, y + wob - r, x + r, y + wob + r],fill=stroke.color,)
This code fully expresses the idea of “restoring a stroke to a physical mark on paper”: interpolate along the path, overlay a slight wobble, and color by brush radius. If you need alpha blending, you can instead draw on an RGBA layer and composite with Image.alpha_composite.
3. How Do You Do the Physics Simulation? Joint Modeling of Brush, Paint, and Canvas
“Realism” is not just a slogan; it requires three physical approximations:
1. Brush Model
Different brushes determine the “personality” of a line:
- Round-tip brush: opaque at the center and semi-transparent at the edges, suitable for soft transitions;
- Flat-tip brush: has an angular feel, with a “dry brush” effect at the edges;
- Dry brush: uses a noise threshold to leave some pixels unpainted, creating a flying-white effect.
In engineering practice, a common technique is to use a brush “stamp” image and repeatedly “stamp” it along the path while stacking opacity to approximate a real brush stroke.
2. Paint Model
- Wet-on-wet: a new stroke blends with adjacent wet strokes (approximated with a simple weighted average or a “muddiness” model);
- Opacity / covering power: opaque paint covers the underlying color, while transparent paint (like watercolor) layers on top.
3. Canvas Texture
A canvas is not a pure white plane; it has a weave. You can apply a “multiply” or multiplicative blend between the brush stamp and the canvas texture, so paint deposits more deeply in the recesses of the texture and produces a real “paper feel.”
4. How Do You Build the Iterative Refinement Loop? How Does the Model Check Its Own Work?
The thing that most distinguishes this paradigm from diffusion models is that it introduces a closed-loop visual feedback. The cited case describes how, across multiple drawing rounds, the model “observes the canvas and checks its own errors” — for example, noticing that a bird’s back is drawn too thinly or that the lines are messy, and then appending strokes to correct them.
The engineering implementation usually follows a “generate–render–evaluate–refine” loop:
for round in range(max_rounds):strokes = model.plan_next_strokes(state=canvas_history)canvas = render(canvas, strokes)critique = model.evaluate(canvas) # Evaluate whether proportions/structure/lighting meet the barif critique.passes():break# Append overpainting strokes based on critique
Evaluation dimensions can include:
- Structural completeness: whether object outlines are closed and proportions are reasonable;
- Light-and-shadow relationships: whether the direction of highlights and shadows is consistent;
- Color harmony: whether the warm-cool relationships and saturation are unified.
It needs to be stated objectively: diffusion models and code painting are two solutions with fundamentally different mechanisms, and a direct causal comparison is not valid. A diffusion model is essentially a single forward denoising generation process with no explicit “multi-round observe-and-refine” step; code painting is inherently a multi-round “generate–render–evaluate–refine” closed loop. So saying that “multi-round refinement improves structural stability” can only be understood as an engineering characteristic arising from the difference in mechanisms, not a causal judgment about a defect in diffusion models. In fact, the main problems of diffusion models concentrate on fine-grained local details such as fingers, text, and physical structures; in most ordinary scenarios their overall image quality is still significantly better than code painting. The advantage of code painting lies in a controllable, traceable process, not in “never falling apart.”
5. How Do You Shape a “Personified” Artistic Style? The Concrete Approach to a Style Vector
The cited case mentions an interesting practice: having the model design an artist persona with a “fictional background and a stable creative style” on its own, then guiding it via text feedback to adjust its brush and engine parameters. In engineering terms, this is equivalent to injecting a set of style priors into the model. When putting it into practice, you can solidify it into a structured configuration that echoes the BrushStroke data structure from Section 2:
{"style_vector": {"palette": ["#2b2d42", "#8d99ae", "#edf2f4"],"stroke_bias": { "texture": "dry", "wobble": 6, "width_range": [8, 40] },"composition": { "horizon": 0.62, "negative_space": 0.35 },"signature_move": "long horizontal dry strokes at edges"}}
A few reusable fields:
palette: a fixed palette preference (such as a cool-gray urban style), preventing colors from drifting randomly from piece to piece;stroke_bias: stroke habits (bold dry strokes versus delicate wet painting), which directly constrain stroke-generation parameters;composition: composition preferences (how much negative space, how high the horizon sits);signature_move: a recognizable “signature move,” such as long dry strokes at the edges, used to build individual identity.
Once style is externalized into a set of reusable parameters, multiple creations by the same model will show “personal identity” rather than drifting randomly with every piece. This is also a constructive answer to the criticism of “over-imitating existing masters’ styles” — rather than imitating others, it is better to accumulate your own style vector.
6. Code Painting vs. Diffusion Models: The Real Cost-Benefit Trade-off
It must be stated objectively: this “code painting” approach is not a replacement for traditional image generation models, but a complement aimed at specific scenarios. The table below gives the typical trade-offs:
| Dimension | Diffusion model (traditional) | Code painting (this paradigm) |
|---|---|---|
| Generation speed | Seconds | Slower; requires multiple rounds of planning and rendering |
| Structural controllability | Weak, prone to structural errors | Strong, controllable at the stroke level |
| Explainability | Low (latent space) | High (each stroke is an explicit instruction) |
| Realism ceiling | High (photorealistic) | Depends on the engine and brush library; needs many strokes layered |
| Compute resources | Requires GPU inference | Mainly CPU rendering + model inference |
| Style consistency | Hard to maintain | Easy to lock via style parameters |
On cost, the measurement basis of the following figures needs to be emphasized. In the case cited in this article (see the source note at the end; not independently verified), a shopping-cart work reaching “photorealistic” realism used about 700,000 simulated strokes, and the drawing program was about 1,000–2,000 lines of code; while the minimalist work of a bird at sunrise used only 111 strokes, with the first stroke colored #30346a, a brush width of 90 pixels, and a path with 5 wobble points, and the entire drawing process was compressed into a 21-second time-lapse video. All these figures come from a single case’s self-report; under different canvas resolutions, brush-library sizes, and hardware configurations they will vary by orders of magnitude. They can only be used to understand the qualitative conclusion that “stroke count is strongly correlated with image complexity and realism, and the cost is highly elastic,” and should not be directly extrapolated as a general benchmark.
7. Applicable Scenarios, Implementation Steps, and Common-Mistake Troubleshooting
This technique has clear value for the following scenarios:
- Teaching and outreach: visualizing the “drawing process,” where every stroke is traceable, is well suited to explaining perspective, light and shadow, and brush-stroke language;
- Controllable generation: when a business has strict requirements for structure, proportion, and physical plausibility (such as diagrams, engineering sketches, and chart-style illustrations), the controllability of strokes stands out;
- High demand for style consistency: scenarios that need to batch-produce material in the style of the same “artistic persona”;
- Auditability / reproducibility: each work is essentially a piece of code, naturally suited to version control, reproduction, and auditing.
If you want to implement it in your own system, the recommended approach is:
- Build a brush library first: abstract common strokes into a set of parameterizable stamps; this is the foundation of realism;
- Then build the rendering pipeline: adopt a “layered canvas” (background color at the bottom, color blocks in the middle, details on top) to make iteration and refinement easier;
- Finally connect the model loop: have the model output “structured stroke JSON” as its protocol, and use visual evaluation to drive multi-round refinement.
You can also use a cloud-based, general-purpose container platform to orchestrate rendering tasks, object storage to save canvas snapshots and code versions, and logging plus monitoring and alerting to track the time and stroke scale of each drawing round — these are all vendor-agnostic, generic capability categories.
Common Mistakes and Troubleshooting Checklist
- Excessive wobble: when
wobbleexceeds half the brush width, the line “falls apart”; keep it around 3–8 pixels first and increase gradually; - Wrong layer order: drawing the detail layer before the background layer means it will be covered by later color blocks; always preserve the “background → color blocks → details” order;
- Evaluation threshold too loose or too tight: if the
critique.passes()threshold is too loose, it causes repeated rework; if too tight, it fails to converge. Set an upper bound onmax_roundsand record the pass rate of each round; - Mismatched brush stamp size: if the stamp radius does not match
width, you get “broken strokes”; normalize the scaling before rendering; - Alpha stacking too deep: layered wet-on-wet blending easily turns colors gray; limit the number of wet-stroke layers in the same area;
- No canvas snapshots: multi-round refinement becomes untraceable, so be sure to save
canvas_historyeach round for reproduction and comparison.
Conclusion
“Not calling an image model, but drawing stroke by stroke with code” represents a shift in thinking worth paying attention to: turning generation from “black-box output” into “white-box planning + explicit execution + visual feedback.” It sacrifices some speed in exchange for structural controllability, an explainable process, and an accumulable style. For developers, understanding this paradigm means having one more tool for making fine trade-offs between “controllability” and “realism.”
It will not replace diffusion models, but in scenarios that “require process transparency, rigorous structure, and auditability,” it offers a highly imaginative path — one that lets AI not just “draw like the real thing,” but “know how it is drawing.”
Source note: The specific figures in this article — stroke counts, lines of code, colors, and sizes — as well as the “original case” content, are all relayed from a publicly available technical case article (original title: “AI large models don’t rely on image generation and can actually write code to paint stroke by stroke”), have not been independently verified, and are used only to explain the technical approach.
