Skip to content

Instantly share code, notes, and snippets.

@Wolfr
Created February 11, 2026 02:46
Show Gist options
  • Select an option

  • Save Wolfr/43e4020278ad249a3bf17ad764708d39 to your computer and use it in GitHub Desktop.

Select an option

Save Wolfr/43e4020278ad249a3bf17ad764708d39 to your computer and use it in GitHub Desktop.
name description
gemini-avatar-generation
Generate avatar images using Google's Gemini API. Use when creating placeholder avatars, profile pictures, or character images for components.

Gemini Avatar Generation

Generate 512x512 avatar images using Google's Gemini API for use in components like Team sections, testimonials, and user profiles.

Setup

API Key

Set your Gemini API key as an environment variable:

export GEMINI_API_KEY="your-api-key-here"

Or add to .env:

GEMINI_API_KEY=your-api-key-here

Install SDK

npm install @google/genai

Models

Model Best For
imagen-4.0-generate-001 Standard quality, good balance
imagen-4.0-fast-generate-001 Faster generation
imagen-4.0-ultra-generate-001 Highest quality

Basic Avatar Generation

import { GoogleGenAI } from "@google/genai";
import * as fs from "node:fs";

const ai = new GoogleGenAI({ apiKey: process.env.GEMINI_API_KEY });

async function generateAvatar(prompt, outputPath = "avatar.png") {
  const response = await ai.models.generateImages({
    model: "imagen-4.0-generate-001",
    prompt: prompt,
    config: {
      numberOfImages: 1,
      aspectRatio: "1:1",
    }
  });

  if (response.generatedImages && response.generatedImages.length > 0) {
    const image = response.generatedImages[0];
    if (image.image && image.image.imageBytes) {
      const buffer = Buffer.from(image.image.imageBytes, "base64");
      fs.writeFileSync(outputPath, buffer);
      console.log(`Avatar saved to ${outputPath}`);
    }
  }
}

Avatar Prompt Examples

Professional Headshots

// Generic professional avatar
generateAvatar(
  "Professional headshot portrait of a person in business attire, neutral background, soft studio lighting, friendly expression, looking at camera"
);

// Specific characteristics
generateAvatar(
  "Professional headshot of a woman with short dark hair, wearing a navy blazer, warm smile, clean white background, corporate photography style"
);

Illustrated Avatars

// Minimalist illustration style
generateAvatar(
  "Minimalist illustrated avatar of a person, flat design style, soft pastel colors, simple geometric shapes, friendly expression"
);

// Modern cartoon style
generateAvatar(
  "Modern cartoon-style avatar portrait, clean vector look, vibrant colors, friendly professional appearance, solid color background"
);

Diverse Team Avatars

const teamPrompts = [
  "Professional headshot of a young man with glasses, casual smart attire, friendly smile, neutral background",
  "Professional headshot of a woman with curly hair, creative professional look, warm expression, soft lighting",
  "Professional headshot of an older man, distinguished appearance, kind smile, business casual, clean background",
  "Professional headshot of a young woman, modern professional style, confident expression, neutral tones"
];

// Generate multiple avatars
teamPrompts.forEach((prompt, i) => {
  generateAvatar(prompt, `team-member-${i + 1}.png`);
});

Batch Generation Utility

import { GoogleGenAI } from "@google/genai";
import * as fs from "node:fs";
import * as path from "node:path";

const ai = new GoogleGenAI({ apiKey: process.env.GEMINI_API_KEY });

async function generateAvatarSet(count = 6, style = "professional", outputDir = "./avatars") {
  // Ensure output directory exists
  if (!fs.existsSync(outputDir)) {
    fs.mkdirSync(outputDir, { recursive: true });
  }

  const stylePrompts = {
    professional: "Professional headshot portrait, business attire, clean white background, soft studio lighting, friendly expression",
    illustrated: "Minimalist illustrated avatar, flat design, soft colors, simple geometric shapes, friendly expression",
    casual: "Casual portrait photo, natural lighting, relaxed friendly expression, simple background"
  };

  const basePrompt = stylePrompts[style] || stylePrompts.professional;

  const variations = [
    "young woman with long dark hair",
    "man with short beard and glasses",
    "woman with short gray hair",
    "young man with curly hair",
    "woman with red hair and freckles",
    "older man with distinguished features"
  ];

  for (let i = 0; i < Math.min(count, variations.length); i++) {
    const prompt = `${basePrompt}, ${variations[i]}`;
    const outputPath = path.join(outputDir, `avatar-${i + 1}.png`);

    try {
      const response = await ai.models.generateImages({
        model: "imagen-4.0-generate-001",
        prompt: prompt,
        config: {
          numberOfImages: 1,
          aspectRatio: "1:1",
        }
      });

      if (response.generatedImages && response.generatedImages.length > 0) {
        const image = response.generatedImages[0];
        if (image.image && image.image.imageBytes) {
          const buffer = Buffer.from(image.image.imageBytes, "base64");
          fs.writeFileSync(outputPath, buffer);
          console.log(`Generated: ${outputPath}`);
        }
      }
    } catch (error) {
      console.error(`Failed to generate avatar ${i + 1}:`, error.message);
    }

    // Small delay between requests
    await new Promise(resolve => setTimeout(resolve, 1000));
  }
}

// Usage
generateAvatarSet(6, "professional", "./public/avatars");

Prompt Best Practices

  1. Be descriptive - Use full sentences, not keyword lists
  2. Specify lighting - "soft studio lighting", "natural window light"
  3. Define background - "neutral gray background", "clean white backdrop"
  4. Include expression - "friendly smile", "confident expression", "approachable look"
  5. Mention style - "professional photography", "illustrated", "minimalist"

Aspect Ratios

Supported aspect ratios for aspectRatio config:

  • 1:1 - Square (ideal for avatars)
  • 3:4, 4:3 - Standard photo
  • 9:16, 16:9 - Widescreen

Imagen generates high-resolution images by default. For exact 512x512 dimensions, resize after generation.

Resizing to 512x512

import sharp from "sharp";

async function resizeAvatar(inputPath, outputPath) {
  await sharp(inputPath)
    .resize(512, 512, { fit: "cover" })
    .toFile(outputPath);
}

Notes

  • All generated images include a SynthID watermark
  • Rate limits apply based on your API tier
  • For consistent character appearance across images, use gemini-3-pro-image-preview with reference images
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment