Harnessing xAI’s Grok Imagine API: A Developer’s Guide to Aspect Ratios and Base64 Output
Building AI-powered creative pipelines requires robust control over image dimensions, payload formats, and generation settings. xAI’s Grok Imagine image generation suite (grok-imagine-image) provides developers with a streamlined, OpenAI-compatible endpoint to integrate state-of-the-art visual generation directly into applications.
This article explores how to configure image generation requests using precise aspect ratios and handling responses via b64_json for direct data embedding.
Core Concepts of the Grok Imagine Endpoint
When working with xAI’s image capabilities through site:docs.x.ai, developers interact primarily with the image generations endpoint. Instead of dealing with erratic sizing constraints, the API exposes structured parameters to dictate how your final visual asset looks and arrives.
Two parameters stand out when fine-tuning your integration workflow:
aspect_ratio: Controls the geometric layout of the generated image.response_format: Determines whether the API returns a temporary hosted URL or direct base64-encoded JSON data (b64_json).
Controlling Layout with aspect_ratio
By default, image generation can rely on an auto setting, allowing the model to interpret the prompt and select an optimal orientation. However, production environments often demand rigid layout adherence—such as a 1:1 square for social media profiles or a 16:9 widescreen layout for banners.
The grok-imagine-image-2.0 model supports a wide array of precise aspect ratios divided into standard categories:
- Square:
1:1 - Landscape:
16:9,4:3,3:2,2:1,19.5:9,20:9,21:9,5:2 - Portrait:
9:16,3:4,2:3,1:2,9:19.5,9:20
Example Request Body (JSON)
{
"model": "x-ai/grok-imagine-image",
"prompt": "A cyberpunk street market glowing with neon signs in the rain",
"aspect_ratio": "16:9",
"resolution": "2k",
"response_format": "b64_json"
}
Handling Payload Delivery with b64_json
By default, image endpoints return a temporary public URL (url) pointing to the generated asset. While convenient for rapid prototyping, these URLs expire, requiring external downloading logic if you intend to preserve the asset.
Setting response_format to b64_json bypasses temporary hosting entirely. The API response delivers the image as a raw base64-encoded string inside the payload body (without a data-URI prefix).
Benefits of b64_json:
- Immediate Persistence: Pass the string directly into database BLOB fields or write it straight to disk as a binary file without making an secondary HTTP GET request.
- Network Independence: Eliminates broken asset links caused by expired temporary cloud storage URLs.
- Serverless Friendly: Ideal for serverless functions that need to process, water-mark, or pipe the image bytes onward immediately.
Implementation Blueprint (Python)
Here is how you can tie these parameters together using a standard API payload request to generate and catch a base64 string:
import os
import base64
import requests
api_key = os.getenv("XAI_API_KEY")
url = "https://api.x.ai/v1/images/generations"
headers = {
"Authorization": f"Bearer {api_key}",
"Content-Type": "application/json"
}
payload = {
"model": "x-ai/grok-imagine-image",
"prompt": "Minimalist architecture of a concrete museum facing the ocean",
"aspect_ratio": "4:3",
"resolution": "2k",
"response_format": "b64_json",
"n": 1
}
response = requests.post(url, json=payload, headers=headers)
data = response.json()
# Decode and save the b64_json output
if "data" in data and len(data["data"]) > 0:
img_b64 = data["data"][0]["b64_json"]
img_bytes = base64.b64decode(img_b64)
with open("museum_output.jpg", "wb") as f:
f.write(img_bytes)
print("Image successfully saved from b64_json payload!")
else:
print("Generation failed:", data)
Summary Table
| Parameter | Key Options | Recommended Use Case |
| :— | :— | :— |
| aspect_ratio | 1:1, 16:9, 9:16, 21:9, etc. | Enforce precise dimensions layout matching UI containers (
Leave a Reply