Grok Image Generation API: Aspect Ratio & Base64 Guide

Written by

in

Generating Images with xAI’s Grok Imagine Models: Aspect Ratios, Base64 Output, and Endpoint Design

xAI’s image generation endpoint (/v1/images/generations) powers text-to-image synthesis across the Grok Imagine family—including grok-imagine-image and grok-imagine-image-2.0—giving developers direct control over framing, batch size, quality, and how binary image payloads enter their application.

For teams building media pipelines, web apps, or automated asset generators, two details matter immediately: how aspect_ratio shapes composition and how response_format: "b64_json" changes storage and latency trade-offs.


How /v1/images/generations Works

Calls to [https://api.x.ai/v1/images/generations](https://api.x.ai/v1/images/generations) accept a JSON body specifying a model, a prompt, and optional generation controls. You can invoke the REST endpoint directly, use the xAI Python SDK, or connect via OpenAI-compatible clients and Vercel’s AI SDK (@ai-sdk/xai).

Key request parameters documented for Grok image generation include:

  • model & prompt: Identifies the Grok Imagine model (such as grok-imagine-image-2.0) and describes the scene, subject, lighting, and framing.
  • n: Controls how many images are generated in a single request (1 to 10 on the REST API and OpenAI-compatible SDKs, defaulting to 1). In the xAI Python SDK, sample() generates a single image while sample_batch(n=...) generates multiple images (n is required).
  • aspect_ratio: Sets the width-to-height proportion of the generated image, or defaults to auto when omitted so the model selects a ratio suited to the prompt.
  • quality: Supported on grok-imagine-image-2.0 with values low, medium, and auto (which defaults to low for generation and medium for edits). Pinning medium (alongside higher resolution such as 2k) helps preserve fine details.
  • response_format: Selects between url (default, returning temporary hosted URLs) and b64_json (returning base64-encoded image data directly in the JSON response).
  • deferred: When set to true, returns a request_id right away so you can poll GET /v1/images/{request_id} (or listen via webhooks such as image.generation.completed) for long-running batches, retaining url outputs for 24 hours.

Controlling Framing with aspect_ratio

Picking the right aspect_ratio upfront prevents awkward cropping later and aligns visual assets with their target UI containers.

Aspect Ratio Typical Use Cases
1:1 Social media posts, square cards, thumbnails
16:9 / 21:9 Widescreen banners, video frames, cinematic compositions
9:16 Vertical mobile stories and short-form video canvases
4:3 / 3:4 Presentations, editorial layouts, portraits
19.5:9 / 20:9 (and inverted) Modern smartphone displays
auto Lets the model choose the ratio based on the prompt when omitted

When prompting grok-imagine-image-2.0, pair your aspect_ratio choice with clear spatial framing in the prompt—naming the subject, count, camera angle, lighting, and color fields explicitly rather than relying on vague style buzzwords. If you need to tweak only one or two details on an existing image while keeping its layout intact, /v1/images/edits is better suited than regenerating from scratch.


b64_json vs. Temporary URLs

By default, /v1/images/generations returns temporary hosted URLs (url). Because those URLs are temporary, they work well for quick previews or immediate downstream fetching, but they should not be treated as permanent asset links.

Setting "response_format": "b64_json" embeds the base64-encoded image payload directly inside the API response. That design pays off when:

  • You plan to persist or post-process the image immediately: You can decode the base64 string straight to disk, an object store, or an image-processing pipeline without a second network round-trip to a short-lived URL.
  • You want inline transport in server-to-server workflows: Passing base64 payloads inside internal service calls or data:...;base64,... image inputs avoids expiration edge cases.

The trade-off is payload size: base64 encoding expands binary data by roughly one-third and increases JSON response weight—especially at 2k resolution or higher n counts—so streaming or asynchronous batching (deferred: true, which uses url outputs) may be preferable for large multi-image jobs.

Example Request (curl)

curl -X POST https://api.x.ai/v1/images/generations 
  -H "Authorization: Bearer $XAI_API_KEY" 
  -H "Content-Type: application/json" 
  -d '{
    "model": "grok-imagine-image-2.0",
    "prompt": "Overhead shot of a pour-over coffee setup on a pale oak table in morning sunlight, ceramic dripper, glass server, and folded linen cloth",
    "aspect_ratio": "3:2",
    "resolution": "2k",
    "quality": "medium",
    "response_format": "b64_json",
    "n": 1
  }'

Practical Integration Tips

  • Check moderation metadata: When using the xAI SDK, inspect fields such as response.respect_moderation so your app handles filtered outputs cleanly rather than assuming an image was returned.
  • Parallelize distinct prompts: If you need several unrelated images with different prompts, dispatch concurrent requests (for example with AsyncClient and asyncio.gather in Python) instead of waiting on them sequentially.
  • Know when to use the agent tool instead: If an LLM is already orchestrating a multi-step conversation or chaining web search with image creation and follow-up edits, attaching the image_generation tool lets the model write the prompt and invoke Grok Imagine server-side; call /v1/images/generations directly when you want deterministic control over aspect_ratio, quality, and response_format.

Comments

Leave a Reply

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