Command Palette

Search for a command to run...

AI Badges/Use AI Avatar

Use AI Avatar

React hook for generating AI avatars from photos with multiple style options

Open in v0Open in

AI Avatar Generator

Upload a photo to generate a pixel-art avatar

Original
Input
AI Avatar
Output

Note: This demo requires a backend API endpoint at /api/generate-avatar

Overview

The Use AI Avatar hook provides a client-side interface for generating AI-transformed avatars from photos. It supports multiple styles including pixel-art, anime, cartoon, realistic, and sketch.

Installation

npx shadcn@latest add "https://tryelements.dev/r/use-ai-avatar"

Usage

import { useAiAvatar } from "@/components/elements/use-ai-avatar";

export function AvatarGenerator() {
  const { generateAvatar, isGenerating, avatarUrl, progress, status } = useAiAvatar({
    endpoint: "/api/generate-avatar",
    style: "pixel-art",
  });

  const handleFileChange = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (file) {
      const url = await generateAvatar({ image: file });
      if (url) {
        console.log("Avatar generated:", url);
      }
    }
  };

  return (
    <div>
      <input type="file" accept="image/*" onChange={handleFileChange} />
      {isGenerating && <p>{status} ({progress}%)</p>}
      {avatarUrl && <img src={avatarUrl} alt="AI Avatar" />}
    </div>
  );
}

Hook Options

OptionTypeDefaultDescription
endpointstring"/api/generate-avatar"API endpoint for generation
styleAvatarStyle"pixel-art"Style of avatar to generate
promptAdditionsstring""Custom prompt additions
grayscalebooleantrueConvert to grayscale
removeBackgroundbooleantrueRemove background
outputSizeobject{ width: 684, height: 577 }Output dimensions

Available Styles

StyleDescription
pixel-art8-bit pixel art with flat grayscale shading
animeClean anime style with soft coloring
cartoonBold outlines with flat colors
realisticPhotorealistic enhancement
sketchHand-drawn pencil sketch style

Return Values

PropertyTypeDescription
generateAvatarfunctionGenerate avatar from image
isGeneratingbooleanLoading state
progressnumberProgress percentage (0-100)
statusstring | nullCurrent status message
errorError | nullError if generation failed
avatarUrlstring | nullGenerated avatar URL
resetfunctionReset hook state

Backend Setup

This hook requires a backend API endpoint. Here's an example using FAL AI:

// app/api/generate-avatar/route.ts
import { NextRequest, NextResponse } from "next/server";
import * as fal from "@fal-ai/serverless-client";

fal.config({
  credentials: process.env.FAL_API_KEY,
});

export async function POST(req: NextRequest) {
  const { imageUrl, prompt, grayscale, removeBackground, outputSize } = await req.json();

  // Generate with FAL AI
  const result = await fal.subscribe("fal-ai/qwen-image-edit", {
    input: { prompt, image_url: imageUrl },
  });

  // Optional: Remove background
  if (removeBackground) {
    const bgResult = await fal.subscribe("fal-ai/birefnet/v2", {
      input: { image_url: result.images[0].url },
    });
    // Process and return...
  }

  return NextResponse.json({ url: result.images[0].url });
}

Environment Variables

FAL_API_KEY=your_fal_api_key

Features

  • Multiple avatar styles (pixel-art, anime, cartoon, etc.)
  • Progress tracking with status messages
  • Error handling with detailed messages
  • Background removal support
  • Grayscale conversion
  • Custom output sizing
  • File and URL input support