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:
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:
const result = await generateImage ({
model ,
prompt: 'A futuristic cityscape at sunset' ,
n: 3 , // Generate 3 images
size: '1024x1024' , // Image dimensions
});
Available sizes depend on the provider and model. Common sizes include:
256x256
512x512
1024x1024
1792x1024 (landscape)
1024x1792 (portrait)
The generateImage() function returns:
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:
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 ( ` \n Image ${ index + 1 } :` );
if ( image . url ) {
console . log ( 'URL:' , image . url );
}
});
Handling Image Data
Save to File
Display in Browser
Upload to Storage
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' );
}
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" />` ;
}
}
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' );
Revised Prompts
Some providers modify your prompt for better results:
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:
Square
Landscape
Portrait
const result = await generateImage ({
model ,
prompt: 'A centered logo design' ,
size: '1024x1024' , // Square format
});
const result = await generateImage ({
model ,
prompt: 'A wide panoramic landscape' ,
size: '1792x1024' , // Landscape format
});
const result = await generateImage ({
model ,
prompt: 'A tall building from ground level' ,
size: '1024x1792' , // Portrait format
});
Prompt Engineering Tips
Write effective prompts for better results:
Be specific and descriptive
// 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' ,
});
Include style and quality keywords
const result = await generateImage ({
model ,
prompt: 'a mountain landscape at sunset, ' +
'oil painting style, impressionist, ' +
'vibrant colors, detailed brushstrokes' ,
});
Specify composition and perspective
const result = await generateImage ({
model ,
prompt: 'a modern kitchen, ' +
'wide angle shot, ' +
'centered composition, ' +
'eye-level perspective, ' +
'well-lit interior' ,
});
Add technical details for realism
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' ,
});
Error Handling
Handle image generation errors:
import { LLMError , 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 LLMError ) {
console . error ( 'LLM error:' , error . message );
} else {
console . error ( 'Unknown error:' , error );
}
}
Provider-Specific Options
Use provider-specific features:
const result = await generateImage ({
model ,
prompt: 'A futuristic vehicle' ,
n: 2 ,
size: '1024x1024' ,
providerOptions: {
// Provider-specific options
quality: 'hd' ,
style: 'vivid' ,
},
});
Provider-specific options vary by provider. Check your provider’s documentation for available options.
Practical Examples
Logo Generator
Product Mockup
Illustration Generator
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` );
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'
);
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'
);
Best Practices
Handle both URL and base64 responses
Different providers return different formats: 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' );
}
Store generated images permanently
URLs may expire - save images you need: if ( image . url ) {
// URL might expire, download and store
const response = await fetch ( image . url );
const buffer = await response . arrayBuffer ();
await saveToStorage ( buffer );
}
Use appropriate sizes for your use case
Smaller sizes are faster and cheaper: // 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' ,
});
Next Steps