Hardware FixRecommendedDevice not working? Your driver may be the problemCheck updates for common hardware issues.Fix DriversOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsPC HealthRecommendedCrashes, freezes, slowdowns? Check your PC nowSpot repairable issues before they interrupt work.Check PC×
Skip to content
AI APIs

How to Generate Images From Code: Drawing, Browser Canvas, and AI APIs

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

There are two different ways to generate an image with code: draw a predictable composition (pixels, text, shapes and existing assets), or send a prompt and optional input images to a generative model. Use Pillow, Canvas or ImageMagick when exact geometry and repeatability matter; use an image API when you need semantic synthesis or an AI-guided edit. The sections below show both workflows, with runnable examples and the operational issues that commonly break them.

Choose the right image-generation workflow

What you need Good starting point Why
Text, shapes, overlays or compositing in Python Pillow ImageDraw Draws directly on an image and supports transparent layers and alpha compositing.
Drawing or composing in a web page HTML Canvas 2D drawImage() accepts images and programmatically created sources.
Batch conversion, resizing or command-line drawing ImageMagick The magick command converts, transforms and draws, including SVG/MVG workflows.
A new scene from a natural-language prompt, or an AI-guided edit A hosted image API The provider supplies a model that synthesizes pixels from text and image inputs.

Before choosing, decide whether you need deterministic layout, which runtime and language you have, whether semantic synthesis is required, the input/output formats (including transparency), and what limits your provider or deployment imposes. The available documentation does not establish that one approach is universally faster, cheaper or higher quality.

Generate a deterministic image in Python with Pillow

Pillow modifies an image through an ImageDraw.Draw context. This is ideal for certificates, thumbnails, charts, social cards and any design whose coordinates should be identical on every run.

Install and run a complete example

python -m pip install pillow
from PIL import Image, ImageDraw, ImageFont

WIDTH, HEIGHT = 1200, 630
base = Image.new("RGBA", (WIDTH, HEIGHT), (20, 28, 48, 255))
draw = ImageDraw.Draw(base)

# Background shapes
draw.rounded_rectangle((60, 60, WIDTH - 60, HEIGHT - 60), radius=32,
                       fill=(35, 48, 78, 255), outline=(90, 180, 255, 255), width=4)
draw.ellipse((820, 100, 1120, 400), fill=(255, 170, 80, 220))

# A transparent overlay is useful for effects or separately composited artwork
overlay = Image.new("RGBA", base.size, (0, 0, 0, 0))
overlay_draw = ImageDraw.Draw(overlay)
overlay_draw.rectangle((0, 500, WIDTH, HEIGHT), fill=(0, 0, 0, 90))
base = Image.alpha_composite(base, overlay)
draw = ImageDraw.Draw(base)

# Use a known TrueType font path in production for consistent metrics.
try:
    font = ImageFont.truetype("DejaVuSans-Bold.ttf", 64)
    small = ImageFont.truetype("DejaVuSans.ttf", 30)
except OSError:
    font = ImageFont.load_default()
    small = font

draw.text((110, 150), "Generated by code", font=font, fill="white")
draw.text((110, 530), "Repeatable pixels, predictable output", font=small,
          fill=(220, 230, 245, 255))
base.convert("RGB").save("python-card.webp", "WEBP", quality=90)

The drawing context changes its target in place. For overlays, draw on a separate RGBA image and alpha-composite it over the base. Font availability is a deployment concern: TrueType loading depends on the font file and the Pillow build, so package a licensed font and use an absolute or configured path when output must match across machines. Save as PNG for lossless or transparent output; JPEG does not preserve an alpha channel; WebP can be lossy or lossless depending on encoder settings.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Wacom Intuos Small, Wired Graphic Drawing Tablet with Pen + Software
  • Wacom Intuos Small Graphics Drawing Tablet: Enjoy industry leading tablet performance in superior control and precision with Wacom's EMR, battery free technology that feels like pen on paper
  • Works With All Software: Wacom Intuos tablet can be used in any software program to explore new facets of digital creativity; draw, paint, edit photos/videos, create designs, and mark up documents
  • What the Professionals Use: Wacom's industry leading pen technology and pen to paper feeling makes it the preferred drawing tablet of professional graphic designers
  • Software and Training Included: Only Wacom gives you software with every purchase. Register your Intuos tablet and gain access to some of the best creative software and Wacom's online training
  • Wacom is the Global Leader in Drawing Tablet and Displays: For over 40 years in pen display and tablet market, you can trust that Wacom to help you bring your vision, ideas and creativity to life

Make layout data-driven

Keep colors, margins, font sizes and content in a configuration object, then calculate positions from the canvas dimensions rather than hard-coding every coordinate. Measure text with draw.textbbox() before centering, wrap long strings, and render at a larger working resolution before downsampling when small text looks jagged. Validate user-supplied text and paths so a batch job cannot overwrite arbitrary files.

Generate browser images with Canvas

Canvas is the natural choice when the output is already in a browser: diagrams, editors, previews and client-side exports. drawImage() can draw an image, video, canvas or other permitted source.

<canvas id="card" width="1200" height="630"></canvas>
<button id="save">Download PNG</button>
<script>
const canvas = document.querySelector('#card');
const ctx = canvas.getContext('2d');

ctx.fillStyle = '#141c30';
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = '#23304e';
ctx.roundRect(60, 60, 1080, 510, 32, 32);
ctx.fill();
ctx.fillStyle = '#ffffff';
ctx.font = 'bold 64px system-ui';
ctx.fillText('Generated in Canvas', 110, 220);

const image = new Image();
image.onload = () => {
  ctx.drawImage(image, 820, 100, 260, 260);
};
image.src = '/assets/logo.png';

document.querySelector('#save').addEventListener('click', () => {
  const link = document.createElement('a');
  link.download = 'canvas-card.png';
  link.href = canvas.toDataURL('image/png');
  link.click();
});
</script>

For remote images, set crossOrigin before src and configure the image server's CORS headers. Without an allowed CORS response, the canvas becomes tainted and export methods such as toDataURL() fail. This is a browser security rule, not a problem with the drawImage() syntax. Wait for onload before drawing, and handle onerror so a missing asset does not silently produce an incomplete card. Use toBlob() for large files to avoid holding a long base64 string in memory.

Use ImageMagick for scripts and batch jobs

ImageMagick's magick command is useful when a shell pipeline must create, resize, crop, convert or annotate many files. Operations are applied in command order.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
# Create a canvas, draw a background and text, and write PNG
magick -size 1200x630 canvas:'#141c30' 
  -fill '#23304e' -draw 'roundrectangle 60,60 1140,570 32,32' 
  -fill white -pointsize 64 -gravity NorthWest 
  -annotate +110+150 'Generated by ImageMagick' output.png

# Resize a directory of images (write to a separate directory)
mkdir -p thumbs
magick mogrify -path thumbs -thumbnail '800x800>' *.jpg

For more complex vector artwork, generate SVG and let ImageMagick render it, or use its MVG drawing language for small command-line compositions. The ImageMagick documentation recommends SVG rather than hand-authoring MVG for sufficiently complex graphics. Quote shell arguments carefully, especially text containing spaces, parentheses or user input. Pin the ImageMagick version in CI and inspect exit codes; a successful command can still produce an unexpected format if the output extension or delegate support is missing.

Rank #2
Sale
XPPen Deco 01 V3 10x6 Drawing Tablet, 16K Battery-Free Stylus, 8 Keys
  • Word-first 16K Pressure Levels: The upgraded stylus features 16,384 levels of pressure sensitivity and supports up to 60 degrees of tilt, delivering smoother lines and shading for a natural drawing experience. With no battery or charging needed, it operates like a real pen, making it easy for beginners to create effortlessly. This functionality helps novice artists develop their skills and explore their creativity without the intimidation of complex tools
  • Designed for Beginners: This drawing pad desinged with 8 customizable shortcuts for both right and left-hand users, express keys create a highly ergonomic and convenient work platform
  • Perfectly Adapted for Android: The XPPen Deco 01 V3 art tablet supports connections with Android devices running version 10.0 and above. It is recommended to download the XPPen Tools Android application, which adapts to your smartphone's screen aspect ratio, ensuring accurate mapping. It also supports mapping on Android screens with different aspect ratios in portrait mode
  • Large Drawing Space, Bigger Bold Inspiration: This expansive drawing pad has10 x 6.25-inch helps you break through the limit between shortcut keys and drawing area
  • Easy Connectivity for Beginners: The Deco 01 V3 offers USB-C to USB-C connectivity, plus adapters for USB C. This ensures easy connection to various devices, allowing beginner artists to set up quickly and focus on their creativity without compatibility concerns. Whether using a laptop, tablet, or desktop, the Deco 01 V3 provides a seamless experience, making it an ideal choice for those just starting their digital art journey

Generate or edit an image with a hosted AI API

Use an image API when a prompt such as “a watercolor map of…” should determine the scene, or when an input image needs semantic editing. OpenAI's documentation says the Image API is the best choice for a single generation or edit request; a Responses API image tool is intended for conversational, multi-step experiences. Google documents Gemini API examples in Python and JavaScript that return image data which can be decoded and written to PNG.

OpenAI-style Python request

Keep the key in an environment variable. Model names, supported sizes and output controls change, so select a currently eligible image model and settings from the provider's reference before deploying.

import os, base64
from openai import OpenAI

client = OpenAI(api_key=os.environ['OPENAI_API_KEY'])
result = client.images.generate(
    model='gpt-image-1',  # confirm the current model identifier and access
    prompt='A clean isometric illustration of a developer pipeline, blue and amber, no text',
    size='1024x1024',
    quality='auto',
)
image_bytes = base64.b64decode(result.data[0].b64_json)
with open('generated.png', 'wb') as f:
    f.write(image_bytes)

The documented controls include size, quality, format, compression and background, but exact combinations are model-specific. PNG is the documented default; JPEG or WebP are available for supported GPT Image models, and transparent backgrounds require PNG or WebP. Treat commonly recommended square, landscape and portrait dimensions as provider settings, not universal rules. Handle rate limits, timeouts, malformed responses and content-policy errors, and never log the API key or untrusted prompt data.

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.

Provider-neutral integration pattern

  1. Read credentials from a secret manager or environment variable.
  2. Send the prompt and optional image inputs to the provider's current generation or edit endpoint.
  3. Check the HTTP status and response schema before decoding bytes or base64.
  4. Write to a temporary file, validate the MIME type and dimensions, then atomically rename it into place.
  5. Record the model, requested settings and your own job identifier so a result can be reproduced when the provider permits it.

Google's Python and JavaScript samples follow the same pattern: call the Gemini API, locate the returned image part, decode it and write a PNG. Use the current Google SDK setup and model identifier from its documentation rather than copying an outdated endpoint.

Reliability, performance and cost decisions

Deterministic pipelines

  • Reuse a drawing surface and fonts for batches, but do not share mutable image objects between concurrent jobs without isolation.
  • Prefer PNG for diagrams, text and transparency; choose JPEG or WebP when a smaller photographic file is more important.
  • Limit dimensions and decoded pixel counts for untrusted uploads to avoid memory-exhaustion attacks.
  • Cache assets and use content hashes for repeatable builds. Store intermediate files outside the web root until validation completes.

Hosted generation

  • Expect variable latency and transient failures; use bounded retries with exponential backoff and an idempotency strategy where the provider supports one.
  • Set explicit request timeouts, queue long jobs and expose progress rather than keeping a browser request open indefinitely.
  • Budget for provider usage according to the current account and model terms. The supplied technical documentation contains no comparative prices or performance benchmark.
  • Review eligibility, image-input limits, dimensions, background support and retention/privacy terms before accepting user content.

Troubleshooting common failures

“Font not found” or changed text wrapping

Install and package the same font file, pass its absolute path, and measure text with the actual loaded font. Do not rely on a desktop font that is absent in a container.

Rank #3
Sale
XPPen Artist 13.3 Pro V2 Drawing Tablet with Screen, 16K, Full-Laminated
  • PLEASE NOTE:XPPen Artist13.3 Pro drawing tablet Need to connect with computer,you need to use it with your computer or laptop, the 3 in 1 cable is included
  • Drawing Tablet with Screen: Tilt Function- XPPen Artist 13.3 Pro supports up to 60 degrees of tilt function, so now you don't need to adjust the brush direction in the software again and again. Simply tilt to add shading to your creation and enjoy smoother and more natural transitions between lines and strokes
  • Graphics Tablets: High Color Gamut- The 13.3 inch fully-laminated FHD Display pairs a superb color accuracy of 88% NTSC (Adobe RGB≧91%,sRGB≧123%) with a 178-degree viewing angle and delivers rich colors, vivid images, and dazzling details in a wider view. Your creative world is now as powerful as it is colorful
  • Drawing Pad: One is enough- The sleek Red Dial on the display is expertly designed with creators in mind, its strategic placement allows for natural drawing postures. With just one wheel, you can effortlessly zoom in and out, adjust brush sizes, and flip the canvas—all tailored to suit the habits of everyday artists. The 8 customizable shortcut keys allow you to personalize your setup, streamlining your workflow and enhancing creative efficiency
  • Universal Compatibility & Software Support:supports Windows 7 (or later), Mac OS X 10.10 (or later), Chrome OS 88 (or later), and Linux systems. Fully compatible with major creative software including Photoshop, Illustrator, SAI, and Blender 3D. Register your device to access additional programs like ArtRage 5 and openCanvas for expanded creative possibilities.

Canvas export throws a security error

The canvas is tainted by a cross-origin image. Serve the asset with an appropriate CORS header, set crossOrigin before assigning src, or proxy the asset through a server you control.

ImageMagick says a delegate or coder is missing

Your build lacks support for that format or SVG renderer. Check magick -version, install the required delegate in the runtime image, and choose a format supported by the deployed build.

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

An AI response has no usable image

Log status and a redacted response shape, not secrets. Verify the model is enabled for the account, inspect returned parts for image data, and confirm that requested size, format, background and input images are supported together.

The result is blank or partially drawn

In Canvas, wait for image load events. In Pillow and ImageMagick, check that source paths exist and inspect command exit codes. For APIs, write the response to a temporary file and validate its magic bytes before publishing it.

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

Or skip the browser setup

If your “image” is actually a rendered web page, dashboard or documentation view, ScreenshotNeo returns a screenshot from one GET request and can remove consent banners, newsletter popups and chat widgets before capture. Only clean shots are billed: bot checks, CAPTCHAs, blank pages, timeouts, failed loads and cache hits are not billed, and response headers identify the page verdict and billing status. Its MCP server exposes take_screenshot, get_page_info and capture_pdf to Claude, Cursor and other MCP clients.

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

See the ScreenshotNeo API documentation for all options, including viewport and device presets, full-page lazy-image loading, CSS-selector element capture, dark mode, retina scale, PDF settings, custom CSS and JavaScript, clicks, waits, request blocking, headers, cookies, user agents, authorization, timezone, geolocation, transparent backgrounds, resizing, TTL caching, signed image links, asynchronous webhooks, bulk capture and usage reporting.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #4
Sale
HUION Inspiroy H640P 6x4 inch Drawing Tablet 8192 Pen Pressure
  • Customize Your Workflow: The 6 customizable press keys on Huion H640P drawing tablet for pc let you assign your most-used commands—like undo, zoom, brush switch, or save—so you can keep your hands on the tablet and your mind on the art. Whether you're a digital painter switching brushes, or a comic artist zooming in and out, these keys keep your workflow smooth and uninterrupted. Plus, the Huion driver lets you save different shortcut profiles for different apps, so you never have to reconfigure when switching software.
  • Professional Pen Performance: Huion H640P drawing pad for computer comes with the battery-free PW100 stylus that's always ready when inspiration strikes. With 8192 levels of pressure sensitivity, every light sketch, or bold stroke responds naturally to your hand—just like a real pen. The 5080 LPI resolution and 233 PPS report rate deliver lag-free, precise strokes, so you can draw confidently without second-guessing your cursor. The pen side buttons help you switch between pen and eraser instantly.
  • Compact and Portable: Huion H640P computer graphics tablet features a compact, ultra-portable design at just 0.3 inches thin and 0.61 lbs light, so it slides easily into your backpack—perfect for sketching in coffee shops, taking notes in class, or editing on the go between home and studio. The 6x4 inch active area offers enough room for natural pen movements while fitting comfortably on crowded desks, or lecture hall seats.
  • Stable Compatibility: Huion H640P graphic drawing tablet works seamlessly with Mac, Windows, Linux PCs, and Android smartphones/tablets (OS version 6.0 or later). Left-handed friendly, and you just need to flip the tablet and adjust the settings in the driver. Please note: H640P does NOT support iPhone/iPad.
  • Move Beyond the Mouse: Huion Inspiroy H640P is a pen tablet that replaces your mouse for more natural, precise control. Freehand draw, take notes, or even play OSU—everything you do with a mouse, you can do better with a pen. The precise tip makes it ideal for detailed photo editing, graphic design, or signing PDF. Meanwhile, the ergonomic pen grip helps you avoid the strain that comes from hours of using a mouse.

Python

import requests
r = requests.get("https://api.screenshotneo.com/v1/shot", params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"}, timeout=90)
r.raise_for_status()
open("shot.webp", "wb").write(r.content)

Node.js

const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);
if (!res.ok) throw new Error(`Screenshot failed: ${res.status}`);
const fs = await import('node:fs/promises');
await fs.writeFile('shot.webp', Buffer.from(await res.arrayBuffer()));

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.

FAQ

Can code generate an image without AI?

Yes. Pillow, Canvas and ImageMagick construct pixels deterministically from drawing commands and existing assets.

Which method preserves transparency?

Use RGBA in Pillow or Canvas and export PNG or a supported WebP configuration. JPEG has no alpha channel.

Should I use an image API for a chart?

Usually not. A deterministic drawing library gives exact labels and repeatable geometry; use an AI API when you need synthesis or semantic editing.

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

Why do generated dimensions vary by provider?

Image models impose their own size and format limits. Check the current model reference rather than assuming dimensions accepted by another provider will work.

Best Value
Sale
HUION Inspiroy H1060P Graphics Drawing Tablet, 10 x 6.25 in, 12+16 Hot Keys
  • Working Area Configuration - HUION art tablet equips with a 10 x 6.25 inches working area, providing the user with the most comfortable size to work; the 10mm slim structure and minimalist design of appearance make the drawing tablet more attractive.
  • Tilt Function Battery-free Stylus: This computer graphics tablet come with a battery-free stylus PW100, no need to charge, allowing for constant uninterrupted drawing. ±60° tilt support enables imitation of lines input with diverse drawing gestures, with accuracy ensured.
  • Press Keys:12 programmable press keys plus 16 programmable soft keys, you can set shortcut keys on drawing tablet's driver based on your preferences, such as erase, zoom in/out, scroll up and down, and so on.
  • Compatibility: HUION graphics tablet supports Windows 7 or later/ macOS 10.12 or later/ Android 6.0 or later/ Linux (Ubuntu). A USB adapter is required to connect to a Mac computer. H1060P supports various mainstream design and drawing software, including PS, SAI, AI, CDR, etc. (Please note: The H1060P is compatible with Ubuntu, but it requires the use of the Xorg display server. Wayland is not supported.)
  • NOTE: You can easily connect your phone to the art tablet via the OTG connector; while iPhone and iPad are NOT at the moment. The cursor will not show up in the SAMSUNG Galaxy S series at present. If you are not sure whether the product is compatible with your Phone or any help, please contact us.

Frequently Asked Questions

Can code generate an image without AI?

Yes. Pillow, Canvas and ImageMagick construct pixels deterministically from drawing commands and existing assets.

Which method preserves transparency?

Use RGBA in Pillow or Canvas and export PNG or a supported WebP configuration. JPEG has no alpha channel.

Should I use an image API for a chart?

Usually not. A deterministic drawing library gives exact labels and repeatable geometry; use an AI API when you need synthesis or semantic editing.

Free tools Windows power users keep installed

One-click scans. No signup required.

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

Why do generated dimensions vary by provider?

Image models impose their own size and format limits. Check the current model reference rather than assuming dimensions accepted by another provider will work.

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.

Leave a Reply

Your email address will not be published. Required fields are marked *

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

Read next

Recommended PC Tool
Recommended PC Tool
Crashes, No Sound, or Screen Glitches?Free driver scan
Windows Errors? Fix Them Before They SpreadFree repair scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.