Integrate DALL-E image generation into an application.
Code Playground
JavaScript (V8)
Loading...
Console Output
// Output will appear here...
// For React: ReactDOM.createRoot(rootElement).render(<App />);
// For React: ReactDOM.createRoot(rootElement).render(<App />);
Recommended Answer
Implementation:
import OpenAI from 'openai';
import fs from 'fs';
import https from 'https';
const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });
async function generateImage(prompt, options = {}) {
const response = await openai.images.generate({
model: options.model || "dall-e-3",
prompt,
n: options.n || 1,
size: options.size || "1024x1024",
quality: options.quality || "standard", // or "hd"
style: options.style || "vivid" // or "natural"
});
return response.data[0].url;
}
async function downloadImage(url, filepath) {
return new Promise((resolve, reject) => {
const file = fs.createWriteStream(filepath);
https.get(url, (response) => {
response.pipe(file);
file.on('finish', () => {
file.close();
resolve(filepath);
});
}).on('error', (err) => {
fs.unlink(filepath, () => reject(err));
});
});
}
async function generateAndSave(prompt, filename) {
console.log('Generating image...');
const imageUrl = await generateImage(prompt);
console.log('Downloading image...');
await downloadImage(imageUrl, filename);
console.log(`Image saved to ${filename}`);
return filename;
}
// Usage
await generateAndSave(
"A serene mountain landscape at sunset, digital art style",
"mountain.png"
);
// With options
await generateAndSave(
"A futuristic city with flying cars",
"city.png",
{ quality: "hd", size: "1792x1024" }
);