> ## Documentation Index
> Fetch the complete documentation index at: https://docs.core-ai.dev/llms.txt
> Use this file to discover all available pages before exploring further.

# Image Generation

> Generate images using generateImage() with AI image models

Generate images from text prompts using the `generateImage()` function with support for various AI image models.

## Basic Usage

Generate an image from a text prompt:

```typescript theme={null}
import { generateImage } from '@core-ai/core-ai';
import { createOpenAI } from '@core-ai/openai';

const openai = createOpenAI({ apiKey: process.env.OPENAI_API_KEY });
const model = openai.imageModel('gpt-image-1');

const result = await generateImage({
  model,
  prompt: 'A watercolor painting of a robot coding in a quiet mountain cabin at sunrise',
  n: 1,
  size: '1024x1024',
});

for (const [index, image] of result.images.entries()) {
  console.log(`Image ${index + 1}:`);
  if (image.url) {
    console.log('URL:', image.url);
  } else if (image.base64) {
    console.log('Base64 preview:', image.base64.slice(0, 80), '...');
  } else {
    console.log('No image payload found.');
  }
  if (image.revisedPrompt) {
    console.log('Revised prompt:', image.revisedPrompt);
  }
}
```

## Configuration Options

Customize image generation:

```typescript theme={null}
const result = await generateImage({
  model,
  prompt: 'A futuristic cityscape at sunset',
  n: 3,                    // Generate 3 images
  size: '1024x1024',       // Image dimensions
});
```

<Note>
  Available sizes depend on the provider and model. Common sizes include:

  * `256x256`
  * `512x512`
  * `1024x1024`
  * `1792x1024` (landscape)
  * `1024x1792` (portrait)
</Note>

## Image Response Format

The `generateImage()` function returns:

```typescript theme={null}
type ImageGenerateResult = {
  images: GeneratedImage[];
};

type GeneratedImage = {
  base64?: string;        // Base64-encoded image data
  url?: string;           // URL to the generated image
  revisedPrompt?: string; // AI-revised prompt (if modified)
};
```

## Multiple Images

Generate multiple variations:

```typescript theme={null}
const result = await generateImage({
  model,
  prompt: 'A minimalist logo for a tech startup',
  n: 4, // Generate 4 variations
  size: '512x512',
});

console.log(`Generated ${result.images.length} images`);

result.images.forEach((image, index) => {
  console.log(`\nImage ${index + 1}:`);
  if (image.url) {
    console.log('URL:', image.url);
  }
});
```

## Handling Image Data

<Tabs>
  <Tab title="Save to File">
    ```typescript theme={null}
    import { writeFile } from 'fs/promises';
    import { generateImage } from '@core-ai/core-ai';

    const result = await generateImage({
      model,
      prompt: 'A beautiful landscape',
    });

    const image = result.images[0];

    if (image.base64) {
      // Save base64 data
      const buffer = Buffer.from(image.base64, 'base64');
      await writeFile('generated-image.png', buffer);
      console.log('Saved image to generated-image.png');
    } else if (image.url) {
      // Download from URL
      const response = await fetch(image.url);
      const buffer = await response.arrayBuffer();
      await writeFile('generated-image.png', Buffer.from(buffer));
      console.log('Downloaded and saved image');
    }
    ```
  </Tab>

  <Tab title="Display in Browser">
    ```typescript theme={null}
    import { generateImage } from '@core-ai/core-ai';

    async function displayImage() {
      const result = await generateImage({
        model,
        prompt: 'A modern office space',
      });

      const image = result.images[0];

      if (image.url) {
        // Display URL directly
        document.getElementById('output').innerHTML = 
          `<img src="${image.url}" alt="Generated image" />`;
      } else if (image.base64) {
        // Display base64 as data URL
        const dataUrl = `data:image/png;base64,${image.base64}`;
        document.getElementById('output').innerHTML = 
          `<img src="${dataUrl}" alt="Generated image" />`;
      }
    }
    ```
  </Tab>

  <Tab title="Upload to Storage">
    ```typescript theme={null}
    import { generateImage } from '@core-ai/core-ai';
    import { S3Client, PutObjectCommand } from '@aws-sdk/client-s3';

    const s3 = new S3Client({ region: 'us-east-1' });

    const result = await generateImage({
      model,
      prompt: 'A product photo',
    });

    const image = result.images[0];
    let buffer: Buffer;

    if (image.base64) {
      buffer = Buffer.from(image.base64, 'base64');
    } else if (image.url) {
      const response = await fetch(image.url);
      buffer = Buffer.from(await response.arrayBuffer());
    } else {
      throw new Error('No image data');
    }

    await s3.send(
      new PutObjectCommand({
        Bucket: 'my-bucket',
        Key: 'generated-image.png',
        Body: buffer,
        ContentType: 'image/png',
      })
    );

    console.log('Uploaded to S3');
    ```
  </Tab>
</Tabs>

## Revised Prompts

Some providers modify your prompt for better results:

```typescript theme={null}
const result = await generateImage({
  model,
  prompt: 'a robot',
});

const image = result.images[0];

if (image.revisedPrompt) {
  console.log('Original prompt:', 'a robot');
  console.log('Revised prompt:', image.revisedPrompt);
  // Revised prompt: "A humanoid robot with sleek metallic surfaces..."
}
```

## Image Sizes

Different models support different sizes:

<Tabs>
  <Tab title="Square">
    ```typescript theme={null}
    const result = await generateImage({
      model,
      prompt: 'A centered logo design',
      size: '1024x1024', // Square format
    });
    ```
  </Tab>

  <Tab title="Landscape">
    ```typescript theme={null}
    const result = await generateImage({
      model,
      prompt: 'A wide panoramic landscape',
      size: '1792x1024', // Landscape format
    });
    ```
  </Tab>

  <Tab title="Portrait">
    ```typescript theme={null}
    const result = await generateImage({
      model,
      prompt: 'A tall building from ground level',
      size: '1024x1792', // Portrait format
    });
    ```
  </Tab>
</Tabs>

## Prompt Engineering Tips

Write effective prompts for better results:

<AccordionGroup>
  <Accordion title="Be specific and descriptive">
    ```typescript theme={null}
    // Vague
    const result = await generateImage({
      model,
      prompt: 'a dog',
    });

    // Better
    const result = await generateImage({
      model,
      prompt: 'a golden retriever puppy sitting on grass in a sunny park, ' +
              'photorealistic, 8k, natural lighting',
    });
    ```
  </Accordion>

  <Accordion title="Include style and quality keywords">
    ```typescript theme={null}
    const result = await generateImage({
      model,
      prompt: 'a mountain landscape at sunset, ' +
              'oil painting style, impressionist, ' +
              'vibrant colors, detailed brushstrokes',
    });
    ```
  </Accordion>

  <Accordion title="Specify composition and perspective">
    ```typescript theme={null}
    const result = await generateImage({
      model,
      prompt: 'a modern kitchen, ' +
              'wide angle shot, ' +
              'centered composition, ' +
              'eye-level perspective, ' +
              'well-lit interior',
    });
    ```
  </Accordion>

  <Accordion title="Add technical details for realism">
    ```typescript theme={null}
    const result = await generateImage({
      model,
      prompt: 'portrait of a woman, ' +
              'Canon EOS R5, 85mm f/1.4, ' +
              'shallow depth of field, ' +
              'natural window lighting, ' +
              'bokeh background',
    });
    ```
  </Accordion>
</AccordionGroup>

## Error Handling

Handle image generation errors:

```typescript theme={null}
import { CoreAIError, ProviderError } from '@core-ai/core-ai';

try {
  const result = await generateImage({
    model,
    prompt: 'A beautiful landscape',
  });

  if (result.images.length === 0) {
    console.error('No images generated');
  }

  result.images.forEach((image, i) => {
    if (!image.url && !image.base64) {
      console.error(`Image ${i} has no data`);
    }
  });
} catch (error) {
  if (error instanceof ProviderError) {
    console.error('Provider error:', error.message);
    console.error('Status code:', error.statusCode);
  } else if (error instanceof CoreAIError) {
    console.error('CoreAIError:', error.message);
  } else {
    console.error('Unknown error:', error);
  }
}
```

## Provider-Specific Options

Use provider-specific features:

```typescript theme={null}
const result = await generateImage({
  model,
  prompt: 'A futuristic vehicle',
  n: 2,
  size: '1024x1024',
  providerOptions: {
    openai: {
      quality: 'hd',
      style: 'vivid',
    },
  },
});
```

<Note>
  Provider options are namespaced by provider name and validated by each provider adapter. Check the [provider docs](/api/providers/openai) for available options.
</Note>

## Practical Examples

<Tabs>
  <Tab title="Logo Generator">
    ```typescript theme={null}
    async function generateLogo(companyName: string, industry: string) {
      const result = await generateImage({
        model,
        prompt: `A modern, minimalist logo for "${companyName}", ` +
                `a ${industry} company, ` +
                `clean design, professional, vector style, ` +
                `white background, high contrast`,
        n: 3,
        size: '512x512',
      });

      return result.images;
    }

    const logos = await generateLogo('TechFlow', 'software development');
    console.log(`Generated ${logos.length} logo options`);
    ```
  </Tab>

  <Tab title="Product Mockup">
    ```typescript theme={null}
    async function generateProductMockup(
      product: string,
      style: string = 'photorealistic'
    ) {
      const result = await generateImage({
        model,
        prompt: `${product}, product photography, ` +
                `${style}, studio lighting, ` +
                `clean white background, 4k, commercial quality`,
        size: '1024x1024',
      });

      return result.images[0];
    }

    const mockup = await generateProductMockup(
      'a sleek wireless headphone',
      'premium and elegant'
    );
    ```
  </Tab>

  <Tab title="Illustration Generator">
    ```typescript theme={null}
    async function generateIllustration(
      scene: string,
      artStyle: string = 'digital art'
    ) {
      const result = await generateImage({
        model,
        prompt: `${scene}, ${artStyle}, ` +
                `highly detailed, vibrant colors, ` +
                `professional illustration, ` +
                `trending on artstation`,
        size: '1792x1024',
      });

      return result.images[0];
    }

    const illustration = await generateIllustration(
      'a fantasy castle on a floating island',
      'concept art'
    );
    ```
  </Tab>
</Tabs>

## Best Practices

<AccordionGroup>
  <Accordion title="Handle both URL and base64 responses">
    Different providers return different formats:

    ```typescript theme={null}
    const image = result.images[0];

    let imageData: string;
    if (image.url) {
      imageData = image.url;
    } else if (image.base64) {
      imageData = `data:image/png;base64,${image.base64}`;
    } else {
      throw new Error('No image data available');
    }
    ```
  </Accordion>

  <Accordion title="Store generated images permanently">
    URLs may expire - save images you need:

    ```typescript theme={null}
    if (image.url) {
      // URL might expire, download and store
      const response = await fetch(image.url);
      const buffer = await response.arrayBuffer();
      await saveToStorage(buffer);
    }
    ```
  </Accordion>

  <Accordion title="Use appropriate sizes for your use case">
    Smaller sizes are faster and cheaper:

    ```typescript theme={null}
    // Thumbnail: use smaller size
    const thumbnail = await generateImage({
      model,
      prompt: 'icon design',
      size: '256x256',
    });

    // High quality print: use larger size
    const print = await generateImage({
      model,
      prompt: 'artwork',
      size: '1024x1024',
    });
    ```
  </Accordion>
</AccordionGroup>

## Next Steps

<CardGroup cols={2}>
  <Card title="Multi-Modal" icon="images" href="/guides/multi-modal">
    Use images in chat conversations
  </Card>

  <Card title="Chat Completion" icon="message" href="/guides/chat-completion">
    Generate text responses
  </Card>

  <Card title="Tool Calling" icon="wrench" href="/guides/tool-calling">
    Combine image generation with tools
  </Card>

  <Card title="Embeddings" icon="vector-square" href="/guides/embeddings">
    Generate vector embeddings
  </Card>
</CardGroup>
