Systems Library / AI Capabilities / How to Build a Batch Image Generation System
AI Capabilities image generation

How to Build a Batch Image Generation System

Generate hundreds of image variations from templates using AI batch processing.

Jay Banlasan

Jay Banlasan

The AI Systems Guy

A batch ai image generation automation system produces dozens of image variations from a single approved concept. I build these after a client approves one creative direction. Instead of generating one at a time, the system takes the base prompt, applies a variation matrix, and outputs every combination in parallel.

One approval turns into 20 ready-to-test ad variations.

What You Need Before Starting

Step 1: Define the Variation Matrix

VARIATION_MATRIX = {
    "background": ["white studio", "dark gradient", "blue gradient", "natural wood"],
    "layout": ["centered", "left-aligned", "right-aligned"],
    "accent_color": ["#1E40AF", "#DC2626", "#059669"],
}

def generate_combinations(matrix):
    from itertools import product
    keys = list(matrix.keys())
    values = list(matrix.values())
    combos = list(product(*values))
    return [dict(zip(keys, combo)) for combo in combos]

# This creates 4 x 3 x 3 = 36 combinations
all_variations = generate_combinations(VARIATION_MATRIX)

Step 2: Build the Batch Processor

import asyncio
import aiohttp
from openai import AsyncOpenAI

client = AsyncOpenAI()

async def generate_single(base_prompt, variation, semaphore):
    async with semaphore:
        variation_desc = ", ".join([f"{k}: {v}" for k, v in variation.items()])
        full_prompt = f"{base_prompt}\n\nVariation: {variation_desc}"

        response = await client.images.generate(
            model="gpt-image-1",
            prompt=full_prompt,
            size="1024x1024",
            quality="high"
        )
        return {"variation": variation, "url": response.data[0].url}

async def batch_generate(base_prompt, variations, max_concurrent=5):
    semaphore = asyncio.Semaphore(max_concurrent)
    tasks = [generate_single(base_prompt, var, semaphore) for var in variations]
    results = await asyncio.gather(*tasks, return_exceptions=True)

    successes = [r for r in results if isinstance(r, dict)]
    failures = [r for r in results if isinstance(r, Exception)]

    return {"success": successes, "failed": len(failures), "total": len(variations)}

Step 3: Add Cost Tracking

COST_PER_IMAGE = {
    "gpt-image-1": 0.08,
    "flux-pro": 0.03,
    "ideogram": 0.05,
}

def estimate_batch_cost(variation_count, model="gpt-image-1"):
    cost = variation_count * COST_PER_IMAGE.get(model, 0.10)
    return {"total_images": variation_count, "cost_per_image": COST_PER_IMAGE[model], "total_cost": round(cost, 2)}

def confirm_batch(variation_count, model):
    estimate = estimate_batch_cost(variation_count, model)
    print(f"Batch will generate {estimate['total_images']} images at ${estimate['cost_per_image']}/each")
    print(f"Total estimated cost: ${estimate['total_cost']}")
    return estimate

Step 4: Save and Organize Outputs

import requests
import os

def save_batch_results(results, output_folder, naming_prefix):
    os.makedirs(output_folder, exist_ok=True)
    saved = []

    for i, result in enumerate(results["success"]):
        variation = result["variation"]
        name_parts = [naming_prefix] + [str(v).replace(" ", "_")[:10] for v in variation.values()]
        filename = f"{'_'.join(name_parts)}_{i:03d}.png"
        filepath = os.path.join(output_folder, filename)

        resp = requests.get(result["url"])
        with open(filepath, "wb") as f:
            f.write(resp.content)
        saved.append(filepath)

    return saved

Step 5: Generate Report

def batch_report(results, cost_estimate, output_folder):
    report = {
        "total_requested": results["total"],
        "successful": len(results["success"]),
        "failed": results["failed"],
        "estimated_cost": cost_estimate["total_cost"],
        "output_folder": output_folder,
        "variations_generated": [r["variation"] for r in results["success"]]
    }
    return report

What to Build Next

Add quality filtering. After batch generation, run each image through a quality check that scores composition, text readability, and brand compliance. Auto-reject anything below your quality threshold before it reaches the approval step.

Related Reading

Want this system built for your business?

Get a free assessment. We will map every system your business needs and show you the ROI.

Get Your Free Assessment

Related Systems