Building an AI Image Generator with Stable Diffusion API
In this tutorial, you'll learn about Building an AI Image Generator with Stable Diffusion API. We cover key concepts, practical examples, and best practices to help you understand and apply this topic effectively.
What You'll Learn
Use the Stable Diffusion API to generate images from text prompts, customize styles, and build a simple web interface for AI image generation.
Why It Matters
AI image generation is transforming design, marketing, and content creation. Understanding how to integrate it programmatically opens up endless possibilities.
Real-World Use
Generating product images for e-commerce, creating social media graphics, building concept art for games, and prototyping visual designs.
Using Stability AI API
pip install openai
Stability AI offers an API compatible with the OpenAI format:
from openai import OpenAI
client = OpenAI(
api_key="your-stability-api-key",
base_url="https://api.stability.ai/v2beta"
)
response = client.images.generate(
model="stable-diffusion-3.5-large",
prompt="A serene mountain lake at sunset, digital art, highly detailed",
n=1,
size="1024x1024"
)
image_url = response.data[0].url
print(f"Image URL: {image_url}")
Using Replicate (Alternative)
pip install replicate
import replicate
output = replicate.run(
"stability-ai/stable-diffusion-3.5-large:1d",
input={
"prompt": "A futuristic city with neon lights, cyberpunk style",
"aspect_ratio": "16:9"
}
)
print(output[0]) # URL to generated image
Building a Web App
# app.py
from flask import Flask, request, render_template
from openai import OpenAI
import os
app = Flask(__name__)
client = OpenAI(
api_key=os.getenv("STABILITY_API_KEY"),
base_url="https://api.stability.ai/v2beta"
)
@app.route("/", methods=["GET", "POST"])
def index():
image_url = None
if request.method == "POST":
prompt = request.form["prompt"]
response = client.images.generate(
model="stable-diffusion-3.5-large",
prompt=prompt,
n=1,
size="1024x1024"
)
image_url = response.data[0].url
return render_template("index.html", image_url=image_url)
Best Practices for Prompts
| Element | Example |
|---|---|
| Subject | "A cat wearing a spacesuit" |
| Style | "digital art, photorealistic, oil painting" |
| Lighting | "cinematic lighting, golden hour" |
| Mood | "peaceful, dramatic, mysterious" |
| Medium | "4K, trending on ArtStation" |
Limitations
- Cost: Each image generation costs ~$0.04-0.10
- Consistency: Same prompt can produce different results
- Control: Fine details are hard to specify precisely
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro