How LLMs Draw Pictures by Writing Code: Principles and Practice Without Image Models

    This article examines an alternative approach to AI image creation in which a large language model does not output pixels directly but instead writes executable Python code that simulates a virtual brush moving across a canvas, stroke by stroke. It explains the technical principles behind this method, how it differs from mainstream diffusion-based image generation, and how the key modules can be implemented: task decomposition into stroke instructions, brush physics modeling, color and alpha compositing, canvas texture, a four-layer system architecture, a progressive drawing strategy, self-checking and refinement, and performance optimizations. It also covers style constraints, suitable use cases, current limitations, and possible improvements. The main takeaway is that LLMs can act as code generators and process planners, turning drawing into a readable, editable, reproducible program that is easier to control, audit, and iterate on.

    1. Introduction: Another Technical Path for AI Drawing

    A recent experiment in the field works like this: instead of outputting an image directly, a large model writes an executable Python program that simulates a brush moving across a virtual canvas, completing the drawing “one stroke at a time.” The whole process relies on no image generation model, and it needs no pre-rendered or traced base image. The idea has drawn attention in developer communities because it reframes the task of “generating an image” as the task of “writing a drawing program.”

    This article analyzes the phenomenon systematically: its technical principles, how it differs from mainstream image generation approaches, how the key modules are implemented, and the engineering lessons worth borrowing. Note that this article does not evaluate any specific vendor or product; it focuses on the underlying general capability: how a large model, acting as a code generator and process planner, can create work on a controlled virtual canvas that approaches photographic realism.

    2. Background: Where Traditional Image Generation and Code Drawing Diverge

    2.1 The Basic Logic of Mainstream Image Generation

    Most common AI image generation tools today are based on diffusion models. The typical flow starts from random noise and goes through multiple denoising steps that gradually approach the target image distribution; during training, the core objective is noise prediction. The user supplies a text prompt, and the model outputs a final pixel matrix.

    The strengths of this approach are that it is end-to-end, fast, and strong at rendering complex textures such as fur, fabric, and light scattering. The weaknesses are equally clear:

    • The process is not controllable: users cannot specify “what to draw on stroke number N,” and precise local edits are difficult.
    • Results are not traceable: an image is either generated or resampled, with no process-level audit trail.
    • Creative intent is hard to express: the diffusion process is essentially denoising, not planning.

    2.2 The Basic Logic of Code Drawing

    Code drawing takes a different route. The model first breaks the drawing task into a large number of discrete stroke instructions, each describing the brush type, brush size, color, path points, pressure, wetness, and motion curve. A drawing engine then interprets these instructions and renders them on the canvas stroke by stroke. The model does not output pixels; it outputs an executable, debuggable, reproducible program.

    The key differences of this paradigm:

    Dimension Diffusion Model Generation Code-Simulated Drawing
    Output Pixel matrix Stroke instruction sequence / drawing program
    Controllability Weak, prompt-dependent Strong, every stroke precisely controlled
    Reproducibility Depends on random seed High, same program, same result
    Debuggability Low High, stroke-by-stroke inspection and rollback
    Compute cost Single inference pass Multiple inference rounds plus render checks

    3. Technical Breakdown: How a Model “Draws” a Picture

    3.1 Task Decomposition: From Semantics to a Stroke Sequence

    Given a request like “draw a bird at sunrise,” the model first performs a structured decomposition:

    1. Scene understanding: identify the subject (bird), pose (perched or wings spread), lighting (sunrise, backlight, warm tones), and environment (branch, sky gradient).
    2. Composition planning: decide the canvas aspect ratio, subject placement, and negative space.
    3. Stroke decomposition: break the whole image into strokes, each serving a function (base color, outline, shadow, highlight, detail).
    4. Material selection: choose a brush type for each local need (round, flat, fan, airbrush, dry brush, and so on).

    The result is an ordered set of stroke instructions. For example, the first stroke might fill the sky with a base color in a deep indigo, using a wide brush whose path points jitter slightly to mimic a natural stroke.

    3.2 Brush Physics Modeling: Giving the Virtual Brush “Feel”

    The essence of code drawing is brush simulation. A usable brush model typically includes the following parameters:

    1. brush_spec = {
    2. "type": "round", # Brush type: round / flat / fan / dry
    3. "size": 90, # Brush diameter (pixels)
    4. "color": "#30346a", # Main color
    5. "opacity": 0.85, # Opacity
    6. "flow": 0.6, # Paint flow (simulates how wet it is)
    7. "wetness": 0.7, # Wetness; affects edge diffusion and blending
    8. "texture": "canvas_weave", # How the canvas texture absorbs paint
    9. "spacing": 0.1, # Spacing ratio between stroke stamps
    10. "jitter": 7, # Path jitter amplitude, simulating an unsteady human arm
    11. }
    12. def draw_stroke(canvas, points, brush):
    13. """Simulate one stroke along the given path points."""
    14. for i in range(len(points) - 1):
    15. p0, p1 = points[i], points[i + 1]
    16. # Diffuse the paint based on wetness and texture
    17. stamp = render_brush_stamp(brush, wetness=brush["wetness"])
    18. interpolate_and_stamp(canvas, p0, p1, stamp, spacing=brush["spacing"])
    19. return canvas

    Several engineering points matter here:

    • Wetness and edge diffusion: a wet brush on a dry canvas produces softer edges, while a dry brush leaves broken texture suited to rough surfaces.
    • Path jitter: perfectly straight lines often look stiff. The model can add a random offset of a few pixels to each path point to simulate human instability.
    • Paint blending: when wet paint meets wet paint, colors blend naturally; if the layer below is already dry, the result is coverage rather than blending. This requires the engine to maintain a “wetness layer” or “drying time” state.

    3.3 Color System: From Simple Colors to an Optical Approximation

    Photographic realism places high demands on color. A pragmatic approach includes:

    • Selecting colors in HSV/CIELAB space, avoiding the muddy results of direct RGB interpolation;
    • Simulating sub-pixel antialiasing to prevent jagged stroke edges;
    • Correct alpha compositing for transparent and semi-transparent paint;
    • Introducing slight color jitter so large color areas do not look overly uniform.
    1. def blend_pixel(base, top, alpha):
    2. """Correct alpha compositing; avoids color shifts from naive RGB mixing."""
    3. return (
    4. round(top[0] * alpha + base[0] * (1 - alpha)),
    5. round(top[1] * alpha + base[1] * (1 - alpha)),
    6. round(top[2] * alpha + base[2] * (1 - alpha)),
    7. )

    3.4 Canvas and Texture: Giving the Work a “Paper Feel”

    The canvas is not a pure white background but a substrate with micro-surface structure. Engineering options include:

    • A canvas texture map simulating weave, grain, and roughness;
    • A paint absorption model where peaks of the texture hold less paint and valleys hold more, producing natural unevenness;
    • A global lighting approximation that casts slight shadows from stroke ridges based on the light direction, enhancing depth.

    4. Engineering Implementation: A Practical Pipeline

    4.1 System Architecture

    A typical code drawing system splits into four layers:

    1. Dialog and planning layer: receives the user description and produces a drawing plan (canvas size, total stroke count, staged goals).
    2. Stroke generation layer: calls the large model to output structured instructions stroke by stroke (JSON or Python calls).
    3. Rendering engine layer: interprets stroke instructions and maintains canvas state, wetness state, and layer structure.
    4. Verification and feedback layer: analyzes the rendered result (composition, light and shade, outlines) and feeds problems back to the model to trigger corrections.

    4.2 Progressive Drawing Strategy

    Generating thousands of stroke instructions in a single pass is often infeasible because of context length limits, error accumulation, and style drift. A safer strategy is layered and progressive:

    1. plan = [
    2. {"stage": "background", "strokes": 20, "goal": "Sky and ground base colors"},
    3. {"stage": "blockout", "strokes": 50, "goal": "Main shapes and light/shade of the subject"},
    4. {"stage": "middetail", "strokes": 300, "goal": "Outlines and structural transitions"},
    5. {"stage": "detail", "strokes": 700, "goal": "Feathers, light and shadow, edges"},
    6. {"stage": "polish", "strokes": 200, "goal": "Highlights, reflections, atmosphere fixes"},
    7. ]
    8. for stage in plan:
    9. strokes = model.generate_strokes(canvas_state, stage)
    10. for s in strokes:
    11. render(canvas_state, s)
    12. feedback = analyze(canvas_state)
    13. model.refine(stage, feedback)

    After each stage, the system can capture a screenshot or sample a local region and hand it to the model for a “visual check,” spotting issues such as bad proportions, messy lines, or color contamination, then deciding the strategy for the next stage.

    4.3 Self-Check and Correction Mechanisms

    While drawing, the model needs the ability to “look at the image and fix it.” Typical practices include:

    • Local crop inspection: divide the canvas into regions and evaluate light/dark contrast, edge sharpness, and color consistency region by region.
    • Outline analysis: detect whether the subject outline is too thin or the jitter too large.
    • Semantic consistency check: use a multimodal model to confirm “does the current image still look like a bird.”
    • Corrective stroke generation: output additional strokes for problem areas instead of repainting the whole picture.

    For example, when the model finds the lines on the bird’s back too thin and messy, it can:

    1. Reduce the brush size in that area;
    2. Increase the number of path points to smooth the curve;
    3. Cover the messy lines with a semi-transparent base color, then redraw a more restrained outline.

    4.4 Performance and Cost Considerations

    The compute cost of code drawing comes mainly from two sources: multi-round inference of the large model and stroke-by-stroke computation in the rendering engine. Optimization directions include:

    • Batch rendering: merge multiple stamps of the same brush into a single operation;
    • Resolution tiering: use a low-resolution canvas for drafts and scale up for the detail stage;
    • Caching brush stamps: render a stamp once for a given set of brush parameters and reuse it;
    • Parallelization: compute independent strokes in parallel;
    • Instruction compression: replace per-pixel descriptions with parameterized functions to reduce model output length.

    5. Artistic Style and Model Behavior Design

    An interesting by-product of code drawing is that a model can develop a relatively stable “personal style.” This can be achieved by giving the model a virtual artist persona, for example with fictional experiences, preferred colors, and a habitual set of brush combinations, kept consistent across multiple creative sessions.

    Technically, this amounts to adding a style prior to the model:

    • Inject style descriptions into the prompt;
    • Predefine a set of “signature brushes” in the drawing engine;
    • Maintain persona consistency across multiple turns to avoid style drift;
    • Adjust style through text feedback rather than retraining.

    This “guiding creation with text” approach is lighter than modifying model parameters directly, and it suits exploratory creation better.

    6. Comparison with Mainstream Approaches and Suitable Scenarios

    Code drawing is not meant to replace diffusion models; it adds a way of creating that is process-controllable, auditable, and interactive.

    Scenario More Suitable Approach
    Fast concept art Diffusion models
    Precise local edits Code drawing
    Process-level traceability Code drawing
    Complex natural textures Diffusion models
    Teaching how drawing works Code drawing
    Automated pipelines with batch output Diffusion models

    For enterprise users, the value of code drawing is that it turns “AI drawing” from a black-box output into a software asset that can be version controlled, tested, and rolled back. Drawing scripts can live in a code repository and be audited via diffs; render results can be validated automatically by a CI pipeline; and an artistic style can be reused as a configuration item.

    7. Common Challenges and Directions for Improvement

    7.1 Current Limitations

    1. Long-range consistency is hard: when the stroke count reaches the hundreds of thousands, the model struggles to keep the global composition stable.
    2. It is slow: the serial flow of stroke-by-stroke generation and rendering makes real-time feedback difficult.
    3. Style depends on prompts: model style is easily influenced by the user’s description and lacks internal consistency.
    4. Evaluation is difficult: how to automatically judge “does it look right” remains an open problem.

    7.2 Possible Improvement Paths

    • Introduce an intermediate representation: have the model first generate a low-resolution draft and then use it as a constraint for generating strokes.
    • Hierarchical memory: maintain a summary of “completed regions” to avoid context explosion.
    • Multimodal closed loop: use a vision model to evaluate render results in real time, forming a “draw, look, fix” loop.
    • Brush learning: cluster commonly used brush parameters from past works into a toolbox the model can choose from.

    8. Conclusion

    By writing Python code that simulates a real brush, a large model demonstrates another possibility for generative AI: instead of handing pixels to an uninterpretable neural network, it turns the drawing process into a readable, editable, reproducible program. This path has distinct advantages in controllability, auditability, and interactivity, and it fits creative scenarios that require precise iteration.

    For developers, the key to understanding this paradigm is not “reproducing a particular painting” but grasping the engineering ideas behind it: decompose a complex task into discrete actions, build a physical model for each action, and achieve closed-loop correction through multiple rounds of feedback. This thinking applies not only to digital painting but also to broader creative programming areas such as procedural texture generation, 3D modeling, and animation keyframe design.