Image generation and editing examples
const response = await fetch('https://api.electronhub.ai/v1/images/generations', {
method: 'POST',
headers: {
'Authorization': 'Bearer YOUR_API_KEY',
'Content-Type': 'application/json'
},
body: JSON.stringify({
prompt: 'A beautiful sunset over a calm lake with mountains in the background',
model: 'dall-e-3',
size: '1024x1024',
quality: 'hd',
n: 1
})
});
const data = await response.json();
console.log('Generated image URL:', data.data[0].url);
async function generateMarketingImage(productName, style = 'modern') {
const stylePrompts = {
modern: 'clean, minimalist, modern design with white background',
vintage: 'vintage, retro, nostalgic style with warm colors',
luxury: 'premium, elegant, sophisticated with gold accents',
playful: 'colorful, fun, energetic with bold graphics'
};
const prompt = `Professional marketing image for ${productName}, ${stylePrompts[style]}, high quality, commercial photography style, well-lit, product showcase`;
const response = await fetch('https://api.electronhub.ai/v1/images/generations', {
method: 'POST',
headers: {
'Authorization': 'Bearer YOUR_API_KEY',
'Content-Type': 'application/json'
},
body: JSON.stringify({
prompt: prompt,
model: 'dall-e-3',
size: '1792x1024', // Landscape for marketing
quality: 'hd',
style: 'vivid'
})
});
const data = await response.json();
return {
imageUrl: data.data[0].url,
revisedPrompt: data.data[0].revised_prompt
};
}
// Usage
const marketingImage = await generateMarketingImage('wireless headphones', 'modern');
console.log('Marketing image:', marketingImage.imageUrl);
async function generateImageVariations(basePrompt, count = 4) {
const variations = [
`${basePrompt}, daylight, bright and cheerful`,
`${basePrompt}, golden hour, warm lighting`,
`${basePrompt}, minimalist style, clean composition`,
`${basePrompt}, detailed and realistic, high resolution`
];
const promises = variations.slice(0, count).map(async (prompt, index) => {
const response = await fetch('https://api.electronhub.ai/v1/images/generations', {
method: 'POST',
headers: {
'Authorization': 'Bearer YOUR_API_KEY',
'Content-Type': 'application/json'
},
body: JSON.stringify({
prompt: prompt,
model: 'dall-e-2', // Using DALL-E 2 for batch generation
size: '512x512',
n: 1
})
});
const data = await response.json();
return {
index: index + 1,
prompt: prompt,
imageUrl: data.data[0].url
};
});
try {
const results = await Promise.all(promises);
return results;
} catch (error) {
console.error('Batch generation failed:', error);
throw error;
}
}
// Usage
const variations = await generateImageVariations('a cozy coffee shop interior');
variations.forEach(variation => {
console.log(`Variation ${variation.index}: ${variation.imageUrl}`);
});
async function editImage(imageFile, editPrompt, maskFile = null) {
const formData = new FormData();
formData.append('image', imageFile);
formData.append('prompt', editPrompt);
formData.append('model', 'dall-e-2');
formData.append('size', '1024x1024');
formData.append('n', 1);
if (maskFile) {
formData.append('mask', maskFile);
}
const response = await fetch('https://api.electronhub.ai/v1/images/edits', {
method: 'POST',
headers: {
'Authorization': 'Bearer YOUR_API_KEY'
},
body: formData
});
const data = await response.json();
return data.data[0].url;
}
// Usage with file input
const fileInput = document.getElementById('image-upload');
const file = fileInput.files[0];
if (file) {
const editedImageUrl = await editImage(
file,
'Add a beautiful blue sky with fluffy white clouds'
);
console.log('Edited image:', editedImageUrl);
}
async function advancedImageEdit(originalImage, maskImage, editDescription) {
const formData = new FormData();
// Convert base64 or URL to File object if needed
if (typeof originalImage === 'string') {
const response = await fetch(originalImage);
const blob = await response.blob();
originalImage = new File([blob], 'original.png', { type: 'image/png' });
}
formData.append('image', originalImage);
formData.append('mask', maskImage);
formData.append('prompt', editDescription);
formData.append('model', 'dall-e-2');
formData.append('size', '1024x1024');
formData.append('n', 2); // Generate 2 variations
try {
const response = await fetch('https://api.electronhub.ai/v1/images/edits', {
method: 'POST',
headers: {
'Authorization': 'Bearer YOUR_API_KEY'
},
body: formData
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
return data.data.map(item => item.url);
} catch (error) {
console.error('Image editing failed:', error);
throw error;
}
}
// Usage
const editedImages = await advancedImageEdit(
originalImageFile,
maskImageFile,
'Replace the background with a tropical beach scene'
);
editedImages.forEach((url, index) => {
console.log(`Edited variation ${index + 1}: ${url}`);
});
async function createImageVariations(sourceImage, count = 3) {
const formData = new FormData();
formData.append('image', sourceImage);
formData.append('model', 'dall-e-2');
formData.append('n', count);
formData.append('size', '1024x1024');
const response = await fetch('https://api.electronhub.ai/v1/images/variations', {
method: 'POST',
headers: {
'Authorization': 'Bearer YOUR_API_KEY'
},
body: formData
});
const data = await response.json();
return data.data.map(item => item.url);
}
// Usage
const fileInput = document.getElementById('source-image');
const sourceFile = fileInput.files[0];
if (sourceFile) {
const variations = await createImageVariations(sourceFile, 4);
variations.forEach((url, index) => {
console.log(`Variation ${index + 1}: ${url}`);
// Display in UI
const img = document.createElement('img');
img.src = url;
img.style.width = '200px';
img.style.height = '200px';
img.style.objectFit = 'cover';
img.style.margin = '10px';
document.getElementById('variations-container').appendChild(img);
});
}
async function generateLogo(companyName, industry, style = 'modern') {
const industryPrompts = {
tech: 'technology, digital, innovation, circuits, geometric',
food: 'culinary, fresh, appetite, organic, kitchen',
fitness: 'strength, energy, movement, health, athletic',
finance: 'trust, stability, growth, professional, corporate',
creative: 'artistic, imaginative, colorful, expressive, design'
};
const stylePrompts = {
modern: 'clean, minimalist, simple, contemporary',
vintage: 'retro, classic, traditional, timeless',
playful: 'fun, colorful, energetic, dynamic',
elegant: 'sophisticated, premium, luxurious, refined'
};
const prompt = `Professional logo design for "${companyName}", ${industryPrompts[industry] || 'business'}, ${stylePrompts[style]}, vector style, simple, memorable, scalable, white background, high contrast`;
const response = await fetch('https://api.electronhub.ai/v1/images/generations', {
method: 'POST',
headers: {
'Authorization': 'Bearer YOUR_API_KEY',
'Content-Type': 'application/json'
},
body: JSON.stringify({
prompt: prompt,
model: 'dall-e-3',
size: '1024x1024',
quality: 'hd',
style: 'natural' // More appropriate for logos
})
});
const data = await response.json();
return {
logoUrl: data.data[0].url,
originalPrompt: prompt,
revisedPrompt: data.data[0].revised_prompt
};
}
// Usage
const logo = await generateLogo('TechFlow Solutions', 'tech', 'modern');
console.log('Generated logo:', logo.logoUrl);
async function generateArtInStyle(subject, artStyle) {
const artStyles = {
impressionist: 'impressionist painting style, like Monet, soft brushstrokes, light and color',
cubist: 'cubist art style, like Picasso, geometric shapes, abstract forms',
surreal: 'surrealist art, dreamlike, fantasy, impossible scenes',
photorealistic: 'photorealistic, highly detailed, professional photography',
watercolor: 'watercolor painting, soft colors, flowing, artistic',
oilpainting: 'oil painting, rich textures, classical art style',
cartoon: 'cartoon style, animated, colorful, fun illustration',
sketch: 'pencil sketch, black and white, artistic drawing'
};
const prompt = `${subject}, ${artStyles[artStyle] || artStyle}, masterpiece, high quality art, detailed, artistic composition`;
const response = await fetch('https://api.electronhub.ai/v1/images/generations', {
method: 'POST',
headers: {
'Authorization': 'Bearer YOUR_API_KEY',
'Content-Type': 'application/json'
},
body: JSON.stringify({
prompt: prompt,
model: 'dall-e-3',
size: '1024x1024',
quality: 'hd',
style: 'vivid'
})
});
const data = await response.json();
return data.data[0].url;
}
// Usage
const artPiece = await generateArtInStyle(
'a majestic mountain landscape with a lake',
'impressionist'
);
console.log('Art piece:', artPiece);
class ImageGenerationService {
constructor(apiKey) {
this.apiKey = apiKey;
this.baseURL = 'https://api.electronhub.ai/v1';
}
async generateImage(prompt, options = {}) {
const {
model = 'dall-e-3',
size = '1024x1024',
quality = 'standard',
style = 'vivid',
retries = 3
} = options;
for (let attempt = 1; attempt <= retries; attempt++) {
try {
const response = await fetch(`${this.baseURL}/images/generations`, {
method: 'POST',
headers: {
'Authorization': `Bearer ${this.apiKey}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({
prompt,
model,
size,
quality,
style,
n: 1
})
});
if (!response.ok) {
if (response.status === 400) {
const error = await response.json();
throw new Error(`Content policy violation: ${error.error.message}`);
}
if (response.status === 429) {
// Rate limited
const delay = Math.pow(2, attempt) * 1000;
console.log(`Rate limited, waiting ${delay}ms before retry ${attempt}`);
await new Promise(resolve => setTimeout(resolve, delay));
continue;
}
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
return {
success: true,
imageUrl: data.data[0].url,
revisedPrompt: data.data[0].revised_prompt
};
} catch (error) {
if (attempt === retries) {
return {
success: false,
error: error.message
};
}
console.warn(`Attempt ${attempt} failed:`, error.message);
}
}
}
async downloadImage(imageUrl, filename) {
try {
const response = await fetch(imageUrl);
const blob = await response.blob();
// Create download link
const url = window.URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = filename || 'generated-image.png';
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
window.URL.revokeObjectURL(url);
return true;
} catch (error) {
console.error('Download failed:', error);
return false;
}
}
validatePrompt(prompt) {
if (!prompt || prompt.trim().length === 0) {
throw new Error('Prompt cannot be empty');
}
if (prompt.length > 1000) {
throw new Error('Prompt too long (max 1000 characters)');
}
// Check for potentially problematic content
const restrictedTerms = ['violence', 'harmful', 'illegal'];
const lowerPrompt = prompt.toLowerCase();
for (const term of restrictedTerms) {
if (lowerPrompt.includes(term)) {
throw new Error(`Prompt contains restricted content: ${term}`);
}
}
return true;
}
}
// Usage
const imageService = new ImageGenerationService('YOUR_API_KEY');
try {
imageService.validatePrompt('A beautiful landscape painting');
const result = await imageService.generateImage(
'A serene Japanese garden with cherry blossoms',
{
model: 'dall-e-3',
size: '1024x1024',
quality: 'hd'
}
);
if (result.success) {
console.log('Generated image:', result.imageUrl);
console.log('Revised prompt:', result.revisedPrompt);
// Download the image
await imageService.downloadImage(result.imageUrl, 'japanese-garden.png');
} else {
console.error('Generation failed:', result.error);
}
} catch (error) {
console.error('Validation failed:', error.message);
}