JSONtoIMG

Blog

  • The Tech Stack Behind a JSON-to-Image API

    A JSON-to-image API is a job queue, a renderer, object storage, and signed URLs. This post walks the real paths: POST /api/v1/render, POST /api/v1/renders/batch (max 50), GET /api/v1/img/… — not a fictional /v1/images API.

    Overview

    Every image generation API looks the same from the outside: you POST JSON, you get a PNG back. The interesting part is what happens between the request hitting the server and the bytes landing in your response. That’s where the real engineering decisions live — and where most DIY implementations quietly fall apart.

    This is the technical deep dive behind jsontoimg: why it renders images the way it does, what alternatives we evaluated, how the request pipeline is structured, and the specific trade-offs that shaped the architecture. If you’re building your own image pipeline (or just deciding whether to), this is the part nobody shows you.

    The Core Problem: Rendering Is a Resource Problem

    The moment you decide to generate images from data, you discover that the hard part isn’t the API — it’s the renderer. You have three honest options:

    Approach Example tools Fidelity Cost to run
    Headless browser Puppeteer, Playwright Pixel-perfect HTML/CSS High (Chromium is heavy)
    Vector rendering resvg, node-canvas, skia-canvas Great for flat layouts Low to medium
    Canvas/raster libs Sharp, Canvas API Great for photos/effects Low

    The temptation is to reach for a headless browser, because it gives you “real” HTML and CSS — and it’s what GitHub itself uses to render Open Graph previews. But a headless browser is also a full browser: hundreds of megabytes of RAM per instance, CPU spikes, version drift, and the constant babysitting of zombie processes. At scale, that cost shows up on your infrastructure bill as clearly as on a line item.

    The CustomJS blog summed up the hidden cost well: the browser library is easy — the queueing, browser updates, sandboxing, retries, and monitoring around it are what actually eat your engineering time.

    Why jsontoimg Doesn’t Run a Headless Browser

    The jsontoimg stack is built around deterministic template rendering, not HTML screenshots. That’s a deliberate choice, and it changes everything downstream.

    When you send JSON to jsontoimg, the request doesn’t describe a web page — it describes a layer stack: a background color, an image, some styled text, an overlay. Each layer maps to a renderable primitive. Because the input is constrained, the renderer can be constrained too.

    That gives us three properties a browser-based pipeline can’t match:

    1. Predictable memory — no tab, no DOM, no 60fps render loop. A render request uses a bounded, small amount of memory.
    2. Speed — vector rasterization of a flat composition takes milliseconds, not seconds. No page load, no networkidle2 wait, no font-loading race.
    3. Deterministic output — the same JSON always produces the same pixels. With a browser you’re one font-loading race away from a slightly different image on retry.

    This is the same trade-off that services like Bannerbear, Placid, and APITemplate.io make, and it’s why template-based image APIs are so much cheaper per render than screenshot services.

    The Rendering Pipeline

    Here’s the actual request flow inside jsontoimg:

    POST /api/v1/render (JSON payload)
            │
            ▼
    ┌─────────────────┐
    │  API gateway     │  auth, validation, rate limiting
    └────────┬────────┘
             ▼
    ┌─────────────────┐
    │  Template engine │  merge JSON data into template layers
    └────────┬────────┘
             ▼
    ┌─────────────────┐
    │  Renderer        │  vector rasterization → PNG/JPG buffer
    └────────┬────────┘
             ▼
    ┌─────────────────┐
    │  Storage         │  object storage + CDN URL
    └────────┬────────┘
             ▼
       image URL / webhook
    

    Layer 1: Template Engine

    Templates are stored as JSON schemas with typed layers — text, image, shape, group. The engine validates the incoming data against the schema, applies defaults, and resolves references (like layers.product_name.text or image URLs from your payload). This is a pure function: template + data → resolved composition. No side effects, no I/O, trivially testable.

    Layer 2: The Renderer

    The resolved composition is rasterized using a native vector renderer — not a browser. For text, that means explicit font handling: fonts are bundled and subsetted server-side, so “the title wraps differently on the 3rd render” is a problem we simply don’t have. For images, it means decoding input images (logos, backgrounds, product shots), scaling them to the layer bounds, and compositing with alpha blending.

    Transparent PNG output is a first-class feature here — when the composition has no background layer, the alpha channel survives the pipeline. That’s how you can generate overlay graphics and logos, not just full-bleed cards.

    Layer 3: Storage and Delivery

    Every generated image is persisted to object storage and served through a CDN with cache headers. That means:

    • Renders are idempotent — requesting the same image twice returns the stored copy, not a fresh render
    • Response times for repeat requests are CDN-fast
    • Batch jobs don’t hold webhook payloads hostage to slow clients

    The browser overhead is not a matter of opinion — Puppeteer's own containerisation guide walks through the shared-memory limits, sandbox flags, and font packages a headless Chrome image needs before it will render reliably, which is a fair summary of the operational surface you inherit. Skipping it leaves the pipeline with a much smaller job: composite layers, write the file, and cache it. Delivery then follows ordinary web caching rules, where Cache-Control decides how long an edge keeps a rendered image and web.dev's CDN primer explains why serving it from the edge matters more than shaving milliseconds off the render. Choosing what to write is the other half, and MDN's image file type guide is the reference we work from, and web.dev's format guidance is why WebP rather than PNG is the sensible default for anything bound for a browser.

    Sync vs Async: The Two-Path Design

    A common mistake in image APIs is forcing everything through one mode. jsontoimg supports both:

    • Synchronous — for single images where you want the bytes in the response. Ideal for on-demand OG images and user-facing graphics.
    • Asynchronous with webhooks — for batches. POST an array of payloads, get a job ID, and receive a callback when the whole batch is done.

    The batch path uses a worker queue. Each item is a self-contained render job, so the queue scales horizontally: add workers, consume faster. This is the architecture that makes “generate 10,000 product banners” a plausible afternoon task instead of a weekend project. (See our product banner generator use case for how that plays out in practice.)

    What We Chose NOT to Build

    Being an indie product means every layer you add is a layer you maintain. The stack deliberately stops at the edges:

    • No visual template editor — templates are JSON, versioned in your repo, reviewed in PRs. Designers can use Figma → export a spec; developers ship it. The getting started guide walks through the flow end to end.
    • No queuing monolith — the queue is a thin layer, not a platform. If you need orchestration, your existing pipeline (n8n, Make, your own workers) can call the API directly.
    • No browser emulation — if you genuinely need to screenshot a live web page, a screenshot API is the right tool. That’s not this product, and that’s fine.

    The discipline is the point: every “no” keeps the core render path fast, cheap, and predictable.

    The Cost Math That Validated the Approach

    The resource difference between browser-based and vector rendering isn’t subtle. Rough numbers from operating this class of pipeline:

    Metric Headless browser render jsontoimg-style render
    Memory per render 100–250 MB (Chromium) < 50 MB
    Cold render latency 1–5 s (page load + fonts) 50–300 ms
    Retry variance font/timing races none (deterministic)

    That’s the difference between “a service that occasionally costs you real money” and “a function you can call in a loop without thinking.” For teams generating images inside request paths — dynamic OG images, personalized emails, event tickets — that variance is what kills the UX. This is exactly why our Open Graph image and event ticket use cases are built on the synchronous path.

    Key Takeaways

    • The renderer is the architecture. Everything else — API shape, pricing, reliability — follows from whether you render with a browser or with a vector rasterizer.
    • Constrained input enables constrained cost. JSON layer stacks render fast and predictably; HTML screenshots don’t.
    • Two-path design matters. Sync for single images, async + webhooks for batches, and a worker queue that scales horizontally.
    • Storage is part of the product. Idempotent renders + CDN delivery mean repeat requests are cheap and fast.
    • Saying no is a feature. No browser, no visual editor, no queue monolith — every omission keeps the core path lean.

    FAQ

    Why not run a headless browser for image generation?

    A browser loads a full web engine per render, which means heavy memory, cold starts, and font surprises for every image. Compositing named layers directly removes that whole dependency and makes render time predictable.

    What is the difference between the sync and async render paths?

    The sync path renders and returns a single image in the request, which is what an Open Graph image generator or an interactive flow needs. The async path queues the job and reports back by webhook, which is what a batch of thousands needs.

    Where are rendered images stored and served from?

    Each render is written to object storage and served over a CDN, so the first unique request pays the render cost and every later request streams the stored file.

    Related Resources

    Zoom out: How JSON-to-Image Conversion Works maps the whole template, named-layer, and render-job architecture.

  • Placid vs jsontoimg: Request Shape and DX

    Request shape and DX, not the marketing comparison. Rankings for “placid alternative” belong on /alternatives/placid. Here: layers vs Placid’s REST, 422s, batch max 50, n8n vs native Zapier.

    Overview

    If you’re automating image generation, Placid is one of the first names you will hit. It’s been around since 2019, has a polished template editor, and covers images, PDFs, and video from one credit pool. It’s a genuinely good product — but “good” isn’t the same as “right for your pipeline.”

    This post is the developer’s version of the full jsontoimg vs Placid comparison. We’ll skip the marketing pages and look at what actually matters when you’re writing code against an image API: the request shape, the render lifecycle, cost per image at real volumes, and the failure modes you’ll hit in production.

    Short version: if you need images only — OG cards, product banners, certificates, ad variants — jsontoimg gives you roughly 2× the renders per dollar and a simpler API surface. If you need mixed media (images *and* PDFs *and* video) from one platform, Placid’s credit pool makes sense. Everything below is the “why” behind that sentence.

    What Each API Actually Looks Like

    Both tools use the same mental model — design a template, send JSON, get an image. The differences show up in the request shape.

    Placid: layers against a template UUID

    Placid’s image API takes a template_uuid plus a layers object that maps layer names to values:

    curl -X POST https://placid.app/api/rest/creations \
      -H "Authorization: Bearer YOUR_API_KEY" \
      -H "Content-Type: application/json" \
      -d '{
        "template_uuid": "your-template-uuid",
        "layers": {
          "headline": "50% off this week only",
          "subtitle": "Use code WEEK50 at checkout",
          "background": "#1a1a2e"
        }
      }'
    

    The response comes back with a status field — pending or done — and an image_url you poll or receive via webhook (Placid REST API docs). Placid also offers a URL-based API where you put parameters directly in the URL, which is handy for quick social-sharing integrations (Placid Image Automation API).

    jsontoimg: JSON in, image out

    jsontoimg keeps the same idea but collapses it to a single render endpoint. You send the template reference and the data to fill it:

    curl -X POST "https://app.jsontoimg.com/api/v1/render?wait=60" \
      -H "Authorization: Bearer $JSONTOIMG_API_KEY" \
      -H "Content-Type: application/json" \
      -d '{
        "template": "share-card",
        "format": "png",
        "layers": {
          "headline": { "text": "50% off this week only" },
          "subtitle": { "text": "Use code WEEK50 at checkout" }
        }
      }'
    

    One endpoint, one JSON body, one image back. No separate creation/polling endpoints to learn, no URL-encoding dance for complex payloads. If you’ve used Bannerbear’s modifications array or Placid’s layers object, the pattern transfers in minutes — that’s the point of the JSON-to-image convention.

    Cost Per Image: Where the Math Bites

    This is the table that matters if you generate more than a few hundred images a month. Both tools price on credits; the difference is what a credit buys and whether your credit pool is shared with other output types.

    Tier jsontoimg Placid
    Entry $29/mo — 1,000 images $29/mo — 500 credits
    Mid $49/mo — 5,000 images $39/mo — 2,500 credits
    High $99/mo — 15,000 images $89/mo — 25,000 credits
    Cost per image (entry) $0.019 $0.038

    Two things to flag:

    1. Placid’s credits are shared across images (1 credit), PDF pages (2 credits), and 10-second video clips (10 credits). If you only render images, you’re effectively subsidizing video and PDF capacity you’ll never touch.
    2. Rollover is capped. Placid rolls unused credits over, but only up to 2× your monthly allowance — so you can’t bank a light month to cover a heavy launch (Placid pricing FAQ).

    At 15,000 images/month, that’s $99 on jsontoimg vs $569 on Placid if every credit goes to images — and Placid’s $89 “Business” tier gives 25,000 *credits*, not 25,000 images. For stills-and-PDF workloads, the effective price gap is roughly 2× at every tier.

    Render Lifecycle and Production Safety

    The subtle differences are in what happens when your templates change.

    Placid lets you edit templates in its Studio, and the same template can be referenced by live automations. That’s flexible, but the docs don’t describe immutable versioning — an edit to a shared template is visible to every render that references it.

    jsontoimg pins each render to the template version that was live when you enqueued it. You can iterate on a template freely without worrying that a mid-launch edit corrupts in-flight renders. For certificate generators, event tickets, and anything with compliance implications, that immutability is the difference between “ship it” and “please don’t touch the template.”

    Both tools support webhooks for async completion. jsontoimg also offers a long-poll endpoint (GET /renders/{id}/wait) and SSE events for render completion, so you can avoid polling loops entirely.

    Failure Modes You’ll Actually Hit

    • Text overflow: Placid auto-resizes text to fit its containers; jsontoimg gives you explicit width/align control per text layer. If you need pixel-exact typography (brand guidelines, legal fine print), explicit control wins.
    • Batch jobs: jsontoimg accepts an array of payloads in one request and returns an array — one HTTP round-trip for thousands of renders. Placid handles batches via webhook fan-out; you manage the queue yourself.
    • Transparent backgrounds: jsontoimg outputs PNG with alpha channel directly. Placid supports transparency too, but it’s a template-layer setting rather than an output mode.
    • Auth: jsontoimg accepts Bearer or X-Api-Key headers; Placid uses Bearer. Marginal, but if you’re wiring into a legacy system that only sets headers, it matters.

    Decision Framework

    Choose jsontoimg if:

    • Your output is stills (OG cards, banners, certificates, ad variants, social posts)
    • You render more than ~1,000 images/month and care about per-image cost
    • You want one endpoint, explicit text control, and version-pinned renders
    • You want batch array requests and long-poll/SSE completion instead of queue management

    Choose Placid if:

    • You need images and PDFs and video from one platform and one credit pool
    • You rely on the URL API for dead-simple social share links
    • You want a Canva-style editor with a built-in design library for non-developers
    • Mixed-media capacity is a feature you’ll actually use, not a premium you’ll pay for

    Key Takeaways

    • Both tools use the template + JSON pattern, so the mental model transfers — but the request shapes and render lifecycles differ in production-relevant ways
    • For stills-and-PDF pipelines, jsontoimg is cheaper per render at every tier ($0.029 vs Placid Basic at entry)
    • Placid’s shared credit pool is a feature for mixed media and a tax for image-only workloads
    • Version-pinned templates on jsontoimg protect in-flight renders from template edits
    • Batch array requests and long-poll/SSE completion simplify high-volume pipelines

    FAQ

    How do Placid credits compare to jsontoimg credits?

    Placid's pool is mixed: one image is one credit, ten seconds of video is ten, and a PDF page is two, with unused credits rolling over to 2x the plan. jsontoimg bills one credit per still or PDF page and nothing else, and prepaid packs never expire.

    Does jsontoimg have a native Zapier app like Placid?

    Not yet. There is an n8n community node, a WordPress plugin, a REST API, an MCP server, and a CLI. Zapier, Make, Sheets, and Airtable connect over plain HTTP until native connectors ship.

    Does jsontoimg render video?

    No. If a single vendor has to cover image, video, and PDF creative, Placid is the better fit. jsontoimg is a typed stills-and-PDF image generation API.

    Which one should I pick?

    Pick Placid for mixed media and native no-code surfaces. Pick jsontoimg when you want a predictable JSON to image request, versioned templates, and a flat per-image price.

    Related Resources

    Zoom out: How JSON-to-Image Conversion Works maps the whole template, named-layer, and render-job architecture.

  • JSON Image Templates with Named Layers (Not Mustache)

    jsontoimg templates are designed in the visual editor. The JSON you send is layer overrides (layers.headline.text), not a mustache document that describes every rectangle. This guide is the naming and overflow rules that survive production.

    Overview

    With a JSON-to-image API, the template is the product. Your API calls can be perfect — the right endpoint, the right auth, the right payload — but if the template is designed poorly, every image that comes out will look broken. Text overflows its box, images stretch instead of crop, and a price that looks fine at 3 characters turns into a disaster at 8.

    This guide covers everything you need to design JSON image templates that render beautifully at any volume. We’ll walk through the anatomy of a template, each layer type, how dynamic text actually behaves, the naming conventions that keep your integrations stable, and a complete worked example: a product banner built end to end.

    If you haven’t made your first render yet, start with the getting started tutorial — this guide assumes you know the basic flow: design a template, send JSON, get an image.

    Why the Template Is the Contract

    In a template-based image API, everything is separated into two parts:

    1. The template — the visual layout with placeholders. Designed once.
    2. The data — JSON that fills those placeholders. Sent on every render.

    This separation is what makes the whole model work. A template-based image generation API “renders variable text, images, prices, and other structured data inside a predefined visual layout” — that’s the definition used across the industry (Abyssale’s roundup of template-based APIs puts it exactly that way). Bannerbear describes the same pattern as “design once, render many,” where every layer in the template becomes an object you can modify dynamically in your API request.

    The design quality of that template is the single biggest factor in how good your generated images look. Data can’t fix bad layout — but a well-designed template can absorb almost any data you throw at it. So the real skill is designing templates that are *data-tolerant*: they still look right when the title is 20 characters, and still look right when it’s 120.

    The Anatomy of a JSON Template

    Every jsontoimg template is a JSON document with three parts: the canvas, the background, and an ordered layers array.

    {
      "width": 1200,
      "height": 630,
      "background": {
        "type": "gradient",
        "colors": ["#1a1a2e", "#16213e", "#0f3460"]
      },
      "layers": [
        {
          "type": "text",
          "name": "headline",
          "text": "Your headline goes here",
          "font": { "size": 72, "weight": "bold", "color": "#ffffff" },
          "position": { "x": 80, "y": 200 },
          "width": 1040,
          "align": "left"
        }
      ]
    }
    

    Breaking it down:

    • Canvas — width and height in pixels. Design at the exact dimensions you’ll use in production. A 1200×630 social card, a 1080×1080 post, a 2000×800 banner. Don’t design big and scale down — text sizes and stroke weights are tuned per dimension.
    • Background — solid color, gradient, or an image. The background is the foundation; everything else renders on top of it.
    • Layers — an ordered array. Later layers render on top of earlier ones, like a design tool’s layer panel. The order is part of the design, not an accident of your JSON.

    Every layer needs a type and a name. The type tells the renderer what to draw; the name is the handle your API calls will use to target it.

    Layer Types: Text, Image, and Shape

    Text layers

    The workhorse of dynamic image generation. Text layers control their own typography:

    {
      "type": "text",
      "name": "price",
      "text": "$49",
      "font": {
        "size": 48,
        "weight": "bold",
        "color": "#f59e0b"
      },
      "position": { "x": 80, "y": 420 },
      "width": 400,
      "align": "left",
      "line_height": 1.2
    }
    

    Key properties: size, weight, color, align (left/center/right), line_height, and — most importantly — width. The width defines the wrapping box. Text that exceeds the box wraps to the next line; combined with line_height this determines how much vertical space the text block occupies.

    Image layers

    For logos, product photos, avatars, and background imagery:

    {
      "type": "image",
      "name": "product_photo",
      "image_url": "https://cdn.example.com/products/sneaker.png",
      "position": { "x": 700, "y": 80 },
      "width": 420,
      "height": 470,
      "fit": "cover",
      "opacity": 1.0
    }
    

    The fit property matters more than people think:

    • cover — fills the box, cropping the overflow. Best for photos where the subject fills the frame.
    • contain — fits the whole image inside the box, letterboxing with transparency. Best for logos and product shots on white backgrounds.
    • fill — stretches to the box. Almost never what you want.

    If you use cover, remember the box is a *crop window*. Center-weighted images survive cropping better than compositions with critical detail at the edges.

    Shape layers

    Badges, dividers, price tags, and accent blocks:

    {
      "type": "shape",
      "name": "price_badge",
      "shape": "rect",
      "fill": "#f59e0b",
      "radius": 12,
      "position": { "x": 60, "y": 400 },
      "width": 440,
      "height": 80
    }
    

    Shapes give you the design elements that would otherwise be static: a highlight bar behind a headline, a rounded container behind a price, a divider line between sections. Layer them *behind* the text they support — order in the layers array is z-order.

    Naming Layers: The API Contract

    Here’s the rule that saves the most pain later: the name you give a layer is the key you’ll use in every API call, forever. Bannerbear’s own guidance is blunt about this — the names you give your layers are what you reference in your API requests, so get in the habit of naming clearly.

    That means:

    • Use stable, semantic names: headline, subtitle, price, product_name, cta_text, logo.
    • Never use positional names: text_1, layer_2, box_left. They describe location, not meaning, and the meaning is what your data pipeline cares about.
    • Use snake_case consistently so the names transfer cleanly into JSON keys and code variables.
    • Treat names as immutable. Changing product_name to title breaks every integration that sends product_name — silently. The render will fall back to the default text and nobody will notice until the images are wrong.

    A good test: if you handed the layer list to a developer with no design context, would they know what data to send for each name? If not, rename it.

    Dynamic Text Done Right

    This is where most template quality is won or lost. Dynamic text is unpredictable by nature — you don’t control how long a product name or a blog title will be. A data-tolerant template handles that gracefully.

    1. Give every text layer a sensible default

    The text value in the template is the default. When an API call doesn’t override a layer, the default renders. Sensible defaults make the template testable in an editor (you see something reasonable) and give you graceful fallback when data is missing. text: "" is a valid value — sometimes you want an empty layer to collapse when there’s no data.

    2. Design the box, not the text

    Set an explicit width and let text wrap. Design the box with enough height for the *worst case* you expect, not the average. A headline box designed for a 40-character title will overflow (or clip) at 90 characters.

    3. Use auto-fit for critical short text

    For one-line text that must never wrap — prices, names, badge labels — enable auto-fit so the font shrinks to fit the box instead of overflowing:

    {
      "type": "text",
      "name": "price",
      "text": "$49",
      "font": { "size": 64, "weight": "bold", "color": "#ffffff" },
      "position": { "x": 80, "y": 410 },
      "width": 400,
      "height": 70,
      "auto_fit": "shrink"
    }
    

    The renderer starts at size and shrinks until the text fits the box. This is the difference between a price that reads “$49” at any digit count and a price that spills over the badge.

    4. Plan for overflow, don’t ignore it

    For multi-line text (headlines, descriptions), decide what happens at the limit: allow wrapping with a fixed line count, or clip with an ellipsis. The render pipeline in template APIs typically applies “automated content adjustments” like auto-sizing and alignment before the final render (Robolly documents this exact pipeline: load template → apply modifications → auto-adjust content → render). Use those adjustments deliberately — set the max lines and let the engine handle the rest.

    5. Watch the edges

    Dynamic text doesn’t respect your padding. Keep text boxes away from the canvas edges — a 40px margin in the template becomes 0px when the text is bold and long. And when text sits on top of a photo background, add a scrim (a semi-transparent shape layer) or a gradient behind it so contrast never depends on what image arrives that day.

    Two of those rules have standards behind them rather than taste. Overflow behaviour in CSS is governed by text-overflow, and the reason an ellipsis reads better than a clipped glyph is the same in a rendered image as it is on a page: a truncation the reader can see is information, while a silently cut word is a bug. Contrast is the other one — WCAG 2.1's contrast minimum asks for 4.5:1 for body text and 3:1 for large text, and a template that fails it will fail it for every image it ever renders. Font loading deserves the same up-front thought; web.dev's font best practices covers why a missing weight substitutes silently instead of erroring.

    Defaults, Overrides, and Versioning

    • Defaults live in the template. Every render starts from the template’s values.
    • Overrides come from the API call. The layers object replaces values per named layer.
    • Never edit a template that’s live in production. Create a new version instead. When you change a layer’s name, size, or position, every queued render and every integration referencing that template behaves differently — often invisibly.

    Treat templates the way you’d treat a database schema: versioned, reviewed, and never mutated in place once integrations depend on it.

    Worked Example: A Product Banner

    Let’s put it together. A 1200×630 product banner with a product name, a price badge, a product photo, and a call to action — designed to survive real data.

    Template:

    {
      "width": 1200,
      "height": 630,
      "background": {
        "type": "image",
        "image_url": "https://cdn.example.com/bg/dark-hero.jpg"
      },
      "layers": [
        {
          "type": "shape",
          "name": "scrim",
          "shape": "rect",
          "fill": "rgba(10, 10, 20, 0.55)",
          "position": { "x": 0, "y": 0 },
          "width": 1200,
          "height": 630
        },
        {
          "type": "image",
          "name": "product_photo",
          "image_url": "https://cdn.example.com/products/default.png",
          "position": { "x": 680, "y": 80 },
          "width": 440,
          "height": 470,
          "fit": "cover"
        },
        {
          "type": "text",
          "name": "product_name",
          "text": "Your product name",
          "font": { "size": 56, "weight": "bold", "color": "#ffffff" },
          "position": { "x": 80, "y": 190 },
          "width": 520,
          "line_height": 1.15
        },
        {
          "type": "shape",
          "name": "price_badge",
          "shape": "rect",
          "fill": "#f59e0b",
          "radius": 14,
          "position": { "x": 80, "y": 400 },
          "width": 260,
          "height": 76
        },
        {
          "type": "text",
          "name": "price",
          "text": "$49",
          "font": { "size": 44, "weight": "bold", "color": "#1a1a2e" },
          "position": { "x": 100, "y": 412 },
          "width": 220,
          "height": 52,
          "auto_fit": "shrink"
        },
        {
          "type": "text",
          "name": "cta_text",
          "text": "Shop now",
          "font": { "size": 30, "weight": "medium", "color": "#f59e0b" },
          "position": { "x": 80, "y": 520 },
          "width": 300
        }
      ]
    }
    

    Notice what makes it data-tolerant:

    • The scrim shape guarantees text contrast over any background image.
    • product_name has a width and wraps; the badge is positioned well below the worst-case two-line name.
    • price uses auto_fit: "shrink" so “$9” and “$1,299.00” both fit the badge.
    • The product photo uses cover with a centered default — crops gracefully.

    Render it:

    curl -X POST "https://app.jsontoimg.com/api/v1/render?wait=60" \
      -H "Authorization: Bearer $JSONTOIMG_API_KEY" \
      -H "Content-Type: application/json" \
      -d '{
        "template": "product-banner",
        "format": "png",
        "layers": {
          "product_name": { "text": "Aurora Wireless Headphones" },
          "product_photo": { "imageUrl": "https://cdn.example.com/products/aurora.png" },
          "price": { "text": "$129.00" },
          "cta_text": { "text": "Buy now" }
        }
      }'
    

    Same template, different data — that’s the whole model. One template, thousands of SKUs. The product banner use case page shows this exact workflow scaled to an entire catalog.

    Format is a template-level decision too, not an afterthought at request time. web.dev's format guidance puts WebP and AVIF well ahead of JPG at matched quality for anything served to a browser, while MDN's image file type guide is the reference for where each one is actually safe to use. The last pitfall is the one the API protects you from: an unrecognised layer key returns a 422 Unprocessable Content rather than rendering a half-filled image, so a typo surfaces in your logs instead of in a customer's inbox.

    Common Pitfalls (and How to Avoid Them)

    Pitfall Symptom Fix
    Text overflows its box Words clipped mid-glyph, overlapping layers Set width, enable auto_fit for one-liners, design for worst case
    No defaults on layers Broken images when data is missing Give every layer a sensible default value
    Wrong image fit Stretched logos, cropped product shots cover for photos, contain for logos
    Renaming live layers Integrations silently render default text Treat names as immutable; version templates instead
    Text on busy backgrounds Unreadable headlines Add a scrim or gradient shape layer behind text
    Variable-height text under fixed layout Elements overlap when text wraps Reserve vertical space; place lower layers below the worst-case text block

    Key Takeaways

    • The template is the contract between your design and your data — design it to be data-tolerant, not just pretty.
    • Layer names are the API surface: stable, semantic, snake_case, immutable.
    • Dynamic text needs explicit boxes: width for wrapping, auto_fit for critical one-liners, defaults for graceful fallback.
    • Never edit a live template — version it. Integrations depend on its exact shape.
    • Order matters: the layers array is z-order, and backgrounds/scrims belong first.
    • A single well-designed template can produce thousands of distinct images — that’s the entire point.

    FAQ

    What makes a good layer name in an image template?

    A stable, lowercase, descriptive name that describes the slot rather than the current content — product_title, not heading_2. The layer name is the API contract, so renaming it is a breaking change for every caller.

    What happens if I send a layer name the template does not have?

    The render is rejected with a 422 rather than silently dropping the value. A typo in a layer key fails loudly instead of shipping an image with a missing headline.

    How do I stop long dynamic text from overflowing?

    Design the box, not the string: give every text layer a sensible default, size the frame for the longest realistic value, and turn on auto-fit for short critical text so it scales down instead of spilling.

    Can I redesign a template without breaking live renders?

    Yes. Pin design_version in the request and your integration keeps rendering the version it was built against while you edit the draft.

    Related Resources

    Zoom out: How JSON-to-Image Conversion Works maps the whole template, named-layer, and render-job architecture.

  • 7 Lessons from Launching a Stills-and-PDF Image API

    Seven launch notes: time-to-first-call, docs, a narrow stills-and-PDF wedge (we do render PDF pages), public pricing, and distribution. PDF is in the catalog; video is not.

    Overview

    Launching jsontoimg — a JSON-to-image API — taught me that the API itself is the easy part. The renderer took weeks; everything around it took months. This post collects the seven lessons that actually moved the needle: time-to-first-call, docs as product, picking a narrow wedge, transparent pricing, distribution, building in public, and market timing. If you’re launching a developer tool, steal the parts that fit.

    Lesson 1: The API Is One-Third of the Product

    The most repeated line in indie founder launch threads is also the truest: *”the product is one-third of the product”* (Indie Hackers, 5 Lessons Learned from Launching my first SaaS). As a developer, shipping code is the comfortable part. The hard part is everything users touch before, during, and after the first request:

    • The docs — can a stranger understand the API in one page?
    • The signup flow — how many clicks between landing and API key?
    • The error messages — do failures teach or confuse?
    • The pricing page — is the cost obvious or hidden behind “Contact sales”?
    • The first response — is it fast enough to feel magical?

    jsontoimg’s rendering engine was the smallest slice of the build. Templates, webhooks, batch endpoints, transparent status on every render, and clear errors took far more design effort than the renderer itself. Developers don’t fall in love with your architecture; they fall in love with the *experience* of using it.

    Lesson 2: Time-to-First-Call Is the Metric That Matters

    Postman calls time-to-first-call (TTFC) “the most important API metric,” and the data backs it up: developers using a pre-built collection made a successful first call 1.7× to 56× faster than those starting from scratch (Postman Blog). Fern’s developer onboarding research puts concrete numbers on the bar: under two minutes from docs landing to first successful call puts an API in the top tier — anything over ten minutes signals major onboarding friction (Fern).

    What that meant for jsontoimg:

    1. The homepage leads with a complete, copy-pasteable request — no signup wall before you see the shape of the API.
    2. Every tutorial starts from a working example, not from theory.
    3. A real API key is issued in seconds after signup, with a generous free tier so the first call costs nothing.

    The goal was boring on purpose: a developer lands, pastes one curl, and gets an image back before their coffee cools.

    curl -X POST "https://app.jsontoimg.com/api/v1/render?wait=60" \
      -H "Authorization: Bearer $JSONTOIMG_API_KEY" \
      -H "Content-Type: application/json" \
      -d '{
        "template": "og-card",
        "format": "png",
        "layers": {
          "title": { "text": "First image in 30 seconds" },
          "subtitle": { "text": "JSON in, image out" }
        }
      }'
    

    Lesson 3: Docs Are the Product — Write Them Like Code

    API product marketers are unanimous on the launch checklist: documentation live and polished on day one, a single-page quick-start, and showcase projects developers can copy (Stackmatix). Kong’s API product guide adds the important nuance: don’t stop at the reference — organize docs around use cases and workflows, so developers can move from setup to production quickly (Kong).

    That’s exactly why jsontoimg ships a dedicated page for every use case instead of one giant reference:

    Each page answers one question: *”I have this problem — how do I solve it with jsontoimg?”* A developer who finds their exact scenario in the docs is a developer who stays.

    Lesson 4: Pick a Narrow Wedge and Own It

    The biggest temptation in a fast-growing market is to become a platform. jsontoimg deliberately stayed a stills-and-PDF API. No video pipeline, no workflow builder. Competitors like APITemplate.io bundle templates, documents, and automation — genuinely powerful, but a much larger surface to learn, maintain, and price.

    The indie hacker MVP rule applies: ship one or two features and make them excellent. jsontoimg launched with templates, batch generation, and webhooks. Everything else waited for a user to ask for it. A narrow wedge is also a positioning gift — when a developer asks “what does this do?”, the answer is one sentence: *JSON in, image out.*

    Lesson 5: Transparent Pricing Is a Growth Feature

    Developers are allergic to “Contact sales.” They want to know the cost before they invest an afternoon integrating. The playbook for developer products is consistent: transparent, usage-based pricing with a free tier when you can afford it (Markepear).

    jsontoimg follows the same philosophy:

    • Free tier to build and test without a credit card
    • Usage-based pricing that scales with actual renders — no platform fees, no seat costs
    • Published numbers on the pricing page, because hiding them only delays the conversation

    Pricing is part of the developer experience. If the cost math is easy, the decision is easy.

    Lesson 6: Launch Is the Start of Distribution, Not the End

    A launch is a moment; distribution is a habit. The standard channels still work — Hacker News, Product Hunt, and the relevant subreddits (Stackmatix) — but the compounding channel is building in public (Engineers Codex, 10 Lessons from One-Person Startups). The image-API space has living proof: Jon Yongfook publicly shared ~$52k/month across Bannerbear and Browserbear, both built and marketed in the open.

    For jsontoimg, building in public means this blog: the story behind ditching Puppeteer, the use case deep dives, and the honest comparisons. Every post is a distribution asset that keeps working after launch week ends. Ship the product, then ship the story of the product.

    Lesson 7: The Market Is Bigger Than It Looks — Stay Focused

    The AI-powered image generation tool market is projected to grow from $9.1 billion in 2025 to $272.8 billion by 2035 — a 40.5% CAGR (Market.us). MarketsandMarkets pegs the AI image generator segment alone at $8.7 billion in 2024, reaching $60.8 billion by 2030 (38.2% CAGR) (MarketsandMarkets).

    The slice jsontoimg cares about is the deliberately *boring* one: structured, programmatic image generation — OG cards, product banners, certificates, email heroes. Boring is good. It’s predictable, repeatable, and every product team on earth needs it. The temptation is to chase the flashy text-to-image trend; the discipline is to keep solving the boring problem better than anyone.

    Key Takeaways

    • The API is one-third of the product — docs, onboarding, and pricing decide adoption.
    • Time-to-first-call is the metric that matters; aim for under two minutes.
    • Organize docs around use cases, not just endpoints.
    • Stay stills-and-PDF: a narrow wedge is easier to build, price, and explain.
    • Transparent, usage-based pricing with a free tier builds developer trust.
    • Launch is the start of distribution — building in public compounds.
    • The market is huge; focus on the boring, repeatable slice and own it.

    FAQ

    What is the hardest part of launching an image generation API?

    The API itself is about a third of the work. The editor that produces templates, the docs that get someone to a first call, and metered billing are the other two thirds — and they are what people actually judge.

    What onboarding metric matters most for a developer API?

    Time-to-first-call. Every minute between signing up and seeing a rendered image is a chance to lose the developer, which is why jsontoimg gives 25 free images with no card.

    Why target a narrow wedge instead of an all-in-one platform?

    A stills-and-PDF image generation API can be typed, predictable, and cheap per image. Adding video, screenshots, and AI layers widens the surface and blurs the pricing, which is exactly the confusion a dynamic image API should remove.

    Does publishing prices actually help growth?

    Yes. A published price per image lets a developer finish the build-versus-buy math alone, in the tab they are already in, without booking a call.

    Related Resources

  • APITemplate.io vs jsontoimg: HTML-PDF vs Named Layers

    Named-layer canvas vs HTML-to-PDF. The alternative page is /alternatives/apitemplate. This post is payload shape, template caps, and when to keep APITemplate for invoices.

    Overview

    APITemplate.io has a smart pitch: one API for images and PDFs, with an HTML/CSS editor, Jinja2 templating, and integrations for Zapier, Make, n8n, and Airtable. If your stack genuinely spans multiple output formats, that’s a real advantage.

    But most teams evaluating it are generating stills — OG cards, product banners, certificates, ad variants — and “images plus everything else” comes with a price: a shared credit pool, a bigger API surface, and templates that mutate in place.

    This post is the developer’s version of the full jsontoimg vs APITemplate.io comparison. We’ll look at what the APIs actually look like when you write code against them, what a render costs at real volumes, and how the two products behave differently in production.

    Short version: for stills-and-PDF pipelines, jsontoimg is roughly 1.8× cheaper at entry with a single render endpoint and versioned templates. APITemplate.io wins when you genuinely need PDFs from the same account. Everything below is the “why” behind that sentence.

    What Each API Actually Looks Like

    Both tools follow the same mental model — design a template, send data, get an image. The differences appear in the request shape and the render lifecycle.

    APITemplate.io: multi-format, one shared pool

    APITemplate.io’s image API takes a template_id plus a modifications object that maps template fields to values:

    curl -X POST https://api.apitemplate.io/v1/create-image \
      -H "X-API-KEY: YOUR_API_KEY" \
      -F "template_id=your-template-id" \
      -F "modifications={\"headline\":\"50% off this week\",\"price\":\"$19.99\"}" \
      -F "output_format=PNG"
    

    The response returns a download_url you fetch after the render completes. The same account model also exposes a PDF API (/v1/create-pdf), an HTML API, and a query-string URL mode for quick integrations (APITemplate.io docs). Images, PDFs, and HTML all draw from the same render pool on Image + PDF plans — one invoice, one credit meter.

    APITemplate.io’s real strengths live outside the image API: native QR code and barcode generation, regional endpoints (US, EU, SG, AU) for data residency, and SOC 2 Type II certification for enterprise procurement. It has processed 30M+ documents since 2020 with a 99.99% uptime target (APITemplate.io).

    jsontoimg: JSON in, image out

    jsontoimg collapses the job to a single render endpoint. Send the template reference and the data to fill it:

    curl -X POST https://app.jsontoimg.com/api/v1/render?wait=60 \
      -H "Authorization: Bearer $JSONTOIMG_API_KEY" \
      -H "Content-Type: application/json" \
      -d '{
        "template": "share-card",
        "layers": {
          "headline": { "text": "50% off this week" },
          "price": { "text": "$19.99" }
        }
      }'
    

    One endpoint, one JSON body, one image back — PNG or JPG at up to 3× scale, with transparent PNGs supported. No separate PDF/HTML APIs to learn, no multipart forms, no shared credit pool to reason about. If you’ve used Placid’s layers object or Bannerbear’s modifications array, the pattern transfers in minutes — that’s the point of the JSON-to-image convention.

    Cost Per Image: Where the Math Bites

    APITemplate.io offers a genuinely generous free tier — 50 renders/month with no credit card — and PDF-only plans from $29/month. But the moment you need images at volume, the Image + PDF pricing changes the math:

    Volume / month jsontoimg APITemplate.io (Image + PDF) Savings
    1,000 renders $29 Starter $35 Starter 46%
    5,000 renders $49 Pro $99 Pro 51%
    10,000 renders $99 Scale $99 Pro (10K pool) Same price, more images
    15,000 renders $99 Scale Enterprise (custom) Better value

    The key detail: on APITemplate.io’s Image + PDF plans, every PDF and HTML render counts against the same pool. If your “1,000 renders” are 700 images and 300 PDFs, you still paid for 1,000. jsontoimg charges strictly for images — a PNG is a PNG, a JPG is a JPG, and nothing else can silently consume your quota.

    At entry tier that works out to $0.019 per image on jsontoimg vs $0.035 per render on APITemplate.io — roughly 1.8× more expensive for the same image volume, before you count the pages where the shared pool gets eaten by non-image output.

    Template Versioning vs Mutable Templates

    This is the difference that shows up in production, not in the marketing docs.

    APITemplate.io templates are mutable — edit a template and in-flight and future renders use the new version. That’s fine for prototyping; it’s dangerous when a designer tweaks the “wrong” template and your live banner pipeline suddenly renders with a new font, a moved logo, or a broken field mapping. Their own comparison content acknowledges troubleshooting complex templates can be a steep learning curve (Templated’s take on APITemplate.io).

    jsontoimg uses versioned templates: production renders pin to the template version active when the render was enqueued. Editing the live template never breaks in-flight renders, and rollbacks are a version pointer away. If you’ve ever been woken up by an image pipeline that changed overnight, you know why this matters.

    Delivery Model: Synchronous Wait vs Webhooks

    APITemplate.io delivers async renders via webhooks — solid, but you own the webhook receiver, retries, and timeouts.

    jsontoimg offers both paths:

    • Long-poll — GET /renders/{id}/wait blocks until the render is ready, so a simple script stays synchronous
    • SSE — GET /renders/{id}/events streams completion for batch jobs
    • Webhooks — with signature verification for fire-and-forget pipelines

    For a first integration, long-poll means you don’t need to stand up a webhook endpoint just to test. For batch work, SSE and webhooks cover the rest. APITemplate.io has no long-poll or SSE equivalent — webhooks are the only async option (APITemplate.io API docs).

    When the Mixed Pipeline Actually Wins

    Be honest about your pipeline before picking sides:

    Choose APITemplate.io when:

    • You need PDFs — invoices, reports, certificates as documents — from the same template account
    • You want HTML/CSS/Jinja2 template authoring instead of a visual editor
    • You need native QR codes or barcodes inside renders
    • You need regional endpoints for data residency, or SOC 2 Type II for enterprise deals
    • You want official SDKs in JS, Python, PHP, Java, C#, or Ruby

    Choose jsontoimg when:

    • Your output is stills and simple PDFs — OG cards, social posts, product banners, certificates as images, ad variants
    • You want the lowest cost per image and a predictable quota (no video credits eating your pool; PDF is one credit per page)
    • You want one render endpoint and a synchronous wait option for simple integrations
    • You value template versioning so production renders can’t be broken by edits
    • You want a Canva-style visual editor your designers will actually enjoy

    If you need both formats at real scale, the honest answer is often two focused tools — jsontoimg for images, a PDF service for documents — rather than one mixed pool where both compete for the same credits. That’s the tradeoff the APITemplate.io alternative page explores in more depth.

    Key Takeaways

    • APITemplate.io is a strong multi-format platform — but images and PDFs share one credit pool, and image-only users pay ~1.8× more per render at entry
    • jsontoimg charges strictly for images: $0.019/image at entry vs $0.035/render, with better volume pricing at 10K+
    • Template versioning on jsontoimg means production renders are never at risk from template edits; APITemplate.io templates are mutable
    • jsontoimg offers long-poll and SSE for simple sync integrations; APITemplate.io is webhooks-only
    • Pick APITemplate.io for genuine PDF needs (invoices, reports, QR codes); pick jsontoimg for stills and PDF (not HTML invoices)

    FAQ

    Is APITemplate.io or jsontoimg cheaper per image?

    It depends on what you render. APITemplate's Starter pool is larger but shared across images and PDFs and capped at 15 templates on that tier. jsontoimg Starter is $29/mo for 1,000 stills or PDF pages with unlimited templates in the editor, so the per-image cost is predictable when stills are all you send.

    Should I stay on APITemplate.io for PDFs?

    Yes, if HTML and CSS documents are the product. APITemplate is a document engine and handles invoices and contracts properly. jsontoimg PDF is a multi-page template billed one credit per page — right for certificates and tickets, not a replacement for an HTML invoice pipeline.

    Can I pin a template so a redesign does not break live renders?

    Yes. jsontoimg templates are versioned, and a request can pin design_version. Mutable templates change under your running integration the moment someone edits them in the UI.

    Does jsontoimg deliver results synchronously or by webhook?

    Both. A single POST /api/v1/render returns the image on the sync path, and batch jobs can POST to a webhook instead so long runs do not hold a connection open.

    Related Resources

  • Batch Image Generation API: 50 Jobs per Request

    With a batch image generation API, thousands of images means loops of 50. POST /api/v1/renders/batch accepts at most 50 jobs. This tutorial covers pacing, webhooks, retries, and why a naive 5,000-long HTTP array will 400.

    Overview

    Generating one image with an API is easy. Generating ten thousand is a different problem entirely — and it’s the problem every growing product eventually hits: a catalog with thousands of SKUs that each need a banner, a blog with hundreds of posts that each need an Open Graph card, an event platform that issues a unique ticket per registration, a course platform that mints a certificate per completion.

    Doing that with a design tool is impossible. Doing it with a headless browser is a maintenance sink. Doing it with an image generation API means learning how to batch — how to design one template, feed it thousands of data rows, and get thousands of images back without babysitting the process.

    This tutorial covers exactly that: the mechanics of batch generation with jsontoimg, when to use synchronous vs webhook delivery, how to structure your data for a clean batch, the cost math that makes batches worth it, and the failure modes that will bite you at volume. You’ll finish with a working Node.js script that turns a spreadsheet of rows into a folder of finished images.

    Why Batch Generation Is a Different Problem

    The naive approach is a loop: for each row of data, call the API, wait, save the image. It works — up to a point. At 100 images it’s tolerable. At 5,000 images, three things break:

    1. Latency compounds. If one render takes 1–2 seconds, 5,000 sequential requests is 1.5–3 hours of waiting, most of it idle time on your side.
    2. Rate limits. Every API has throughput limits. A naive loop slams the endpoint with no pacing and trips 429s in the first few minutes.
    3. Failures pile up. At volume, individual requests fail. Without retry logic, error tracking, and idempotency, you end up with 4,783 images and no idea which 217 are missing.

    Batch generation solves all three at once. Instead of N requests, you send one request containing N data objects, the API handles the parallelism and pacing internally, and you get an array of results back — or a webhook when they’re done.

    This is the same pattern the whole category settled on: Bannerbear’s Multi Image API renders several images per request and delivers results via webhook (Bannerbear API docs), Placid offers both synchronous and webhook delivery (Placid REST API docs), and RenderForm describes bulk generation as “a single template, data for the images, and multiple images generated at once” (RenderForm bulk image generation). jsontoimg follows the same conventions, so the mental model transfers.

    Step 1: Understand the Batch Model

    With jsontoimg, a batch is simple: you send an array of data objects against a template, and you get an array of images back.

    POST /api/v1/renders/batch
    
    {
      "jobs": [
        {
          "template": "product-banner-v1",
          "format": "png",
          "layers": {
            "product_name": { "text": "Wireless Mouse" },
            "price": { "text": "$29" }
          }
        },
        {
          "template": "product-banner-v1",
          "format": "png",
          "layers": {
            "product_name": { "text": "Mechanical Keyboard" },
            "price": { "text": "$89" }
          }
        }
      ]
    }
    

    Each object fills the placeholders in the template — same design, different data, thousands of times. The key insight: your data IS the design. Every variable — text, image URL, color, badge, QR code — is a field in JSON. Nothing is hardcoded, so nothing needs a human.

    A minimal template for the example above looks like this:

    {
      "width": 1200,
      "height": 630,
      "background": { "type": "solid", "color": "#0f172a" },
      "layers": [
        {
          "type": "text",
          "name": "product_name",
          "text": "named layer name",
          "font": { "size": 64, "weight": "bold", "color": "#ffffff" },
          "position": { "x": 80, "y": 200 }
        },
        {
          "type": "text",
          "name": "price",
          "text": "named layer price",
          "font": { "size": 40, "color": "#38bdf8" },
          "position": { "x": 80, "y": 320 }
        }
      ]
    }
    

    Placeholders like named layer name are replaced with values from each data object. If you need to design templates from scratch, the Designing Image Templates with JSON guide covers the full layer system.

    Step 2: Choose Your Delivery Mode

    Batch endpoints generally offer two delivery modes, and choosing correctly matters more than any other decision in this tutorial.

    Synchronous (small batches, interactive flows)

    You send the batch, the API renders everything, and the response contains all images. Use this when:

    • Batch size is small (tens of images, not thousands)
    • The caller is waiting on the result (e.g., a user uploading a CSV in your dashboard)
    • You want the simplest possible integration

    The tradeoff is the request can take a while, and your HTTP client needs a generous timeout. For a 50-image batch at ~1s per render, expect 30–60 seconds.

    Webhooks (large batches, background pipelines)

    You send the batch with a webhook_url, the API responds immediately with a batch ID, and each completed image — or the whole batch — is POSTed to your URL. Use this when:

    • Batch size is large (hundreds to thousands)
    • Generation happens in the background (nightly catalog refresh, event-triggered jobs)
    • You want automatic retries and a durable audit trail

    The pattern is identical to what Bannerbear describes as its primary flow: “POST a request, the API responds immediately with 202 Accepted and you either receive the generated result via webhook or via polling” (Bannerbear async docs). It keeps the request/response cycle predictable no matter how big the job is.

    This is the mode the rest of this tutorial uses, because it’s the one that scales.

    Step 3: Structure Your Data Like a Pro

    Garbage data produces garbage images — and with thousands of images, garbage is expensive to catch. Structure your batch data with these rules:

    1. Every row gets a stable ID. Include a name or id field per item. It becomes the output filename and your source of truth for tracking.

    { "id": "A-001", "name": "Wireless Mouse", "price": "$29" }
    

    2. Normalize before you send. Trim whitespace, validate that image URLs resolve, and pre-format currency and dates. An API renders what you give it — it won’t fix “usd 29.0” or a broken image URL.

    3. Escape and encode text. JSON handles escaping automatically, but be careful with user-generated content: long strings overflow text layers, newlines break single-line layouts, and emoji can fall back to ugly system fonts. Add a max_chars check per field before sending.

    4. Test on a sample batch first. Never run your first batch at full scale (max 50 jobs per request). Generate 10–20 test images, check the output, then scale. The MindStudio guide on batch generation makes exactly this point: “Never run your first batch at full scale (max 50 jobs per request). Generate 10-20 test images to validate your workflow” (MindStudio: Batch AI Image Generation).

    Step 4: Build the Batch Script

    Here’s a complete Node.js script that reads a CSV of product data and fires a webhook-delivered batch. Install dependencies with npm install csv-parse:

    import { parse } from "csv-parse/sync";
    import { readFileSync } from "node:fs";
    
    const API_KEY = process.env.JSONTOIMG_API_KEY;
    const BATCH_URL = "https://app.jsontoimg.com/api/v1/renders/batch";
    
    // 1. Read and parse your data source (CSV, DB rows, spreadsheet export — anything)
    const csv = readFileSync("./products.csv", "utf8");
    const rows = parse(csv, { columns: true, skip_empty_lines: true });
    
    // 2. Map rows to template data objects
    const data = rows.map((row) => ({
      id: row.sku,
      name: row.product_name.trim(),
      price: `$${Number(row.price).toFixed(0)}`,
      badge: row.badge || "",
    }));
    
    // 3. Fire the batch with webhook delivery
    const response = await fetch(BATCH_URL, {
      method: "POST",
      headers: {
        Authorization: `Bearer ${API_KEY}`,
        "Content-Type": "application/json",
      },
      body: JSON.stringify({
        jobs: data.slice(0, 50).map((row) => ({
          template: "product-banner-v1",
          format: "png",
          webhookUrl: "https://your-app.com/webhooks/jsontoimg",
          layers: {
            product_name: { text: row.name },
            price: { text: row.price },
            badge: { text: row.badge },
          },
        })),
      }),
    });
    
    const batch = await response.json();
    console.log(`Batch ${batch.id} accepted ${batch.acceptedCount} jobs`);
    console.log(`Poll GET /api/v1/renders/batches/${batch.id}`);
    

    Step 5: Handle the Webhook Results

    Your webhook endpoint receives a POST per completed image (or per batch, depending on your setting). The payload should look like:

    {
      "id": "batch_8f3k2",
      "status": "processing",
      "acceptedCount": 2,
      "rejectedCount": 0
    }
    

    Track results in a database keyed by item_id. This gives you three superpowers:

    • Idempotency — if a webhook is delivered twice, updating the same row is harmless.
    • Retry targeting — after the batch finishes, query for rows where status != "completed" and re-send only those.
    • Auditability — you always know exactly which images exist and which don’t.

    Here’s a minimal retry loop that runs after a batch completes:

    async function retryFailed(batchId) {
      const failed = await db.query(
        `SELECT item_id FROM batches WHERE batch_id = $1 AND status != 'completed'`,
        [batchId]
      );
    
      if (failed.length === 0) return console.log("All images generated ✓");
    
      const rows = failed.map((f) => dataById[f.item_id]);
      await fetch(BATCH_URL, {
        method: "POST",
        headers: { Authorization: `Bearer ${API_KEY}`, "Content-Type": "application/json" },
        body: JSON.stringify({
          jobs: rows.slice(0, 50).map((row) => ({
            template: "product-banner-v1",
            format: "png",
            layers: {
              product_name: { text: row.name },
              price: { text: row.price },
            },
          })),
        }),
      });
      console.log(`Retrying ${rows.length} failed items...`);
    }
    

    Step 6: The Cost Math That Justifies the Batch

    Batch generation isn’t just convenient — it’s the difference between an automation that makes sense and one that doesn’t. Consider the numbers:

    Approach Cost per image Time for 1,000 images Maintenance
    Designer in Figma/Canva $5–$50+ (hourly labor) Weeks High (human in loop)
    Headless browser (Puppeteer) $0.50–$2.00 (compute + infra) Hours, but you run the infra High (servers, deps, memory leaks)
    Template-based API batch Pay-per-render, volume pricing Minutes, fully managed Near zero

    The e-commerce comparison is starker. Traditional product photography runs $200–$5,000 per session; AI/template-generated product visuals come in around $0.10–$2.00 per image — for a 500-SKU catalog, that’s a drop from $12,500+ to under $1,000 (Digital Applied: AI product photography costs).

    The compounding effect matters too: at 10,000 images, even a $0.01-per-image price difference is $100. That’s why volume pricing and batch-friendly plans exist — and why you should always run a small test batch before committing to a full production run.

    One detail worth internalising before the failure list: a 429 is not an error in the sense a 500 is. Per MDN's reference on 429 Too Many Requests, it is the server telling you the request was well-formed but arrived too soon, and it may carry a Retry-After header saying how long to wait. Treat it as flow control and back off; treat it as a failure and you will drop images that would have rendered fine.

    Common Failure Modes at Scale (and How to Avoid Them)

    After generating tens of thousands of images, these are the failures that actually happen:

    1. Text overflow. A 200-character product name in a 40-char text layer. Fix: enforce max_chars in your data mapping, and design templates with auto_fit or truncation enabled for untrusted fields.

    2. Broken image URLs. A logo or product photo that 404s renders as a broken placeholder across thousands of images. Fix: pre-validate all URLs in your batch script with a HEAD request, and fail the batch early if more than X% are broken.

    3. Missing retries. A transient network error drops 3% of a 10,000-image batch, and nobody notices for a week. Fix: always track status per item and run the retry loop (Step 5) automatically after every batch.

    4. Wrong dimensions for the destination. A 1080×1080 square image uploaded to a 1200×630 OG slot gets cropped or squashed. Fix: define one template per destination format, and name templates by format (og-v1, feed-v1, banner-v1).

    5. Cost surprises. A forgotten loop regenerating the same batch nightly burns credits silently. Fix: log batch sizes, set per-batch limits, and alert on abnormal volume.

    Beyond Products: The Same Batch Powers Everything

    The batch pattern isn’t specific to product banners. The identical flow — template + array of data + webhook — powers every high-volume use case on the site:

    • Open Graph images for every blog post and page (use case)
    • Social media posts scheduled from a spreadsheet (use case)
    • Certificates minted per course completion (use case)
    • Event tickets unique per registration
    • Email hero images personalized per subscriber

    Each one is a template, a data source, and a webhook endpoint. If you’ve built the product banner pipeline, you’ve built them all.

    Key Takeaways

    • Batch generation is one request with an array of data — the API handles parallelism and pacing, so 5,000 images don’t mean 5,000 requests from your side.
    • Choose delivery mode by size: synchronous for interactive small batches, webhooks for background large batches.
    • Data hygiene is everything — stable IDs, normalized fields, and validated URLs separate a clean 10,000-image run from a disaster.
    • Track per-item status and retry only the failures; idempotent webhook handling makes this trivial.
    • Test at 10–20 images before full scale — the cheapest bug is the one you catch before generating thousands.
    • Template-based API batches cost $0.10–$2.00 per image versus $200+ per traditional shoot session — the cost math is why this category exists.

    FAQ

    How many jobs can one batch image generation request hold?

    Fifty. POST /api/v1/renders/batch accepts at most 50 jobs per request and returns 400 if you send more, so a 5,000-image run is 100 sequential requests of 50 rather than one giant array.

    Should I wait for the batch response or use a webhook?

    Wait synchronously only for small, interactive batches where a user is watching. For anything large or background, pass a webhook URL and let jsontoimg POST each result as it finishes — that keeps your request from timing out on a long queue.

    Do failed jobs in a batch cost credits?

    No. One credit is one successful PNG, JPG, WebP, AVIF, or PDF page. A job that errors is not billed, so a partially failed batch only charges for the images you actually received.

    How do I avoid rate limits when generating thousands of images?

    Send the 50-job batches sequentially rather than firing all of them at once, and retry a 429 with backoff before moving to the next chunk. Pacing the loop is what keeps a bulk run stable.

    Is a PDF page billed differently from a PNG?

    No. A PDF page costs the same single credit as a still, so a 3-page PDF is 3 credits.

    Related Resources

    See also batch docs (max 50) and product banners.

    Zoom out: How JSON-to-Image Conversion Works maps the whole template, named-layer, and render-job architecture.

  • Certificate Generator with QR Code Verification: How to Build It

    How to Build a Certificate Generator with Verification QR Codes

    Looking for the commercial API overview and pricing? Check out the primary Certificate Generator API hub.

    Certificates are essential milestones for modern SaaS platforms, online courses, bootcamps, and professional accreditations. When a student completes a course, they expect an immediate, high-resolution certificate with a verifiable credential ID and a scannable QR code.

    This tutorial walks through building a programmatic certificate generator with jsontoimg using Python or Node.js. By the end, you will have a pipeline that reads completion records from your database and renders print-ready vector PDFs and web-ready PNGs automatically.

    Why Manual Certificate Workflows Fail

    Most teams start with a graphic designer, a Figma or Canva template, and a spreadsheet. While manageable for 15 students, this approach breaks down at scale:

    • Time Drain: Exporting, naming, and emailing 500 certificates consumes 80–120 hours of manual labor per cohort.
    • Typo Exposure: Human copy-paste errors on recipient names or dates undermine institutional credibility.
    • No Instant Verification: Manual exports lack verifiable cryptographic UUIDs and tamper-evident QR lookups.

    By treating certificates as a template driven by structured JSON, you turn graduation day into an automated 2-minute API background job.

    Step 1: The Certificate Data Model

    Every certificate requires a consistent JSON schema: recipient name, course title, completion date, credential UUID, and a verification URL:

    {
      "certificate_id": "0190a7e2-5b1c-7c3e-9f00-2a6d1e4b8c11",
      "recipient_name": "Priya Sharma",
      "course_title": "Advanced Distributed Systems",
      "instructor": "Balaji R",
      "completion_date": "2026-11-17",
      "verification_url": "https://verify.example.com/c/0190a7e2-5b1c-7c3e-9f00-2a6d1e4b8c11"
    }
    

    In J2I Studio, design your certificate with dynamic text layers for recipient_name, course_title, completion_date, and certificate_id. Add a native Code layer named qr with format qrcode. Static elements (borders, emblems, background graphics, signatures) stay on fixed layers.

    Step 2: Rendering a Single Certificate via REST

    To issue a single certificate upon course completion, send a POST request to /api/v1/render:

    curl -X POST "https://app.jsontoimg.com/api/v1/render?wait=60" \
      -H "Authorization: Bearer $JSONTOIMG_API_KEY" \
      -H "Content-Type: application/json" \
      -d '{
        "template": "tpl_graduation_award",
        "version": 1,
        "format": "pdf",
        "layers": {
          "recipient_name": { "text": "Priya Sharma" },
          "course_title": { "text": "Advanced Distributed Systems" },
          "completion_date": { "text": "November 17, 2026" },
          "certificate_id": { "text": "0190a7e2-5b1c-7c3e" },
          "qr": { "text": "https://verify.example.com/c/0190a7e2-5b1c-7c3e" }
        }
      }'
    

    The response returns a permanent asset URL for the rendered vector PDF. Each PDF page costs exactly 1 credit.

    Step 3: Batch Rendering for Graduating Cohorts

    For graduating cohorts of 100 to 1,000 students, use POST /api/v1/renders/batch to process jobs in batches of up to 50 certificates per request.

    Here is the complete production batch script in Python:

    import os
    import sqlite3
    import requests
    
    API_KEY = os.environ.get("JSONTOIMG_API_KEY")
    TEMPLATE_ID = "tpl_graduation_award"
    
    conn = sqlite3.connect("lms.db")
    cursor = conn.cursor()
    
    # Query pending certificate awards
    rows = cursor.execute("""
        SELECT certificate_id, recipient_name, course_title, completion_date
        FROM completions
        WHERE certificate_generated = 0
        LIMIT 50
    """).fetchall()
    
    jobs = [
        {
            "id": f"cert_{r[0]}",
            "template": TEMPLATE_ID,
            "version": 1,
            "format": "pdf",
            "layers": {
                "certificate_id": {"text": r[0]},
                "recipient_name": {"text": r[1]},
                "course_title": {"text": r[2]},
                "completion_date": {"text": r[3]},
                "qr": {"text": f"https://verify.example.com/c/{r[0]}"}
            }
        }
        for r in rows
    ]
    
    response = requests.post(
        "https://app.jsontoimg.com/api/v1/renders/batch",
        json={"jobs": jobs},
        headers={"Authorization": f"Bearer {API_KEY}"}
    )
    
    batch = response.json()
    print(f"Batch {batch.get('id')} accepted with {batch.get('acceptedCount')} certificates queued.")
    

    Step 4: Making Certificates Verifiable

    A certificate without verification is vulnerable to screenshot forgery. To ensure credibility:

    1. Mint RFC 9562 UUIDs: Use UUID v4 or v7 rather than sequential IDs (#41, #42), which leak cohort volume and allow guessing adjacent URLs.
    2. Vector QR Code Layer: jsontoimg generates native vector QR codes on the canvas, ensuring maximum scannability on both phone screens and printed paper.
    3. Public Verification Page: Host a fast public route (e.g., https://verify.example.com/c/<uuid>) that looks up the UUID in your database and validates the recipient's name, issue date, and credential status.

    Contrast & Print Accessibility

    Certificates are frequently printed and framed:

    • Follow WCAG 2.1 contrast minimums (4.5:1 for body copy). Avoid light grey or subtle gold text against cream backgrounds.
    • Enable auto-fitting on the recipient_name layer in J2I Studio so unusually long names automatically scale down rather than overflowing the certificate border.

    Related Resources

    Frequently Asked Questions

    Can I generate certificates as both PNG and PDF?

    Yes. Requesting "format": "pdf" outputs a vector-sharp printable document. Requesting "format": "png" or "webp" outputs an image ideal for email attachments and LinkedIn sharing.

    How does jsontoimg bill batch certificates?

    Each rendered certificate or PDF page costs 1 credit. Failed renders never deduct credits. Prepaid credit packs ($5 for 250 certificates, $10 for 500) never expire.

    Can I use n8n or Zapier to trigger certificates?

    Yes. jsontoimg provides a native n8n community node (@j2i/n8n-nodes-j2i) and standard REST endpoints that connect to Zapier, Make, and Airtable via HTTP.

    Get 25 free images →
    "template": "certificate-award-v2",
    "format": "png",
    "layers": {
    "certificate_id": { "text": "CERT-2026-004218" },
    "recipient_name": { "text": "Arjun Mehta" },
    "course_title": { "text": "Advanced SQL for Data Analysts" },
    "completion_date": { "text": "2026-08-01" }
    }
    }
    ]
    }'

    
    Your LMS or course platform already has this data — you’re just exporting a few columns. Here’s the whole pipeline in Python against a typical database:
    

    import requests
    import sqlite3

    API_KEY = "YOUR_API_KEY"
    TEMPLATE_ID = "certificate-award-v2"

    conn = sqlite3.connect("lms.db")
    rows = conn.execute("""
    SELECT certificate_id, recipient_name, course_title, completion_date
    FROM completions
    WHERE certificate_generated = 0
    """).fetchall()

    jobs = [{
    "template": TEMPLATE_ID,
    "format": "png",
    "layers": {
    "certificate_id": { "text": r[0] },
    "recipient_name": { "text": r[1] },
    "course_title": { "text": r[2] },
    "completion_date": { "text": r[3] },
    },
    } for r in rows[:50]]

    resp = requests.post(
    "https://app.jsontoimg.com/api/v1/renders/batch",
    json={"jobs": jobs},
    headers={"Authorization": f"Bearer {API_KEY}"},
    )
    batch = resp.json()
    print(batch["id"], batch.get("acceptedCount"))

    
    That’s the whole generator: select ungenerated completions → render → save. Run it after every cohort closes, or on a schedule.
    
    ## Async Delivery with Webhooks
    
    For very large batches — an event with 10,000 attendees, a certification body with quarterly exam cycles — synchronous rendering ties up your request for too long. Use async mode with a webhook instead:
    

    curl -X POST https://app.jsontoimg.com/api/v1/renders/batch
    -H "Authorization: Bearer $JSONTOIMG_API_KEY"
    -H "Content-Type: application/json"
    -d '{
    "jobs": [ /* max 50; each job has template + layers; optional webhookUrl per job */ ]
    }'

    Then GET /api/v1/renders/batches/{id}

    
    jsontoimg calls your webhook when each batch finishes, and your app emails the certificate or updates the participant record. The typical flow:
    

    Webhook trigger (course completion)
    → Look up participant row
    → Render certificate (sync for singles, batch for cohorts)
    → Upload to storage / attach to email
    → Mark certificate_generated = 1

    
    ## Verification: Unique IDs and QR Codes
    
    A certificate without verification is just a nice picture. Put the `certificate_id` on the certificate itself, and optionally a QR code that resolves to a public verification page:
    
    1.  Generate a unique ID per recipient in your database (`CERT-2026-004217`).
    2.  Pass it into the render as a dynamic layer — it appears on the certificate.
    3.  Publish a public endpoint: `https://verify.yoursite.com/CERT-2026-004217` shows “Valid — issued to Priya Sharma for Advanced SQL for Data Analysts.”
    4.  Render the same ID as a QR code layer so employers can scan and verify instantly.
    
    This is the same pattern event platforms use for attendee badges and [event tickets](https://jsontoimg.com/use-cases/event-tickets/): unique identifier in, tamper-evident image out.
    
    Two of the choices above have published guidance behind them. For the identifier, [RFC 9562](https://datatracker.ietf.org/doc/html/rfc9562) is the current UUID specification and the reason to mint a v4 or v7 UUID rather than an incrementing integer: a sequential certificate number tells a holder how many you have issued and lets anyone guess a neighbour's URL. For legibility, [WCAG 2.1's contrast minimum](https://www.w3.org/WAI/WCAG21/Understanding/contrast-minimum.html) applies to a certificate as much as to a web page, and a recipient name set in light grey on a cream background fails it on every copy. The format call is the last one — [MDN's image file type guide](https://developer.mozilla.org/en-US/docs/Web/Media/Guides/Formats/Image_types) covers PNG for the screen-shared version, while PDF is what survives being printed.
    
    ## Real-World Numbers
    
    An online learning platform with 5 concurrent courses, 100 graduates each per month:
    
    | Step | Manual | jsontoimg pipeline |
    | --- | --- | --- |
    | Design template | 1 designer, ~4 hours | 1 designer, ~4 hours (once) |
    | Generate 500 certificates | 80–125 hours | ~2 minutes of API time |
    | Error rate | Typos happen per-certificate | Zero — data in, image out |
    | Delivery time | 3 days processing | Minutes after completion |
    | Verification | None or manual lookup | Built-in IDs + QR |
    
    The template cost is paid once; the marginal cost of the 501st certificate is a single API call.
    
    ## Key Takeaways
    
    -   Certificates are a data problem, not a design problem — one template plus JSON per recipient is the whole system.
    -   Batch rendering handles entire cohorts in one request; webhooks make it async for events at any scale.
    -   Unique IDs and QR codes turn generated certificates into verifiable credentials.
    -   The same pipeline pattern applies across use cases: product banners, OG images, tickets, welcome graphics.
    
    ## FAQ
    
    ### How do I generate hundreds of certificates at once?
    
    One row per recipient, then `POST /api/v1/renders/batch` in chunks of 50. Five hundred certificates is ten sequential batch requests.
    
    ### Can the certificates come out as PDF instead of PNG?
    
    Yes. Send `format: "pdf"` and a multi-page template becomes a multi-page PDF, billed one credit per page — the same as a still.
    
    ### How do I make a generated certificate verifiable?
    
    Mint a unique ID per recipient, render it into the certificate as text, and point a QR image layer at a verification URL containing that ID. The image becomes a lookup key rather than a claim.
    
    ### Do I need a webhook for a certificate run?
    
    For a cohort of a few dozen, waiting on the batch response is fine. Past a few hundred, pass a webhook so the run does not hold a connection open while the queue drains.
    
    ## Related Resources
    
    -   [Building a Certificate Generator with a Template-to-Image API](https://jsontoimg.com/use-cases/certificates/) — the use case overview
    -   [Getting Started with jsontoimg: Your First API Call](https://jsontoimg.com/blog/getting-started-with-jsontoimg-first-api-call/) — template basics before you build
    -   [Auto-Generate Open Graph Images for Your Blog](https://jsontoimg.com/blog/auto-generate-og-images-with-jsontoimg) — another data-to-image pipeline
    -   [Event Ticket Generation with jsontoimg](https://jsontoimg.com/use-cases/event-tickets/) — unique-ID patterns for per-person assets
    -   [bulk certificate generation from a CSV](https://jsontoimg.com/blog/certificate-generator-api-guide)
    
    Zoom out: [How JSON-to-Image Conversion Works](https://jsontoimg.com/blog/json-to-image-converter) maps the whole template, named-layer, and render-job architecture.
    
  • A/B Test Ad Creatives: Enumerate Variants, Then Batch-Render

    Build the headline × image matrix in code, then batch-render. jsontoimg does not score CTR. Parent: /use-cases/ad-creatives.

    Overview

    Ad creative fatigue is the silent budget killer of modern paid media. A single creative that converts well will, within weeks, start costing you more while converting less — and the fix isn’t a better designer, it’s a faster creative pipeline. The teams winning on Meta, Google, and TikTok in 2026 don’t rely on a handful of hand-made ads; they generate dozens of variations, test them in structured batches, and let performance data pick the winners.

    This post walks through building an automated A/B testing workflow for ad creatives using jsontoimg: a JSON-in, image-out API. You’ll design one modular template, generate every variation you want to test from a simple config file, and ship them to your ad platform with a naming convention that makes results analysis trivial. By the end, you’ll have a repeatable pipeline that turns a creative hypothesis into a tested, measured ad — in minutes instead of days.

    Why Manual Creative Testing Is Failing You

    The data on creative fatigue is stark. Cross-source frequency research in 2026 found that conversion rates drop ~45% after just four exposures to the same creative, and CTR drops ~50% after 5–8 views. Costs climb 50–80% at five or more exposures — meaning your best-performing ad from last month is quietly becoming your most expensive one today.

    At the same time, ad fatigue windows have compressed dramatically. A 2025 study of 3,014 advertisers across 115.7 billion impressions found fatigue windows shrank from 6–8 weeks to just 2–4 weeks — and advertisers who relied on a few strong creatives saw the sharpest performance drops. Meta’s Andromeda system (fully rolled out in October 2025) surfaces ads more aggressively, which burns through audiences faster.

    The practical implication: you need more creative variations, produced faster, and tested systematically. Manual design simply can’t keep up. A designer might produce 5–10 ad variations per week; a template-based API can produce hundreds in the same window.

    The Old Way: Design, Export, Repeat

    Here’s the manual A/B testing workflow that most small teams still run:

    1. Designer creates 4–6 ad concepts in Figma or Canva
    2. Marketer requests size variants (1080×1080, 1200×628, 1080×1350)
    3. Someone exports, renames, and uploads each file to the ad platform
    4. Two weeks later, the winner is declared — and the process starts over

    At 6 concepts × 3 sizes, that’s 18 assets per test round. Each round takes days. And because the bottleneck is human design time, teams test far fewer hypotheses than they should — which means they’re not really A/B testing, they’re guessing with extra steps.

    The jsontoimg Way: One Template, Every Variation

    The core insight is that an ad variation is just data applied to a design. The background, headline, offer, CTA color, and image are all variables. If you define the design once as a template, then every variation is just a different JSON payload — and generating 50 variations is as easy as generating 1.

    Here’s the architecture:

    Variation config (JSON: headlines, colors, offers, images)
            │
            ▼
    jsontoimg API → renders template × every data combination
            │
            ▼
    Named output files (headline-a_bg-blue_cta-red.png)
            │
            ▼
    Upload to Meta / Google / TikTok via API or bulk import
            │
            ▼
    Performance data → winners feed the next variation round
    

    The loop is the important part: your A/B test results don’t just declare a winner — they become the input for the next generation of variations.

    Step 1: Define Your Test Matrix

    Before generating anything, decide what you’re testing. The most common variables for static ad creatives:

    • Headline — 3–5 copy angles (benefit-led, problem-led, social-proof, urgency)
    • Background — brand color, gradient, photo, or pattern
    • CTA color — contrast variations (red vs. green vs. brand blue)
    • Offer framing — price anchor, discount percentage, “free shipping”
    • Product image — hero shot, lifestyle shot, or graphic illustration
    • Badge — “NEW”, “BESTSELLER”, “LIMITED” placements

    A good test matrix looks like this:

    Variable Values
    Headline 4 (benefit, problem, social proof, urgency)
    Background 2 (brand gradient, photo)
    CTA color 2 (brand blue, high-contrast red)
    Offer 2 (20% off, free shipping)

    That’s 4 × 2 × 2 × 2 = 32 variations — more than a designer could produce in a week, generated in a single API call. Keep the matrix structured: one variable family at a time for clean results (more on that below).

    Step 2: Design a Modular Template

    Design your ad template in jsontoimg with placeholders for every variable in the matrix. A standard feed ad is 1080×1080 (square) or 1200×628 (landscape). Conceptually, the template looks like this:

    {
      "width": 1080,
      "height": 1080,
      "background": { "type": "named layer background_type", "color": "named layer background_color" },
      "layers": [
        {
          "type": "image",
          "source": "named layer product_image",
          "x": 90, "y": 420, "width": 520, "height": 520
        },
        {
          "type": "text",
          "text": "named layer headline",
          "x": 80, "y": 120, "size": 56, "weight": "bold", "color": "#111827",
          "max_width": 920, "wrap": true
        },
        {
          "type": "text",
          "text": "named layer offer",
          "x": 80, "y": 300, "size": 34, "color": "#374151"
        },
        {
          "type": "badge",
          "text": "named layer badge",
          "visible": "named layer has_badge",
          "x": 80, "y": 80, "background": "#dc2626", "color": "#ffffff"
        },
        {
          "type": "button",
          "text": "Shop Now",
          "background": "named layer cta_color",
          "x": 80, "y": 900, "width": 400, "height": 90
        }
      ]
    }
    

    Every named layer placeholder maps to one variable in your test matrix. Design once, and the same template powers all 32 variations.

    Step 3: Generate All Variations from a Config File

    Now the magic: define your variations as data, and render them in one batch. A minimal config:

    {
      "jobs": [
        {
          "template": "ad-feed-v1",
          "format": "png",
          "layers": {
            "headline": { "text": "Save 20% on Your First Order" },
            "offer": { "text": "Limited time — 20% off everything" },
            "badge": { "text": "SALE" }
          }
        },
        {
          "template": "ad-feed-v1",
          "format": "png",
          "layers": {
            "headline": { "text": "Tired of Products That Fall Apart?" },
            "offer": { "text": "Free shipping on all orders" }
          }
        }
      ]
    }
    

    With jsontoimg’s batch generation, one request returns an array of images — 32 variations from 32 config entries. In Node.js:

    const variations = require("./variations.json"); // your test matrix
    
    const result = await fetch("https://app.jsontoimg.com/api/v1/renders/batch", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        "Authorization": "Bearer $JSONTOIMG_API_KEY",
      },
      body: JSON.stringify({
        jobs: variations.slice(0, 50).map((v) => ({
          template: "ad-feed-v1",
          format: "png",
          layers: {
            headline: { text: v.headline },
            offer: { text: v.offer },
          },
        })),
      }),
    });
    
    const batch = await result.json();
    // GET /api/v1/renders/batches/{id} — done jobs expose assetUrl
    

    Step 4: Name Files for Analysis (This Matters More Than You Think)

    The #1 reason A/B tests fail is sloppy naming. If you can’t tell which asset is which when the results come back, the test is worthless. Make the variation name encode every variable:

    {hypothesis}_{variable1}-{value1}_{variable2}-{value2}.png
    
    benefit_gradient_blue_20off.png
    problem_photo_red_freeship.png
    urgency_gradient_red_20off.png
    

    Each variation’s name field becomes the filename. When Meta or Google reports “benefit_gradient_blue_20off delivered 2.4% CTR,” you immediately know: benefit-led headline + gradient background + blue CTA + 20% off. No cross-referencing spreadsheets, no guessing.

    Step 5: Ship to Your Ad Platform and Measure

    Once images are rendered and stored on your CDN, upload them to your ad platform. You can do this via the platform’s bulk tools or API (Meta’s Graph API, Google Ads API), or simply use the bulk import CSV in Ads Manager — most platforms accept a list of image URLs, which jsontoimg returns.

    Then the testing rules that actually matter:

    • Test one variable family at a time — if you change headline, background, and CTA all at once, you can’t attribute the win. Run headline tests with everything else fixed, then iterate.
    • Give tests enough traffic — small budgets split 32 ways produce noise, not insight. For low-budget accounts, test 4–8 variations per round and use the winner to seed the next round.
    • Define your metric before launch — CTR for engagement, CPA/ROAS for conversions. A creative that wins CTR but loses ROAS isn’t a winner.
    • Rotate before fatigue sets in — with fatigue windows at 2–4 weeks, fresh variations need to be entering the pipeline continuously. Batch generation makes that possible.

    Two caveats keep a big matrix honest. The first is statistical: more variants means less traffic each, and Evan Miller's sample-size calculator will show you how much volume a detectable difference actually needs before you split a budget forty ways. The second is platform rules — Meta's ad creative reference documents the fields and image constraints a creative has to satisfy, and a template that violates them produces 240 rejected ads just as efficiently as it produces 240 good ones. On the output itself, web.dev's format guidance and MDN's image file type guide cover which format to ship where, and Google's image SEO documentation is worth a pass if the same creatives also land on a landing page.

    The Numbers That Make This Worth It

    The payoff is measurable. According to 2026 benchmarks, AI-generated creatives achieve ~12% higher CTR on Meta on average, driven by the ability to test far more visual hooks and copy combinations than human teams can produce. Brands running structured creative testing loops report 25–40% improvements in blended ROAS within 6 months — not from better media buying, but from better creative intelligence. Creative lifespan extends from 10–14 days to 21–30 days when format diversity keeps patterns from fatiguing, and testing velocity of 3–5 variations per week means fresh creative always enters the pipeline before the old stuff burns out.

    Beyond Static Ads: The Same Pipeline Powers Everything

    The template you build for feed ads is reusable across your whole visual content surface — email hero images, social posts, OG images, and display banners. Each is just a template with different dimensions and placeholders. For the full list of scenarios, see the Ad Creatives use case page — and if you’re already running product banners, the Product Banners guide covers the catalog-driven side of the same system.

    Key Takeaways

    • Creative fatigue is faster than ever — conversion drops ~45% after 4 exposures, CTR ~50% after 5–8 views; fatigue windows are now 2–4 weeks.
    • Manual design can’t keep pace — a designer produces 5–10 variations a week; a template-based API produces hundreds in minutes.
    • An ad variation is just data applied to a design — define the design once as a jsontoimg template, and every variable (headline, background, CTA, offer) becomes a JSON field.
    • Generate the whole test matrix in one batch request — 4×2×2×2 variables = 32 variations, rendered from a single config file.
    • Encoding variable names into filenames is the difference between a usable A/B test and an expensive guessing game.
    • Structured creative testing compounds — 25–40% blended ROAS improvements within 6 months, plus longer creative lifespan and lower costs.

    FAQ

    How many ad creative variations should I test at once?

    Enumerate the full matrix of the variables you care about — headline, offer, background, format — and render all of it. Once design is a template-to-image API call, the cost of the 48th variant is one credit, so the limit is what your ad platform can meaningfully measure, not design time.

    How should I name generated creative files?

    Encode every axis of the test in the filename, in a fixed order. When the ad platform hands back performance data keyed on filename, you can split results by variable without a manual lookup table.

    Can I generate every variation in one API request?

    Not in one, but in chunks of 50. POST /api/v1/renders/batch takes up to 50 jobs, so a 240-variant matrix is five sequential batch calls.

    What does a full creative matrix actually cost?

    One credit per rendered image. 240 variants is 240 credits — well inside a single $29 Starter month, and less than an hour of the designer time the same matrix used to take.

    Related Resources

    Zoom out: How JSON-to-Image Conversion Works maps the whole template, named-layer, and render-job architecture.

  • Email Hero Image Size and Specs: 600px, JPEG, Send-Time Renders

    Email-client constraints: design at 1200×630, display at 600px, JPEG under 150KB, alt text required. The use-case page is /use-cases/email-hero-images. Measure lift in your own ESP; do not copy someone else’s ROI number.

    Overview

    Your email hero image is the first pixel a subscriber sees — and for most campaigns, it’s also the most wasted one. It’s the same generic banner sent to 50,000 people, while every other part of the email (subject line, product recommendations, even the sender name) gets personalized.

    That’s backwards. Personalized heroes are worth it only if you can measure lift in your own ESP. Generating one unique image per subscriber is a batch of signed URLs or send-time JPEGs — not a Chromium farm.

    It doesn’t have to be. With a JSON-driven image API like jsontoimg, you can generate a fully personalized hero image for every subscriber in a batch — name, product, price, location, countdown timer, anything in your data — in a single API call. This guide walks through the whole pipeline: template design, batch generation, caching, and email-client-safe sizing.

    Why the Hero Image Is the Highest-Leverage Pixel in Email

    Before diving into code, it’s worth understanding why this matters. The data is unambiguous:

    • Emails with personalized content see 29% higher open rates and 41% higher click-through rates than static sends (The Loop Marketing, 2026)
    • Personalized emails deliver 6x higher transaction rates (Campaign Monitor)
    • Usage of AI for generating email imagery grew 340% from 2024 to 2025 (Leadoom)

    The hero image sits above the fold, occupies the largest visual area, and sets expectations for everything below it. If it’s generic, the reader’s brain classifies the email as bulk before reading a single word. If it’s clearly built for *them*, the opposite happens.

    The Old Ways of Doing This (and Why They Break)

    Manual design in Figma/Canva

    Fine for one campaign. Impossible at 10,000 subscribers. Nobody is hand-designing 10,000 unique heroes.

    Dynamic image platforms (NiftyImages, Liveclicker, etc.)

    These work, but they’re add-ons to your email platform, they cost per render, and you’re locked into their template engine. If you’re already running an API-driven stack, bolting on a separate visual platform is friction you don’t need.

    DIY rendering with Puppeteer

    Full control, but now you’re maintaining a headless browser fleet, font installation, scaling, and rendering infrastructure — all to generate one image per subscriber. That’s a lot of moving parts for a marketing email.

    The jsontoimg approach

    Design a template once, send JSON per subscriber, get images back. No browser infrastructure, no template lock-in, no manual design. One POST request per subscriber (or one batch request for thousands), and you’re done.

    Step 1: Design the Hero Template

    A hero template is a layout with placeholders. In jsontoimg you define:

    • Dimensions — 1200×630 (displayed at 600px, exported at 2x for retina)
    • Text layers — greeting, name, offer, product title, price
    • Image layers — product photo, logo, background
    • Styles — fonts, colors, alignment, text wrapping

    Think of it as a design file, but expressed as JSON:

    {
      "template": {
        "width": 1200,
        "height": 630,
        "background": {
          "type": "color",
          "value": "#0F172A"
        },
        "layers": [
          {
            "type": "image",
            "src": "named layer product_image",
            "x": 60,
            "y": 120,
            "width": 400,
            "height": 400,
            "fit": "cover"
          },
          {
            "type": "text",
            "value": "Hey named layer first_name,",
            "x": 520,
            "y": 140,
            "font_size": 56,
            "font_weight": 700,
            "color": "#FFFFFF",
            "align": "left"
          },
          {
            "type": "text",
            "value": "named layer product_name is back in stock",
            "x": 520,
            "y": 220,
            "font_size": 36,
            "font_weight": 400,
            "color": "#94A3B8",
            "max_width": 600,
            "wrap": true
          },
          {
            "type": "text",
            "value": "named layer price · Buy now →",
            "x": 520,
            "y": 320,
            "font_size": 44,
            "font_weight": 700,
            "color": "#F59E0B"
          }
        ]
      }
    }
    

    Design once. The template lives in your codebase (or jsontoimg’s template storage), and every subscriber’s image is a data variation of it.

    Step 2: Generate One Image Per Subscriber

    Now the fun part. For a list of 10,000 subscribers, you build an array of payloads — one per person — and send it in a single batch request:

    import requests
    
    API_URL = "https://app.jsontoimg.com/api/v1/render"
    
    subscribers = [
        {
            "first_name": "Priya",
            "product_name": "Noise-Cancelling Headphones",
            "product_image": "https://cdn.example.com/products/headphones.png",
            "price": "$199"
        },
        {
            "first_name": "Marcus",
            "product_name": "Mechanical Keyboard",
            "product_image": "https://cdn.example.com/products/keyboard.png",
            "price": "$149"
        },
        # ... 9,998 more
    ]
    
    # Batch: send an array, get an array back
    resp = requests.post("https://app.jsontoimg.com/api/v1/renders/batch", json={
        "jobs": [
            {
                "template": "hero_v2",
                "format": "jpg",
                "layers": {
                    "first_name": { "text": row["first_name"] },
                    "product_name": { "text": row["product_name"] },
                    "price": { "text": row["price"] },
                },
            }
            for row in subscribers[:50]
        ]
    })
    batch = resp.json()  # accepted jobs; poll GET /api/v1/renders/batches/{id}
    

    Each item resolves the named layer placeholders in the template and renders a unique image. For very large lists, or when you don’t want to block on the response, switch to webhook delivery — jsontoimg calls your callback URL when the batch finishes:

    resp = requests.post("https://app.jsontoimg.com/api/v1/renders/batch", json={
        "jobs": [
            {
                "template": "hero_v2",
                "format": "jpg",
                "webhookUrl": "https://api.yourdomain.com/webhooks/jsontoimg",
                "layers": {
                    "first_name": { "text": row["first_name"] },
                    "product_name": { "text": row["product_name"] },
                    "price": { "text": row["price"] },
                },
            }
            for row in subscribers[:50]
        ]
    })
    # 202 + batch id. Loop remaining subscribers in chunks of 50.
    

    Step 3: Cache and Serve the Images

    Here’s the subtlety most people miss: email clients download images at open time, not send time. So you have two options:

    Option A: Render at send time, host statically

    Generate all images before the campaign, upload to your CDN/S3, and reference the static URLs in the email. This is the simplest and most predictable path. For a 50K list at ~100KB per image, that’s about 5GB of storage for one campaign — trivial on any object store.

    Option B: Render at open time (truly dynamic)

    If you want real-time personalization (countdown timers, current inventory, weather-based content), the image URL points to your API and renders on first open:

    https://app.jsontoimg.com/api/v1/img/<template>?sig=...
    

    The email client fetches this URL when the subscriber opens the message, so the image is always current. Add a CDN in front and cache by the full query string — the first open pays the render cost, the next 9,999 hit the cache.

    > Practical rule: use send-time rendering for stable content (names, products, prices) and open-time rendering for anything that must stay fresh (countdowns, stock levels, live offers).

    Step 4: Make the Images Email-Client-Safe

    Email is the most conservative rendering environment on the web, so follow these specs when generating heroes:

    Aspect Best practice
    Display width 600 px (max-width: 600px, width: 100%)
    Source width 1200 px (2x for retina)
    File size ≤ 100–150 KB per image
    Format JPEG for photos, PNG for transparent/logos
    Alt text Always set — images are blocked by default in many clients
    Text/image ratio Keep at least 60% text / 40% image for deliverability

    In your jsontoimg template, that means designing at 1200×630 and letting the API output a compressed JPEG. A 1200px-wide hero displayed at 600px renders crisply on iPhone Retina, MacBook Pro XDR, and 4K displays without bloating the message.

    And always include alt text in the email HTML — most email clients block images by default, and the alt text is what sells the click before the image loads:

    <img src="https://cdn.yourdomain.com/heroes/priya-20260813.jpg"
         width="600" style="width:100%;max-width:600px;height:auto;"
         alt="Priya, your Noise-Cancelling Headphones are back in stock — $199">
    

    The format advice above is worth checking against data rather than taking on faith. Can I email tracks client support feature by feature: WebP in email and AVIF in email are both well short of the near-universal support they enjoy in browsers, which is the whole reason a hero image ships as JPG while the same template serves WebP on the web. The other constraint is proxying: Gmail fetches and caches images through its own image proxy, so an open-time render is fetched by Google rather than by the reader, and per-open personalisation behaves differently than you would expect. Keep the markup boring too — MDN's img reference is a reminder that width, height, and alt are doing real work when images are blocked by default. Caching is the last piece: a hero rendered at send time should go out with a long Cache-Control lifetime, because that file will never change once the message is sitting in someone's inbox.

    Real-World Patterns That Work

    Birthday offers

    Pull the subscriber’s birth date, generate a hero with their name and a “Happy Birthday” offer. Automated birthday emails average a 43% open rate and convert 5x better than promotional emails.

    Back-in-stock alerts

    The hero shows the exact product with the subscriber’s name — not a generic “Your item is available” banner. This is the HostelWorld pattern: the hero calls out something specific to the reader.

    Abandoned cart

    Render the actual product, price, and a countdown (“Your 15% discount expires in 6 hours”) directly into the hero. The image is the reminder; the subject line just gets them to open.

    Location-based content

    Show the nearest store or a local event using the subscriber’s geodata. One template, thousands of local variations.

    Key Takeaways

    • Personalization is measurable: use your ESP’s lift, not a blog statistic. The hero is still the largest pixel in the message
    • One template, many images: design the hero once in JSON, then generate one image per subscriber with a single batch API call
    • Send-time vs open-time: render stable content (name, product, price) at send time; use open-time rendering for countdowns and live data
    • Mind the email specs: 600px display / 1200px source, ≤150KB, JPEG, alt text always, 60/40 text-to-image ratio
    • No infrastructure: no Puppeteer fleet, no design tooling, no per-render lock-in — just JSON in, images out

    FAQ

    What size should a personalized email hero image be?

    Design for 600 px of display width — the safe content width in most email clients — and render at 2x so it stays sharp on retina screens. The client scales it down with CSS.

    Should I render email hero images at send time or at open time?

    Send time is cheaper and safer: you render once per subscriber, host the file, and the email just links to it. Open time is only worth the latency when the content genuinely has to be current at the moment of opening.

    Which image format is safest for email?

    JPG. Email client support for WebP and AVIF is still uneven, so keep those for the web and send JPG (or PNG when you need transparency) in the message itself.

    How many credits does a personalized campaign cost?

    One credit per image, so one per subscriber if every hero is unique. A 10,000-subscriber send is 10,000 images; re-sends that reuse the same stored file cost nothing more.

    Related Resources

    Zoom out: How JSON-to-Image Conversion Works maps the whole template, named-layer, and render-job architecture.

  • Auto-Generate OG Images: Signed URLs in Next.js and WordPress

    How-to for Next.js and WordPress: mint signed OG URLs with POST /api/v1/img/sign. The commercial explainer lives on /use-cases/open-graph-images — this post is the code.

    Overview

    Every time you share a blog post on Twitter, LinkedIn, or Slack, the first thing people see is your Open Graph image. A great OG image can double your click-through rate. A missing or bad one makes your link look broken.

    The problem: most blogs have dozens or hundreds of posts, and manually designing a social preview card for each one doesn’t scale. You need an automated pipeline that generates a unique OG image for every page the moment it’s published.

    This post walks through building exactly that — an automated OG image generation pipeline using jsontoimg. By the end, you’ll have a system that takes your blog post data and returns a branded social preview card, ready to be served by your tags.

    Why You Need Automated OG Images

    Open Graph images serve as the thumbnail when your content is shared on social platforms. Here’s why automating them matters:

    • Scale**: A blog with 200 posts needs 200 unique OG images. Manual design doesn’t scale.

    • Consistency**: Automated templates ensure every card follows the same brand guidelines — same fonts, colors, logo placement.

    • SEO/Social lift**: Pages with custom OG images get 2-3x more social engagement than those without.

    • No developer overhead**: Once the pipeline is set up, each new post gets a card automatically with zero manual work.

    The jsontoimg Approach

    jsontoimg makes this dead simple. You design a template once, then send JSON data for each post. The API handles the rendering, and you get back a PNG ready to serve.

    Here’s the flow:

    Blog post published
      → Your server sends JSON (title, excerpt, author, etc.) to jsontoimg API
      → jsontoimg renders the template with your data
      → Returns a PNG image
      → You serve it via your OG meta tags
    

    Step 1: Design Your OG Image Template

    First, design a template in jsontoimg. A standard OG image is 1200×630 pixels. Your template should include:

    • Background** — a branded color gradient or subtle pattern

    • Logo** — positioned at the top or bottom corner

    • Blog title** — large, bold text, the primary headline

    • Post title** — smaller, readable, fits within the card

    • Author/date** — subtle attribution at the bottom

    • Decorative elements** — lines, shapes, or brand accents

    The template becomes a JSON structure with placeholders for dynamic content. For example:

    {
      "width": 1200,
      "height": 630,
      "background": {
        "type": "gradient",
        "colors": ["#1a1a2e", "#16213e", "#0f3460"]
      },
      "layers": [
        {
          "type": "image",
          "src": "https://yourdomain.com/logo.png",
          "x": 40,
          "y": 40,
          "width": 120,
          "height": 40
        },
        {
          "type": "text",
          "text": "named layer post_title",
          "font": "Inter-Bold",
          "fontSize": 48,
          "color": "#ffffff",
          "x": 60,
          "y": 220,
          "maxWidth": 1080,
          "lineHeight": 1.3
        },
        {
          "type": "text",
          "text": "named layer excerpt",
          "font": "Inter-Regular",
          "fontSize": 22,
          "color": "#a0a0b0",
          "x": 60,
          "y": 380,
          "maxWidth": 900,
          "lineHeight": 1.5
        },
        {
          "type": "text",
          "text": "named layer author · named layer date",
          "font": "Inter-Regular",
          "fontSize": 16,
          "color": "#606080",
          "x": 60,
          "y": 540
        }
      ]
    }
    

    Step 2: Set Up the Generation Pipeline

    Once your template is ready, you call the jsontoimg API whenever a post is published. Here’s a Node.js example:

    // generate-og-image.js
    const JSONTOIMG_API_KEY = process.env.JSONTOIMG_API_KEY;
    const TEMPLATE_ID = 'og-blog-card';
    
    async function generateOGImage(post) {
      const response = await fetch('https://app.jsontoimg.com/api/v1/render', {
        method: 'POST',
        headers: {
          'Authorization': `Bearer ${JSONTOIMG_API_KEY}`,
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({
          template: TEMPLATE_ID,
          format: 'png',
          layers: {
            post_title: { text: post.title },
            excerpt: { text: post.excerpt.substring(0, 120) },
            author: { text: post.author },
            date: { text: new Date(post.publishedAt).toLocaleDateString('en-US', {
              month: 'short',
              day: 'numeric',
              year: 'numeric'
            }) }
          }
        })
      });
    
      const data = await response.json();
      return data.assetUrl;
    }
    

    Python version

    import requests
    
    JSONTOIMG_API_KEY = os.environ.get('JSONTOIMG_API_KEY')
    TEMPLATE_ID = 'og-blog-card'
    
    def generate_og_image(post):
        response = requests.post(
            'https://app.jsontoimg.com/api/v1/render',
            headers={
                'Authorization': f'Bearer {JSONTOIMG_API_KEY}',
                'Content-Type': 'application/json'
            },
            json={
                'template': TEMPLATE_ID,
                'format': 'png',
                'layers': {
                    'post_title': { 'text': post['title'] },
                    'excerpt': { 'text': post['excerpt'][:120] },
                    'author': { 'text': post['author'] },
                    'date': { 'text': format_date(post['published_at']) }
                }
            }
        )
        return response.json()['assetUrl']
    

    Step 3: Hook It Into Your CMS

    The most common approach is to hook into your CMS’s post-publish event. Here are examples for popular platforms:

    Next.js (App Router)

    In your blog post page or layout, generate the OG image on build:

    // app/blog/[slug]/page.tsx
    export async function generateMetadata({ params }): Promise<Metadata> {
      const post = await getPost(params.slug);
    
      // Generate OG image using jsontoimg
      const ogUrl = await generateOGImage(post);
    
      return {
        title: post.title,
        openGraph: {
          title: post.title,
          description: post.excerpt,
          images: [{ url: ogUrl, width: 1200, height: 630 }]
        }
      };
    }
    

    WordPress

    Use the save_post hook to trigger generation whenever a post is published:

    add_action('save_post', 'generate_og_image_for_post', 10, 3);
    
    function generate_og_image_for_post($post_id, $post, $update) {
      if ($post->post_type !== 'post') return;
      if ($post->post_status !== 'publish') return;
    
      $og_url = call_jsontoimg_api([
        'post_title' => $post->post_title,
        'excerpt'    => wp_trim_words($post->post_excerpt, 20),
        'author'     => get_the_author_meta('display_name', $post->post_author),
        'date'       => get_the_date('M j, Y', $post_id)
      ]);
    
      update_post_meta($post_id, '_og_image_url', $og_url);
    }
    

    Static Site Generator (Hugo/11ty)

    Generate all OG images at build time by iterating through your content collection:

    // build-og-images.js — run during your build step
    const fs = require('fs');
    const path = require('path');
    const posts = getBlogPosts();
    
    async function buildAllOGImages() {
      for (const post of posts) {
        const imageUrl = await generateOGImage({
          title: post.title,
          excerpt: post.excerpt,
          author: post.author,
          publishedAt: post.date
        });
    
        // Save the URL or download the image
        const imagePath = path.join('static', 'og', `${post.slug}.png`);
        await downloadImage(imageUrl, imagePath);
      }
    }
    

    Before wiring up delivery, it is worth reading the contract you are satisfying. The Open Graph protocol specification defines og:image and its companion og:image:width and og:image:height properties, which is why supplying the dimensions alongside the URL makes crawlers render the card without fetching the file first. In the App Router those values come back from Next.js generateMetadata, which serialises them into the head for you. And because these images are themselves indexable, Google's image SEO documentation on descriptive filenames and alt text applies to generated assets exactly as it does to hand-made ones.

    Step 4: Serve the OG Image

    With the image URL stored, add the appropriate meta tags to your page’s :

    <meta property="og:image" content="https://yourdomain.com/og/my-awesome-post.png" />
    <meta property="og:image:width" content="1200" />
    <meta property="og:image:height" content="630" />
    <meta property="og:image:type" content="image/png" />
    <meta name="twitter:card" content="summary_large_image" />
    

    For static sites that pre-render, you can download the image and serve it from your own CDN for faster load times. For dynamic sites, jsontoimg supports webhook delivery — the image URL is pushed to your endpoint when rendering completes.

    Batch Generation for Existing Content

    What about your existing 150 posts? You don’t need to trigger the publish hook for each one — just run a batch generation:

    async function generateForAllExistingPosts() {
      const allPosts = await getPublishedPosts();
    
      // Send them all at once using jsontoimg's batch endpoint
      const jobs = allPosts.slice(0, 50).map((post) => ({
        template: TEMPLATE_ID,
        format: 'jpg',
        layers: {
          post_title: { text: post.title },
          excerpt: { text: post.excerpt.substring(0, 120) },
          author: { text: post.author },
          date: { text: formatDate(post.date) },
        },
      }));
    
      const response = await fetch('https://app.jsontoimg.com/api/v1/renders/batch', {
        method: 'POST',
        headers: {
          'Authorization': `Bearer ${JSONTOIMG_API_KEY}`,
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({ jobs })
      });
    
      const results = await response.json();
      // poll GET /api/v1/renders/batches/{id}; each done job has assetUrl
    }
    

    With jsontoimg’s batch endpoint, you can generate 150 OG images in seconds — something that would take hours with manual design tools and days of Puppeteer-infrastructure headache.

    Cost Comparison

    | Approach | Cost per 1K images | Infrastructure overhead |

    |—|—|—|

    | Manual design (Canva/Figma) | ~$500 (designer time) | None |

    | Puppeteer/Playwright DIY | ~$30 (server cost) | High (Docker, Chrome, scaling) |

    | Vercel OG (@vercel/og) | ~$20 (edge functions) | Medium (locked to Vercel) |

    | **jsontoimg** | **~$5-10** | **Low (just the API)** |

    Beyond cost, jsontoimg saves you from maintaining headless browsers, managing font loading, handling timeouts, and debugging rendering inconsistencies across different environments.

    Key Takeaways

    • Design once, generate thousands** — a single jsontoimg template replaces hundreds of manual designs

    • Integrate in minutes** — a few lines of code hook into your CMS or static site generator

    • Batch existing content** — generate OG images for your entire archive in one API call

    • No infrastructure** — no Puppeteer, no Chrome, no Docker containers to maintain

    • Brand consistency** — every social share card follows the same template, every time

    FAQ

    What size should an Open Graph image be?

    1200×630 pixels. It is the ratio Facebook, LinkedIn, and X all crop cleanly, and it stays legible in the small card previews most feeds render.

    How do I add an automated Open Graph image to Next.js?

    Mint a signed URL with POST /api/v1/img/sign and return it from the route's metadata.openGraph.images. The URL goes in the HTML head like any other; no build step renders it.

    Does every page view re-render the OG image?

    No. The first unique GET renders the image and costs one credit; every later request streams the stored file from the CDN. A viral post does not cost more than a quiet one.

    Can WordPress generate the og:image automatically?

    Yes. The WordPress plugin renders from the post's own fields on publish and writes the result into the og:image tag, so an editor never has to open a design tool.

    Related Resources

    Zoom out: How JSON-to-Image Conversion Works maps the whole template, named-layer, and render-job architecture.