Skip to Content
API ReferenceImage Cost Estimation

Image Cost Estimation

Estimate the cost of image generation before making a payment. No payment required.

Endpoint

POST /v1/images/estimate

Request

Headers

Content-Type: application/json

Body Parameters

FieldTypeRequiredDefaultDescription
modelstringNoflux-schnellModel ID to estimate for. See Available Models
widthnumberNo1024Image width in pixels (128-2048, must be divisible by 64)
heightnumberNo1024Image height in pixels (128-2048, must be divisible by 64)
numberResultsnumberNo1Number of images to generate (1-4)

Validation Rules

  • Dimensions: Both width and height must be divisible by 64
  • Range: 128 to 2048 pixels for both dimensions
  • Quantity: 1 to 4 images per request

Response

Success Response (200 OK)

{ model: string; // Model ID used for estimation dimensions: string; // Formatted dimensions (e.g., "1024×1024") number_of_images: number; // Quantity requested estimatedCost: { usd: string; // Maximum estimated cost in USD (actual may be lower) note: string; // Information about refunds }; }

Example Response

{ "model": "flux-schnell", "dimensions": "1024×1024", "number_of_images": 1, "estimatedCost": { "usd": "0.006955", "note": "Maximum upfront charge. Any difference from actual cost is automatically refunded." } }

Error Responses

Status CodeErrorDescription
400INVALID_DIMENSIONSWidth/height not divisible by 64, or outside valid range
400INVALID_MODELUnknown or unsupported model ID
500ESTIMATE_ERRORServer error during estimation

Examples

Example 1: Standard Estimation

Estimate cost for a standard 1024×1024 image.

async function estimateImageCost() { const response = await fetch('https://api.x-router.ai/v1/images/estimate', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ model: 'flux-schnell', width: 1024, height: 1024, numberResults: 1, }), }); const estimate = await response.json(); console.log(`Model: ${estimate.model}`); console.log(`Resolution: ${estimate.dimensions}`); console.log(`Number of images: ${estimate.number_of_images}`); console.log(`Estimated cost: $${estimate.estimatedCost.usd} USDC`); } estimateImageCost();

Example 2: High Resolution Estimation

Estimate cost for a high-resolution 2048×2048 image.

const response = await fetch('https://api.x-router.ai/v1/images/estimate', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ model: 'flux-schnell', width: 2048, height: 2048, numberResults: 1, }), }); const estimate = await response.json(); console.log(`High-res cost: $${estimate.estimatedCost.usd} USDC`); console.log(`Resolution: ${estimate.dimensions}`);

Example 3: Multiple Images Estimation

Estimate cost for generating 4 images at once.

const response = await fetch('https://api.x-router.ai/v1/images/estimate', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ model: 'sdxl-realvis-v4', width: 1024, height: 1024, numberResults: 4, }), }); const estimate = await response.json(); console.log(`Number of images: ${estimate.number_of_images}`); console.log(`Total cost: $${estimate.estimatedCost.usd} USDC`);

Example 4: Comparing Models

Compare costs across different models for the same parameters.

async function compareModelCosts() { const models = ['flux-schnell', 'sdxl-realvis-v4', 'sd15-dreamshaper-v8']; const width = 1024; const height = 1024; console.log(`Comparing costs for ${width}×${height}:\n`); for (const model of models) { const response = await fetch('https://api.x-router.ai/v1/images/estimate', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ model, width, height, numberResults: 1 }), }); const estimate = await response.json(); console.log(`${model}: $${estimate.estimatedCost.usd}`); } } compareModelCosts();

Example 5: Resolution Cost Comparison

Compare costs at different resolutions for the same model.

async function compareResolutions() { const model = 'flux-schnell'; const resolutions = [ { width: 512, height: 512 }, { width: 1024, height: 1024 }, { width: 2048, height: 2048 }, ]; console.log(`Comparing resolutions for ${model}:\n`); for (const { width, height } of resolutions) { const response = await fetch('https://api.x-router.ai/v1/images/estimate', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ model, width, height, numberResults: 1 }), }); const estimate = await response.json(); console.log(`${width}×${height}: $${estimate.estimatedCost.usd}`); } } compareResolutions();

Example 6: Complete Workflow with Estimation

Use estimation before actual generation.

import { wrapFetchWithPayment } from 'x402-fetch'; import { privateKeyToAccount } from 'viem/accounts'; const account = privateKeyToAccount(process.env.PRIVATE_KEY as `0x${string}`); const fetchWithPayment = wrapFetchWithPayment(fetch, account); async function generateWithEstimate() { const params = { model: 'flux-schnell', width: 1024, height: 1024, numberResults: 1, }; // Step 1: Get cost estimate console.log('Getting cost estimate...'); const estimateRes = await fetch('https://api.x-router.ai/v1/images/estimate', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(params), }); const estimate = await estimateRes.json(); console.log(`Estimated cost: $${estimate.estimatedCost.usd} USDC`); console.log(`Resolution: ${estimate.dimensions}`); // Optional: Ask user for confirmation const userConfirmed = true; // Your confirmation logic here if (!userConfirmed) { console.log('Generation cancelled by user'); return; } // Step 2: Generate with payment console.log('Generating image...'); const response = await fetchWithPayment('https://api.x-router.ai/v1/images/generate', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ ...params, prompt: 'a beautiful landscape at sunset, highly detailed', }), }); const data = await response.json(); console.log('Image generated:', data.images[0].url); console.log('Any overpayment will be automatically refunded to your wallet'); } generateWithEstimate();

Response Fields

  • model: Model ID used for the estimate
  • dimensions: Human-readable dimension string (e.g., “1024×1024”)
  • number_of_images: Number of images requested (from numberResults parameter)
  • estimatedCost.usd: Total estimated cost in USD
  • estimatedCost.note: Confirmation that this matches the payment price exactly

Use Cases

Budget Planning

Use estimates to plan generation costs for your project or application:

async function calculateBudget(dailyImages: number) { const response = await fetch('https://api.x-router.ai/v1/images/estimate', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ model: 'flux-schnell', width: 1024, height: 1024, numberResults: 1, }), }); const estimate = await response.json(); const costPerImage = parseFloat(estimate.estimatedCost.usd); const dailyCost = costPerImage * dailyImages; const monthlyCost = dailyCost * 30; console.log(`Cost per image: $${costPerImage.toFixed(4)}`); console.log(`Daily cost (${dailyImages} images): $${dailyCost.toFixed(2)}`); console.log(`Monthly estimate: $${monthlyCost.toFixed(2)}`); } calculateBudget(100); // Estimate for 100 images per day

Model Selection by Cost

Choose the most cost-effective model for your quality requirements:

async function findBestValueModel() { const models = [ 'flux-schnell', 'sdxl-realvis-v4', 'sd15-dreamshaper-v8', 'flux-dev', ]; const estimates = await Promise.all( models.map(async (model) => { const response = await fetch('https://api.x-router.ai/v1/images/estimate', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ model, width: 1024, height: 1024, numberResults: 1, }), }); const data = await response.json(); return { model, cost: parseFloat(data.estimatedCost.usd), }; }) ); estimates.sort((a, b) => a.cost - b.cost); console.log('Models ranked by cost (1024×1024):'); estimates.forEach((e, idx) => { console.log(`${idx + 1}. ${e.model}: $${e.cost.toFixed(4)}`); }); } findBestValueModel();

Important Notes

  • Maximum Cost: The estimate represents the maximum amount you’ll be charged upfront
  • Automatic Refunds: After generation completes, any difference between the estimate and actual cost is automatically refunded to your wallet
  • No Action Needed: Refunds are processed automatically - you don’t need to do anything
  • No Payment Required: Estimation is free and does not require x402 payment
  • Fast Response: Returns immediately without performing image generation
  • Same Validation: Uses the same validation rules as the generation endpoint
  • Batch Calculations: Automatically calculates total cost for multiple images

Best Practices

  1. Always estimate before large batches: Check costs before generating many images
  2. Compare models: Use estimates to find the best value for your needs
  3. Test different resolutions: Balance quality needs with budget constraints
  4. Cache estimates: Estimates are deterministic for the same parameters
  5. Show users: Display estimated costs in your UI before generation
Last updated on