simple_image_generation/
simple_image_generation.rs1use base64::{engine::general_purpose::STANDARD as BASE64, Engine};
2use gemini_rust::{Gemini, GenerationConfig};
3use std::env;
4use std::fs;
5
6#[tokio::main]
9async fn main() -> Result<(), Box<dyn std::error::Error>> {
10 let api_key = env::var("GEMINI_API_KEY").expect("GEMINI_API_KEY environment variable not set");
12
13 let client = Gemini::with_model(api_key, "models/gemini-2.5-flash-image-preview".to_string());
16
17 println!("🎨 Generating image with Gemini...");
18
19 let response = client
21 .generate_content()
22 .with_user_message(
23 "Create a photorealistic image of a cute robot sitting in a garden, \
24 surrounded by colorful flowers. The robot should have a friendly \
25 expression and be made of polished metal. The lighting should be \
26 soft and natural, as if taken during golden hour.",
27 )
28 .with_generation_config(GenerationConfig {
29 temperature: Some(0.8),
30 max_output_tokens: Some(8192),
31 ..Default::default()
32 })
33 .execute()
34 .await?;
35
36 let mut images_saved = 0;
38 for candidate in response.candidates.iter() {
39 if let Some(parts) = &candidate.content.parts {
40 for part in parts.iter() {
41 match part {
42 gemini_rust::Part::Text { text, .. } => {
43 println!("📝 Model response: {}", text);
44 }
45 gemini_rust::Part::InlineData { inline_data } => {
46 println!("🖼️ Image generated!");
47 println!(" MIME type: {}", inline_data.mime_type);
48
49 match BASE64.decode(&inline_data.data) {
51 Ok(image_bytes) => {
52 images_saved += 1;
53 let filename = format!("robot_garden_{}.png", images_saved);
54 fs::write(&filename, image_bytes)?;
55 println!("✅ Image saved as: {}", filename);
56 }
57 Err(e) => {
58 println!("❌ Failed to decode image: {}", e);
59 }
60 }
61 }
62 _ => {
63 println!("🔍 Other content type in response");
64 }
65 }
66 }
67 }
68 }
69
70 if images_saved == 0 {
71 println!("⚠️ No images were generated. This might be due to:");
72 println!(" - Content policy restrictions");
73 println!(" - API limitations");
74 println!(" - Model configuration issues");
75 } else {
76 println!("🎉 Successfully generated {} image(s)!", images_saved);
77 }
78
79 Ok(())
80}