Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Some links on this page are affiliate links: if you buy through them we may earn a commission, at no extra cost to you.

Use the image API only for the artwork, then let a deterministic Node.js pipeline place that artwork behind your fixed template. Generate a composition-safe background, decode the returned Base64 into a Buffer, resize and crop it with Sharp, and composite your transparent overlay, logos, and text afterward. This keeps typography, branding, and geometry repeatable while still giving every output a new visual background.

What the pipeline does

A reliable implementation separates variable and fixed content:

  • Generated layer: scenery, texture, lighting, or an abstract backdrop.
  • Template layers: exact copy, fonts, logos, badges, guides, and layout.
  • Renderer: Sharp, which fits the generated image to the canvas and composites the fixed layers over it.

The image API can generate or edit images and configure dimensions, quality, format, compression, and background behavior. Its documented output formats are PNG, JPEG, and WebP; PNG or WebP is required when you need an alpha channel. See the OpenAI image-generation guide for the currently available models and parameters.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Do not ask the model to typeset your headline or reproduce a logo. The guide notes that precise text placement and clarity can still be difficult. Render those elements in your own template instead.

Prepare the Node.js project

Use a runtime supported by the versions you install. The Sharp project currently states support for Node.js ≥ 20.9.0 among runtimes supporting Node-API v9; check the Sharp repository if your deployment uses another version.

  1. Create a project and install the SDK and image library:
    mkdir ai-template-renderer
    cd ai-template-renderer
    npm init -y
    npm install openai sharp dotenv
  2. Add OPENAI_API_KEY to a .env file. Keep the key on the server, never in browser code.
  3. Put a transparent foreground template at assets/template-overlay.png. Its canvas should be the final output size; transparent regions reveal the generated background.

Choose the final canvas before writing the prompt. Common dimensions listed in the image guide include 1024×1024 (square), 1536×1024 (landscape), and 1024×1536 (portrait). Newer models may accept custom dimensions subject to model-specific limits, so verify the selected model’s current constraints.

Design a composition-safe prompt

Tell the model what belongs in the background and where the template will place copy. For example:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Wide cinematic mountain landscape at sunrise, realistic atmospheric haze,
open low-detail negative space on the left third for a large title,
subjects concentrated on the right, no words, no logos, no watermark,
clean edges and colors that support dark text.

Negative space is a design requirement, not a guarantee. Review every result for visual collisions and contrast. If a subject must be isolated, explicitly request a transparent background. A checkerboard pattern drawn into the image is not transparency; preserve the returned alpha channel and select PNG or WebP as recommended by the image-prompting guidance.

Generate the background and composite the template

The following complete example uses the official OpenAI Node client shape documented in its image resource source. Set IMAGE_MODEL to a model available to your account. Parameters and response fields can change with model versions, so confirm them in the current API documentation.

import 'dotenv/config';
import OpenAI from 'openai';
import sharp from 'sharp';
import { mkdir } from 'node:fs/promises';

const client = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });
const model = process.env.IMAGE_MODEL || 'gpt-image-1';
const width = 1536;
const height = 1024;
const outputPath = 'output/post.webp';

const prompt = `Wide cinematic mountain landscape at sunrise, realistic atmospheric haze,
open low-detail negative space on the left third for a large title,
subjects concentrated on the right, no words, no logos, no watermark,
clean edges and colors that support dark text.`;

if (!process.env.OPENAI_API_KEY) {
  throw new Error('Set OPENAI_API_KEY before running this script.');
}

await mkdir('output', { recursive: true });

const response = await client.images.generate({
  model,
  prompt,
  size: '1536x1024',
  output_format: 'png'
});

const encoded = response.data?.[0]?.b64_json;
if (!encoded) {
  throw new Error('The image response did not contain b64_json data.');
}
const generatedBackground = Buffer.from(encoded, 'base64');
const templateOverlay = await sharp('assets/template-overlay.png')
  .png()
  .toBuffer();

await sharp(generatedBackground)
  .resize(width, height, { fit: 'cover', position: 'centre' })
  .composite([{ input: templateOverlay, left: 0, top: 0 }])
  .webp({ quality: 88 })
  .toFile(outputPath);

console.log(`Wrote ${outputPath}`);

Run it with node render.js. The generated response is Base64 image data; Buffer.from(..., 'base64') converts it to bytes that Sharp accepts. Sharp’s documented compositing operation places listed overlays over the processed (resized or extracted) base image; operation order therefore matters. See Sharp compositing documentation.

Why fit: 'cover' is used

cover fills the exact template canvas and crops the excess. Generate near the template’s aspect ratio to reduce cropping. If every edge matters, use fit: 'contain' and choose a deliberate background color, or generate at the exact supported dimensions instead. Test your crop against the text-safe area rather than assuming the model will keep a subject in place.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Preserving transparency

The foreground PNG must retain its alpha channel. Do not flatten it against white before compositing. If the generated layer itself needs transparency, request it explicitly, select PNG or WebP, and inspect the result with sharp(input).metadata() for an alpha channel. JPEG cannot carry alpha.

Adding more deterministic layers

Pass several overlays in z-order. Earlier entries are placed first and later entries appear above them:

const logo = await sharp('assets/logo.png').png().toBuffer();
const badge = await sharp('assets/badge.png').png().toBuffer();

await sharp(generatedBackground)
  .resize(width, height, { fit: 'cover' })
  .composite([
    { input: templateOverlay, left: 0, top: 0 },
    { input: logo, left: 64, top: 56 },
    { input: badge, left: 1280, top: 56 }
  ])
  .png()
  .toFile('output/post.png');

All composite inputs must fit within the processed base image. Resize or position them so their bounds remain inside the canvas.

Choose output and quality settings

Need Recommended choice Reason
Transparency PNG or WebP These formats can preserve an alpha channel; JPEG cannot.
Photographic delivery image WebP with an explicit quality value Usually smaller than PNG; choose quality according to visual review.
Pixel-perfect archival output PNG Lossless encoding and alpha support.
Small preview Resize after compositing, then encode WebP or JPEG Downscaling the finished design avoids changing template geometry.

The API also exposes quality and compression controls, but their accepted values are model-specific. Confirm them before relying on a particular setting.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Production reliability and performance

Handle long-running requests

Complex prompts can take up to two minutes according to the image guide. Set an HTTP timeout appropriate for that possibility, retry only transient failures with bounded backoff, and avoid launching duplicate jobs when a client retries. For user-facing systems, queue generation and return a job identifier rather than holding a short web request open.

Validate every response

  • Check that image data exists before decoding Base64.
  • Use Sharp metadata to verify width, height, format, and alpha before compositing.
  • Reject unexpectedly large files to protect memory.
  • Record the prompt, model, requested size, and final output format so a result can be reproduced as closely as the model allows.

Expect visual variation

Recurring characters and brand elements may not remain visually consistent. Keep those elements in fixed template layers and review each generated scene. A deterministic crop policy and fixed overlay geometry make variation less disruptive, but they cannot make the generated artwork identical.

Control throughput

Generate at the target aspect ratio, avoid unnecessary intermediate encodes, and process independent jobs through a bounded queue. Sharp performs resize and related operations before composition, so resize once to the canvas rather than repeatedly scaling each layer.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Troubleshooting

response.data[0].b64_json is missing

The selected endpoint, model, or output mode may return a different response shape. Log the non-secret response structure, then compare it with the current SDK source and image guide. Do not assume a URL or Base64 field without checking the selected API.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

“Invalid size” or a dimension error

The requested dimensions are not supported by that model. Use one of the documented recommended sizes, or consult the model’s current limits and change size and your Sharp canvas accordingly.

Overlay appears off-canvas or the composite fails

Sharp requires composite inputs to fit within the processed image. Inspect each overlay’s metadata, resize it, and ensure left + width and top + height do not exceed the base dimensions.

Text is unreadable or covered

Move the copy into a prompt-defined low-detail area, add a contrast treatment (such as a fixed translucent panel) to the template, and render the text outside the image model. Never depend on generated lettering for exact copy.

Transparent output has a white background

Confirm that transparency was requested, that the API output format is PNG or WebP, and that no later Sharp operation flattened the alpha channel. A checkerboard visible in the pixels is artwork, not transparency.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

The script times out

Allow for the guide’s up-to-two-minute processing caveat, increase the client timeout, and move work to a queue for production. Retry transient network errors with a limit; do not blindly retry validation or authentication errors.

Or skip the browser setup

If your next step is capturing the finished page rather than building the artwork, ScreenshotNeo provides a website screenshot API and MCP server. It accepts consent banners before capture and removes more than 60 known consent platforms, newsletter popups, and chat widgets; bot checks, blank pages, timeouts, failed loads, and cache hits are not billed. Responses identify the page verdict and billing status in X-Page-Verdict and X-Billed headers. AI agents can call its take_screenshot, get_page_info, and capture_pdf MCP tools.

One-call example (see the ScreenshotNeo API documentation):

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp

There is a free allowance of 1,000 screenshots per month with no card. Paid plans start at $5 for 3,000 shots, and every feature is included on every plan. Create a free ScreenshotNeo account.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

FAQ

Frequently Asked Questions

Can I use an existing image instead of generating a new background?

Yes. Use an image-editing endpoint or load an existing file into Sharp, then apply the same resize-and-composite pipeline. Keep the overlay and typography steps unchanged.

Should I generate at the exact final pixel dimensions?

Generate at a supported size close to the target aspect ratio, then let Sharp establish the exact canvas. This gives you predictable crop behavior when model limits do not match your template.

How can I make backgrounds consistent across a batch?

Use a stable prompt structure, fixed crop policy, and fixed template layers, while reviewing each result. The image guide cautions that recurring visual elements can still vary.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.