Generate stunning images from text descriptions using AI image models
import requests
import base64
from PIL import Image
import io
def generate_image(prompt, model="dall-e-3", size="1024x1024"):
"""Generate an image from a text prompt"""
response = requests.post(
"https://api.anyapi.ai/v1/images/generations",
headers={
"Authorization": "Bearer YOUR_API_KEY",
"Content-Type": "application/json"
},
json={
"model": model,
"prompt": prompt,
"size": size,
"quality": "hd",
"n": 1
}
)
result = response.json()
image_url = result["data"][0]["url"]
# Download and save the image
image_response = requests.get(image_url)
image = Image.open(io.BytesIO(image_response.content))
return image, image_url
# Usage examples
image, url = generate_image(
"A serene mountain landscape at sunset with a crystal clear lake reflecting the mountains and sky"
)
# Save the image
image.save("mountain_landscape.png")
print(f"Image generated and saved! URL: {url}")
# Generate with different model
image2, url2 = generate_image(
"A futuristic cityscape with flying cars and neon lights",
model="flux-pro",
size="1792x1024"
)
image2.save("futuristic_city.png")
class ImagePromptGenerator:
def __init__(self, api_key):
self.api_key = api_key
def enhance_prompt(self, basic_prompt):
"""Enhance a basic prompt with detailed descriptions"""
enhancement_request = f"""
Enhance this basic image prompt with rich, detailed descriptions:
"{basic_prompt}"
Add details about:
- Visual style and artistic technique
- Lighting and atmosphere
- Colors and composition
- Camera angle and perspective
- Mood and emotion
- Technical photography details
Create a detailed prompt that will generate a stunning image.
Keep it under 400 characters for optimal results.
"""
response = requests.post(
"https://api.anyapi.ai/v1/chat/completions",
headers={
"Authorization": f"Bearer {self.api_key}",
"Content-Type": "application/json"
},
json={
"model": "gpt-4o-mini",
"messages": [
{
"role": "system",
"content": "You are an expert at writing image generation prompts. Create detailed, visual descriptions that will produce amazing images."
},
{"role": "user", "content": enhancement_request}
],
"temperature": 0.8
}
)
return response.json()["choices"][0]["message"]["content"]
def generate_with_enhanced_prompt(self, basic_prompt, model="dall-e-3"):
"""Generate image with AI-enhanced prompt"""
enhanced_prompt = self.enhance_prompt(basic_prompt)
print(f"Enhanced prompt: {enhanced_prompt}")
response = requests.post(
"https://api.anyapi.ai/v1/images/generations",
headers={
"Authorization": f"Bearer {self.api_key}",
"Content-Type": "application/json"
},
json={
"model": model,
"prompt": enhanced_prompt,
"size": "1024x1024",
"quality": "hd"
}
)
result = response.json()
return result["data"][0]["url"], enhanced_prompt
# Usage
prompt_generator = ImagePromptGenerator("YOUR_API_KEY")
# Basic prompt
basic_prompt = "a cat wearing a hat"
# Generate with enhancement
image_url, enhanced = prompt_generator.generate_with_enhanced_prompt(basic_prompt)
print(f"Generated image: {image_url}")
print(f"Enhanced prompt: {enhanced}")
class ArtisticImageGenerator:
def __init__(self, api_key):
self.api_key = api_key
self.art_styles = {
"impressionist": "in the style of Claude Monet, impressionist brushstrokes, soft colors, outdoor lighting",
"surreal": "surrealist art style, dreamlike, impossible geometry, Salvador Dali inspired",
"cyberpunk": "cyberpunk aesthetic, neon colors, dystopian future, high-tech low-life",
"watercolor": "watercolor painting, soft edges, transparent colors, artistic brushstrokes",
"oil_painting": "classical oil painting, rich textures, realistic details, museum quality",
"anime": "anime art style, vibrant colors, expressive characters, Japanese animation",
"pixel_art": "8-bit pixel art style, retro gaming aesthetic, limited color palette",
"photorealistic": "photorealistic, high detail, professional photography, crisp focus",
"minimalist": "minimalist design, clean lines, simple composition, negative space",
"vintage": "vintage photography, aged colors, film grain, nostalgic mood"
}
self.camera_angles = {
"portrait": "portrait orientation, close-up shot",
"landscape": "landscape orientation, wide shot",
"aerial": "aerial view, bird's eye perspective, drone photography",
"macro": "macro photography, extreme close-up, detailed textures",
"wide_angle": "wide-angle lens, expansive view, dramatic perspective",
"telephoto": "telephoto lens, compressed perspective, shallow depth of field"
}
def generate_artistic_image(self, subject, style_key, camera_key=None, additional_details=""):
"""Generate image with specific artistic style"""
style = self.art_styles.get(style_key, "")
camera = self.camera_angles.get(camera_key, "") if camera_key else ""
prompt = f"{subject}, {style}"
if camera:
prompt += f", {camera}"
if additional_details:
prompt += f", {additional_details}"
response = requests.post(
"https://api.anyapi.ai/v1/images/generations",
headers={
"Authorization": f"Bearer {self.api_key}",
"Content-Type": "application/json"
},
json={
"model": "dall-e-3",
"prompt": prompt,
"size": "1024x1024",
"quality": "hd"
}
)
result = response.json()
return result["data"][0]["url"], prompt
def create_style_variations(self, subject, styles_list):
"""Create multiple style variations of the same subject"""
variations = []
for style in styles_list:
try:
image_url, full_prompt = self.generate_artistic_image(subject, style)
variations.append({
"style": style,
"url": image_url,
"prompt": full_prompt
})
print(f"Generated {style} version: {image_url}")
except Exception as e:
print(f"Failed to generate {style} version: {e}")
return variations
# Usage
art_generator = ArtisticImageGenerator("YOUR_API_KEY")
# Generate single artistic image
subject = "a majestic eagle soaring over snow-capped mountains"
image_url, prompt = art_generator.generate_artistic_image(
subject,
"impressionist",
"landscape",
"golden hour lighting, dramatic clouds"
)
print(f"Impressionist eagle: {image_url}")
# Generate style variations
styles = ["photorealistic", "watercolor", "cyberpunk", "anime", "oil_painting"]
variations = art_generator.create_style_variations(
"a wise old wizard reading a glowing book",
styles
)
for var in variations:
print(f"{var['style']}: {var['url']}")
class MarketingImageGenerator:
def __init__(self, api_key):
self.api_key = api_key
def generate_product_mockup(self, product_description, setting="modern studio"):
"""Generate product mockup images"""
mockup_prompts = {
"modern_studio": "professional product photography, clean white background, studio lighting, high-end commercial style",
"lifestyle": "lifestyle photography, natural setting, people using the product, authentic atmosphere",
"minimalist": "minimalist product shot, simple background, clean aesthetic, negative space",
"luxury": "luxury product photography, elegant setting, premium materials, sophisticated lighting"
}
style = mockup_prompts.get(setting, mockup_prompts["modern_studio"])
prompt = f"{product_description}, {style}, product photography, high resolution, commercial quality"
response = requests.post(
"https://api.anyapi.ai/v1/images/generations",
headers={
"Authorization": f"Bearer {self.api_key}",
"Content-Type": "application/json"
},
json={
"model": "dall-e-3",
"prompt": prompt,
"size": "1024x1024",
"quality": "hd"
}
)
result = response.json()
return result["data"][0]["url"]
def generate_social_media_content(self, theme, platform="instagram"):
"""Generate social media optimized images"""
platform_specs = {
"instagram": {
"size": "1024x1024",
"style": "Instagram-ready, vibrant colors, eye-catching composition, social media optimized"
},
"facebook": {
"size": "1200x630",
"style": "Facebook cover style, wide composition, engaging visual"
},
"twitter": {
"size": "1200x675",
"style": "Twitter header style, clean design, professional look"
},
"linkedin": {
"size": "1128x640",
"style": "LinkedIn professional style, business appropriate, sophisticated"
}
}
spec = platform_specs.get(platform, platform_specs["instagram"])
prompt = f"{theme}, {spec['style']}, high quality, social media ready"
response = requests.post(
"https://api.anyapi.ai/v1/images/generations",
headers={
"Authorization": f"Bearer {self.api_key}",
"Content-Type": "application/json"
},
json={
"model": "dall-e-3",
"prompt": prompt,
"size": spec["size"],
"quality": "hd"
}
)
result = response.json()
return result["data"][0]["url"]
def generate_marketing_campaign(self, campaign_theme, variations=3):
"""Generate a complete marketing campaign with multiple image variations"""
campaign_angles = [
"hero shot, dramatic lighting, premium feel",
"lifestyle approach, people enjoying the product/service, authentic",
"close-up detail shot, texture and quality focus",
"wide environmental shot, context and scale",
"creative artistic interpretation, abstract elements"
]
campaign_images = []
for i in range(variations):
angle = campaign_angles[i % len(campaign_angles)]
prompt = f"{campaign_theme}, {angle}, marketing photography, professional quality, brand-focused"
response = requests.post(
"https://api.anyapi.ai/v1/images/generations",
headers={
"Authorization": f"Bearer {self.api_key}",
"Content-Type": "application/json"
},
json={
"model": "dall-e-3",
"prompt": prompt,
"size": "1024x1024",
"quality": "hd"
}
)
result = response.json()
campaign_images.append({
"angle": angle,
"url": result["data"][0]["url"],
"prompt": prompt
})
return campaign_images
# Usage
marketing_gen = MarketingImageGenerator("YOUR_API_KEY")
# Product mockup
product_url = marketing_gen.generate_product_mockup(
"sleek wireless headphones with noise cancellation",
"luxury"
)
print(f"Product mockup: {product_url}")
# Social media content
social_url = marketing_gen.generate_social_media_content(
"celebrating innovation in technology",
"instagram"
)
print(f"Social media image: {social_url}")
# Marketing campaign
campaign = marketing_gen.generate_marketing_campaign(
"eco-friendly sustainable fashion brand launch",
3
)
for img in campaign:
print(f"{img['angle']}: {img['url']}")
class CreativeWorkflow:
def __init__(self, api_key):
self.api_key = api_key
self.project_history = []
def brainstorm_concepts(self, project_brief):
"""Generate multiple creative concepts for a project"""
brainstorm_prompt = f"""
Given this creative brief: "{project_brief}"
Generate 5 diverse creative concepts with:
1. A catchy concept name
2. Visual description for image generation
3. Target mood/emotion
4. Color palette suggestion
5. Key visual elements
Make each concept unique and creative.
"""
response = requests.post(
"https://api.anyapi.ai/v1/chat/completions",
headers={
"Authorization": f"Bearer {self.api_key}",
"Content-Type": "application/json"
},
json={
"model": "gpt-4o",
"messages": [
{
"role": "system",
"content": "You are a creative director generating innovative visual concepts."
},
{"role": "user", "content": brainstorm_prompt}
],
"temperature": 0.8
}
)
return response.json()["choices"][0]["message"]["content"]
def concept_to_image(self, concept_description):
"""Convert a concept description to an actual image"""
# Extract visual elements for prompt
image_prompt = f"{concept_description}, high quality, creative design, professional artwork"
response = requests.post(
"https://api.anyapi.ai/v1/images/generations",
headers={
"Authorization": f"Bearer {self.api_key}",
"Content-Type": "application/json"
},
json={
"model": "dall-e-3",
"prompt": image_prompt,
"size": "1024x1024",
"quality": "hd"
}
)
result = response.json()
return result["data"][0]["url"]
def create_mood_board(self, theme, num_images=6):
"""Create a mood board with multiple related images"""
mood_variations = [
f"{theme}, inspirational mood",
f"{theme}, dramatic lighting",
f"{theme}, soft and dreamy",
f"{theme}, bold and vibrant",
f"{theme}, minimalist approach",
f"{theme}, textured and detailed"
]
mood_board = []
for i, variation in enumerate(mood_variations[:num_images]):
try:
image_url = self.concept_to_image(variation)
mood_board.append({
"concept": variation,
"url": image_url
})
print(f"Generated mood board image {i+1}: {image_url}")
except Exception as e:
print(f"Failed to generate mood board image {i+1}: {e}")
return mood_board
def iterate_design(self, base_concept, feedback):
"""Iterate on a design based on feedback"""
iteration_prompt = f"""
Original concept: {base_concept}
Feedback received: {feedback}
Create an improved version that addresses the feedback while maintaining the core concept.
Provide a detailed visual description for image generation.
"""
response = requests.post(
"https://api.anyapi.ai/v1/chat/completions",
headers={
"Authorization": f"Bearer {self.api_key}",
"Content-Type": "application/json"
},
json={
"model": "gpt-4o",
"messages": [
{
"role": "system",
"content": "You are a designer iterating on concepts based on feedback."
},
{"role": "user", "content": iteration_prompt}
],
"temperature": 0.6
}
)
improved_concept = response.json()["choices"][0]["message"]["content"]
improved_image = self.concept_to_image(improved_concept)
return improved_image, improved_concept
# Usage
workflow = CreativeWorkflow("YOUR_API_KEY")
# Project brainstorming
brief = "Design visuals for a new eco-friendly coffee shop that appeals to young professionals"
concepts = workflow.brainstorm_concepts(brief)
print("Generated concepts:")
print(concepts)
# Create mood board
mood_board = workflow.create_mood_board("sustainable coffee culture", 4)
print("\nMood board created:")
for item in mood_board:
print(f"{item['concept']}: {item['url']}")
# Design iteration
base_concept = "modern coffee shop interior with living walls and natural lighting"
feedback = "Make it feel more cozy and less corporate, add warm colors"
improved_url, improved_concept = workflow.iterate_design(base_concept, feedback)
print(f"\nImproved design: {improved_url}")
print(f"Improved concept: {improved_concept}")
Model | Strengths | Best For | Style |
---|---|---|---|
DALL-E 3 | Prompt adherence, quality | General purpose, concepts | Balanced, realistic |
Flux Pro | Photorealism, details | Commercial, professional | Photographic |
Stable Diffusion XL | Customization, speed | Experimentation, artistic | Artistic, flexible |
Midjourney | Artistic style, creativity | Creative projects, art | Stylized, artistic |
def recommend_model(use_case, style_preference, quality_needs):
"""Recommend the best model for specific needs"""
recommendations = {
("marketing", "photorealistic", "high"): "flux-pro",
("marketing", "artistic", "high"): "dall-e-3",
("creative", "artistic", "high"): "midjourney-v6",
("prototype", "any", "medium"): "stable-diffusion-xl",
("social_media", "vibrant", "medium"): "dall-e-3",
("product", "photorealistic", "high"): "flux-pro",
("concept_art", "artistic", "high"): "midjourney-v6",
("quick_test", "any", "low"): "stable-diffusion-turbo"
}
key = (use_case, style_preference, quality_needs)
return recommendations.get(key, "dall-e-3") # Default to DALL-E 3
# Usage
model = recommend_model("marketing", "photorealistic", "high")
print(f"Recommended model: {model}")
quality_modifiers = {
"photography": [
"professional photography",
"high resolution",
"sharp focus",
"perfect lighting",
"DSLR camera",
"award-winning"
],
"artwork": [
"masterpiece",
"highly detailed",
"intricate",
"beautiful",
"stunning",
"gallery quality"
],
"commercial": [
"commercial photography",
"product shot",
"clean background",
"professional lighting",
"marketing ready"
]
}
def enhance_prompt_quality(base_prompt, category="photography"):
"""Add quality modifiers to improve image generation"""
modifiers = quality_modifiers.get(category, quality_modifiers["photography"])
selected_modifiers = ", ".join(modifiers[:3]) # Use top 3 modifiers
return f"{base_prompt}, {selected_modifiers}"
# Usage
enhanced = enhance_prompt_quality(
"a modern kitchen with marble countertops",
"commercial"
)
print(enhanced)
# Output: "a modern kitchen with marble countertops, commercial photography, product shot, clean background"