Generating Images with xAI’s Grok Imagine API: aspect_ratio and b64_json
Generating images programmatically through xAI’s Grok Imagine endpoint (POST [https://api.x.ai/v1/images/generations](https://api.x.ai/v1/images/generations)) with models such as grok-imagine-image and grok-imagine-image-2.0 comes down to two practical decisions: how the canvas is framed (aspect_ratio) and how the binary payload is delivered (response_format: "b64_json"). Getting both right prevents awkward cropping, broken UI layouts, and extra download round-trips in backend pipelines.
Endpoint and Core Request Parameters
The /v1/images/generations endpoint accepts a JSON payload with prompt as the required field and optional controls for model selection, batch count, framing, quality, resolution, and output encoding.
model: Specifies the Grok image model (such asgrok-imagine-imageorgrok-imagine-image-2.0).n: Sets how many variations to generate in a single request (1to10, defaulting to1on REST and OpenAI-compatible clients).aspect_ratio: Controls the output proportions before rendering. Defaults toauto, letting the model pick a ratio suited to the prompt.qualityandresolution: Allow tuning output fidelity (such aslow,medium, orautoquality ongrok-imagine-image-2.0, and resolution options where supported), avoiding legacysizefields used by other image APIs.response_format: Controls delivery format ("url"by default, or"b64_json"for inline base64 strings).
Note: Deferred batch requests (
deferred: true, which return arequest_idfor pollingGET /v1/images/{request_id}) only supportresponse_format: "url"(retained for 24 hours), whereas synchronous calls can returnb64_jsondirectly.
Controlling Composition with aspect_ratio
Passing aspect_ratio sets the canvas proportions up front rather than relying on post-generation cropping. When auto is used, the model infers proportions from the prompt, which is convenient for exploration but risky when an image must fit a strict UI container.
| Aspect Ratio | Common Layout & Use Case |
|---|---|
auto |
Default model-selected ratio based on prompt context |
1:1 |
Square tiles, avatars, profile cards, and grid thumbnails |
16:9 / 9:16 |
Widescreen banners and video thumbnails vs. vertical stories |
4:3 / 3:4 |
Presentation slides and classic frames vs. vertical portraits |
3:2 / 2:3 |
Photographic prints and editorial layouts |
2:1 / 1:2 |
Wide headers and panoramic strips vs. tall vertical banners |
19.5:9 / 20:9 (and inverses) |
Tall modern smartphone viewports and mobile UI frames |
21:9 / 5:2 |
Ultra-wide and panoramic layouts supported on grok-imagine-image-2.0 |
Pairing an explicit aspect_ratio with spatial cues in the prompt—such as where the focal subject sits and what margins remain around it—produces cleaner composition than trimming a generic image afterward.
Returning Inline Images with b64_json
By default, /v1/images/generations returns temporary hosted URLs under data[].url. Temporary URLs are fine for quick previews, but they require a second HTTP fetch and should not be treated as permanent storage links.
Setting "response_format": "b64_json" instructs the API to return the encoded image payload directly in data[].b64_json (alongside metadata such as mime_type):
curl --request POST "https://api.x.ai/v1/images/generations"
--header "Authorization: Bearer $XAI_API_KEY"
--header "Content-Type: application/json"
--data '{
"model": "grok-imagine-image-2.0",
"prompt": "Minimalist architectural interior with concrete walls, warm oak bench, and afternoon light",
"aspect_ratio": "16:9",
"response_format": "b64_json"
}'
Decoding and Handling b64_json Safely
- No data-URI prefix:
data[].b64_jsoncontains raw base64-encoded image bytes without adata:image/...;base64,prefix. Prepend the prefix only when constructing a browser data URL, or decode directly to raw bytes when writing to disk or object storage. - Respect
mime_type: Inspectmime_type(for example,image/png,image/jpeg, orimage/webp) or validate the decoded bytes before assigning a file extension. - Watch payload size and memory: Base64 encoding expands binary size by roughly one-third and increases JSON response weight—especially when generating multiple images (
n > 1) at higher resolutions. Stream or decode straight to object storage on the server rather than buffering large payloads unnecessarily. - Keep API keys server-side: Never call
[https://api.x.ai/v1/images/generations](https://api.x.ai/v1/images/generations)with a rawXAI_API_KEYfrom client-side browser code; route requests through a backend endpoint.
Leave a Reply