JSPM

  • ESM via JSPM
  • ES Module Entrypoint
  • Export Map
  • Keywords
  • License
  • Repository URL
  • TypeScript Types
  • README
  • Created
  • Published
  • Downloads 46
  • Score
    100M100P100Q51285F
  • License MIT

Turn your alt text descriptions into real images. Generate AI images automatically from HTML alt attributes and code descriptions.

Package Exports

  • imagenai
  • imagenai/dist/index.js

This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (imagenai) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.

Readme

imagenai

Turn your alt text descriptions into real images. Generate AI images automatically from HTML alt attributes and code descriptions. Never see a broken image again.

🚀 The Problem We Solve

Every developer has experienced this:

<img src="broken-image.jpg" alt="A beautiful sunset over mountains" />
<!-- Broken image icon, but the alt text tells you exactly what should be there -->

Your alt text is already the prompt - you just don't realize it! Instead of seeing broken images, generate the actual visuals from the descriptions you're already writing.

🌟 Key Features

  • Alt Text as Prompt: Generate images from HTML alt attributes automatically
  • Universal Compatibility: Works in Node.js, React, Next.js, and vanilla JavaScript
  • No More Broken Images: Automatic fallback generation from alt text
  • TypeScript First: Full TypeScript support with comprehensive type definitions
  • Enterprise Ready: Built-in retry logic, timeout handling, and error management
  • Seamless Integration: Works with existing HTML and components
  • Environment Consistency: Same images generated across dev, staging, and production

🔄 Permanent Image Storage & Caching

When you generate an image from alt text, it's stored permanently and cached intelligently. This means:

  • Same prompt = Same image forever - No more 1-year expiration issues
  • Environment consistency - Same image generated in dev, staging, and production
  • Cost efficient - No duplicate storage, smart deduplication
  • Fast delivery - Redis caching + Google Cloud Storage CDN
  • Developer confidence - Images remain stable for websites

⚡ Technical Optimizations

Behind the scenes, your images are optimized for performance:

  • Smart compression using Sharp for optimal file sizes
  • Progressive JPEG encoding for faster perceived loading
  • Global CDN delivery for low-latency access worldwide
  • Intelligent caching prevents duplicate generation requests
  • Cross-environment consistency - Images generated once, served everywhere

🌍 Environment Consistency

One of the biggest challenges in development is ensuring consistency across environments. With Imagenai:

  • Development → Staging → Production: Same alt text generates identical images
  • Team collaboration: All developers see the same images for the same descriptions
  • No environment-specific assets: Images are generated once and served everywhere
  • Predictable deployments: Your staging environment exactly matches production
  • Reduced debugging: No more "works on my machine" image issues

This is especially crucial for:

  • Design systems that need consistent visual elements
  • Marketing sites where brand consistency matters
  • E-commerce platforms requiring reliable product images
  • Documentation sites needing consistent illustrations

🗄️ Image Storage & Management

We handle all the complexity of image storage so you don't have to:

  • Automatic storage - Images stored permanently in Google Cloud Storage
  • No infrastructure setup - We manage servers, CDN, and backups
  • Global availability - Images accessible from anywhere in the world
  • Automatic optimization - Compressed and optimized for web delivery
  • Storage scaling - Handles millions of images without performance degradation

📦 Installation

npm install imagenai

🌐 Compatibility

Environment Support Use Case
HTML ✅ Full Generate from alt attributes
React ✅ Full Components with alt text generation
Next.js ✅ Full SSR + Client-side alt text processing
Node.js ✅ Full Server-side alt text processing
Vanilla JS ✅ Full Browser environments

🔑 Quick Start

Basic Alt Text Generation

import { createImagenaiClient } from 'imagenai';

// Initialize the client
const client = createImagenaiClient({
  apiKey: 'your-api-key-here'
});

// Generate image from alt text
const image = await client.generateImage({
  prompt: 'A beautiful sunset over mountains, digital art style'
});

console.log('Generated image URL:', image.url);

HTML Alt Text to Image

<!DOCTYPE html>
<html>
<head>
    <title>Alt Text to Image Generator</title>
</head>
<body>
    <!-- This image will be generated from its alt text -->
    <img 
        src="broken-image.jpg" 
        alt="A cyberpunk city at night with neon lights and flying cars"
        style="width: 100%; height: 300px;"
    />
    
    <script type="module">
        import { createImagenaiClient } from 'https://esm.sh/imagenai';
        
        const client = createImagenaiClient({
            apiKey: 'your-api-key-here'
        });

        // Auto-generate images from alt text
        document.querySelectorAll('img').forEach(async (img) => {
            if (img.alt && img.src.includes('broken-image')) {
                try {
                    const result = await client.generateImage({ 
                        prompt: img.alt 
                    });
                    img.src = result.url;
                } catch (error) {
                    console.error('Failed to generate image for:', img.alt);
                }
            }
        });
    </script>
</body>
</html>

React Auto-Generation on Page Load

import { useEffect, useState } from "react";
import { createImagenaiClient } from 'imagenai';

export default function HeroPage() {
  const [imageUrl, setImageUrl] = useState<string>('');
  const [imagePrompt, setImagePrompt] = useState<string>('');

  const generateImage = async () => {
    try {
      const client = createImagenaiClient({
        apiKey: process.env.NEXT_PUBLIC_IMAGENAI_API_KEY || ''
      });

      const result = await client.generateImage({
        prompt: 'A 3D minimalist, translucent figure 8 with 2 spheres orbiting the figure 8; one sphere is light green and the other is dark green; the figure 8 is in the center'
      });

      setImageUrl(result.url);
      setImagePrompt(result.prompt);
    } catch (error) {
      console.error('Failed to generate image:', error);
    }
  };

  // Auto-generate image when component mounts
  useEffect(() => {
    generateImage();
  }, []);

  return (
    <div className="hero-section">
      {/* Conditional rendering prevents empty src errors */}
      {imageUrl && (
        <img 
          src={imageUrl} 
          alt={imagePrompt}
          className="hero-image"
        />
      )}
    </div>
  );
}

🎯 Core Use Cases

1. Auto-Generation on Page Load

Generate images automatically when components mount. Perfect for:

  • Hero sections and landing pages
  • Marketing sites with dynamic visuals
  • Portfolio showcases
  • Dashboard backgrounds

Key Benefits:

  • No user interaction required
  • Images appear immediately on page load
  • Perfect for marketing and conversion
  • Seamless user experience

2. Generate Missing Images from Alt Text

// Automatically generate images when src fails
const handleImageError = async (event) => {
  const img = event.target;
  const altText = img.alt;
  
  if (altText && !img.dataset.generated) {
    try {
      const result = await client.generateImage({ prompt: altText });
      img.src = result.url;
      img.dataset.generated = 'true';
    } catch (error) {
      console.error('Failed to generate image from alt text:', altText);
    }
  }
};

// Apply to all images
document.querySelectorAll('img').forEach(img => {
  img.addEventListener('error', handleImageError);
});

2. React Component with Alt Text Generation

import React, { useState, useEffect } from 'react';
import { createImagenaiClient } from 'imagenai';

interface ImageWithAltProps {
  altText: string;
  className?: string;
  fallbackSrc?: string;
}

function ImageWithAlt({ altText, className, fallbackSrc }: ImageWithAltProps) {
  const [imageUrl, setImageUrl] = useState<string>('');
  const [isGenerating, setIsGenerating] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const client = createImagenaiClient({
    apiKey: 'your-api-key-here'
  });

  useEffect(() => {
    generateImageFromAlt();
  }, [altText]);

  const generateImageFromAlt = async () => {
    if (!altText.trim()) return;
    
    setIsGenerating(true);
    setError(null);
    
    try {
      const result = await client.generateImage({ prompt: altText });
      setImageUrl(result.url);
    } catch (err) {
      setError('Failed to generate image from alt text');
    } finally {
      setIsGenerating(false);
    }
  };

  if (isGenerating) {
    return (
      <div className={`${className} bg-gray-100 rounded-lg flex items-center justify-center`}>
        <div className="text-center p-8">
          <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600 mx-auto mb-4"></div>
          <p className="text-gray-600">Generating: "{altText}"</p>
        </div>
      </div>
    );
  }

  if (error) {
    return (
      <div className={`${className} bg-red-50 border border-red-200 rounded-lg p-4`}>
        <p className="text-red-800 mb-2">{error}</p>
        <p className="text-sm text-red-600 mb-3">Alt text: "{altText}"</p>
        <button onClick={generateImageFromAlt} className="bg-red-600 text-white px-4 py-2 rounded">
          Retry Generation
        </button>
      </div>
    );
  }

  return (
    <img 
      src={imageUrl || fallbackSrc} 
      alt={altText}
      className={className}
    />
  );
}

// Usage
<ImageWithAlt 
  altText="A futuristic dashboard with glowing blue charts and data visualizations"
  className="w-full rounded-lg shadow-lg"
/>

3. Next.js API Route for Alt Text Processing

// app/api/generate-from-alt/route.ts
import { createImagenaiClient } from 'imagenai';
import { NextRequest, NextResponse } from 'next/server';

export async function POST(request: NextRequest) {
  try {
    const { altText, size = '1024x1024', quality = 'high' } = await request.json();
    
    if (!altText) {
      return NextResponse.json(
        { error: 'Alt text is required' }, 
        { status: 400 }
      );
    }
    
    const client = createImagenaiClient({
      apiKey: process.env.IMAGENAI_API_KEY!
    });

    const result = await client.generateImage({ 
      prompt: altText,
      size,
      quality
    });
    
    return NextResponse.json({
      success: true,
      imageUrl: result.url,
      altText: altText,
      generatedAt: new Date().toISOString()
    });
    
  } catch (error) {
    console.error('Alt text generation failed:', error);
    return NextResponse.json(
      { error: 'Failed to generate image from alt text' }, 
      { status: 500 }
    );
  }
}

4. Node.js HTML Processing

import express from 'express';
import { createImagenaiClient } from 'imagenai';
import { JSDOM } from 'jsdom';

const app = express();
app.use(express.json());

const client = createImagenaiClient({
  apiKey: process.env.IMAGENAI_API_KEY!
});

// Middleware to process HTML and generate missing images from alt text
app.use('/api/process-html', async (req, res) => {
  try {
    const { html, generateMissingImages = true } = req.body;
    
    if (!html) {
      return res.status(400).json({ error: 'HTML content is required' });
    }

    const dom = new JSDOM(html);
    const document = dom.window.document;
    const images = document.querySelectorAll('img');
    
    const processedImages = [];
    
    for (const img of images) {
      const src = img.getAttribute('src');
      const alt = img.getAttribute('alt');
      
      // Check if image is broken or missing
      if ((!src || src.includes('broken') || src.includes('placeholder')) && alt) {
        if (generateMissingImages) {
          try {
            // Generate image from alt text
            const result = await client.generateImage({ prompt: alt });
            
            // Update the image source
            img.setAttribute('src', result.url);
            img.setAttribute('data-generated', 'true');
            
            processedImages.push({
              originalAlt: alt,
              generatedUrl: result.url,
              status: 'generated'
            });
            
          } catch (error) {
            console.error('Failed to generate image for alt text:', alt, error);
            processedImages.push({
              originalAlt: alt,
              error: error.message,
              status: 'failed'
            });
          }
        }
      }
    }
    
    const processedHtml = dom.serialize();
    
    res.json({
      success: true,
      processedHtml,
      processedImages,
      summary: {
        total: images.length,
        generated: processedImages.filter(img => img.status === 'generated').length,
        failed: processedImages.filter(img => img.status === 'failed').length
      }
    });
    
  } catch (error) {
    console.error('HTML processing failed:', error);
    res.status(500).json({ error: 'Failed to process HTML' });
  }
});

app.listen(3000, () => {
  console.log('Alt text image generator server running on port 3000');
});

⚙️ Configuration Options

const client = createImagenaiClient({
  apiKey: 'your-api-key',           // Required: Your Imagenai API key
  baseUrl: 'https://app-imagenai.vercel.app', // Optional: API base URL (defaults to production)
  timeout: 30000,                   // Optional: Request timeout in ms (default: 30000)
  retries: 3                        // Optional: Number of retry attempts (default: 3)
});

Note: The baseUrl parameter is optional. If not provided, the client will default to the production API at https://app-imagenai.vercel.app. You only need to specify this if you're using a custom API endpoint or testing environment.

🎨 Image Generation Options

Option Type Default Description
prompt string Required Your alt text description (the image prompt)
size '1024x1024' | '1024x1536' | '1536x1024' '1024x1024' Image dimensions
quality 'low' | 'medium' | 'high' 'medium' Rendering quality

🚀 Auto-Generation Best Practices

Environment Variables

# .env.local
NEXT_PUBLIC_IMAGENAI_API_KEY=your-actual-api-key

Conditional Rendering

Always prevent empty src errors:

{/* ❌ Wrong - causes empty src errors */}
<img src={imageUrl} alt="description" />

{/* ✅ Correct - only renders when image exists */}
{imageUrl && <img src={imageUrl} alt="description" />}

Error Handling

const generateImage = async () => {
  try {
    const client = createImagenaiClient({
      apiKey: process.env.NEXT_PUBLIC_IMAGENAI_API_KEY || ''
    });
    
    const result = await client.generateImage({ prompt: 'your prompt' });
    setImageUrl(result.url);
  } catch (error) {
    console.error('Failed to generate image:', error);
    // Handle error gracefully
  }
};

📝 Writing Effective Alt Text for Generation

The better your alt text, the better your generated images. Here's how to write descriptions that create amazing visuals:

✅ Good Alt Text Examples

  • "A majestic mountain landscape at golden hour with snow-capped peaks, pine forests, and a crystal-clear alpine lake reflecting the sunset sky"
  • "A futuristic dashboard with glowing blue charts, holographic displays, and sleek dark interface elements"
  • "A cozy coffee shop interior with warm lighting, exposed brick walls, vintage furniture, and steam rising from coffee cups"

❌ Vague Alt Text Examples

  • "A nice landscape"
  • "A dashboard"
  • "A coffee shop"

🎯 Alt Text Best Practices

  1. Be Descriptive: Include style, mood, atmosphere, colors, lighting, and composition
  2. Be Specific: Use concrete nouns, vivid adjectives, and relevant details
  3. Specify Style: Mention artistic style, genre, or rendering approach
  4. Include Context: Describe the subject, setting, and any important elements

🛡️ Error Handling

The library provides comprehensive error handling with detailed information:

try {
  const image = await client.generateImage({
    prompt: 'A beautiful landscape'
  });
} catch (error: any) {
  if (error.details?.status === 'active' && error.details?.current >= error.details?.limit) {
    console.log('Quota exceeded - upgrade your subscription for more images');
  } else if (error.message.includes('invalid prompt')) {
    console.log('Please provide a valid alt text description');
  } else {
    console.log('An error occurred:', error.message);
    console.log('Error details:', error.details);
  }
}

📊 Response Types

GeneratedImage

interface GeneratedImage {
  id: string;           // Unique image identifier
  url: string;          // CDN URL for the generated image
  prompt: string;       // The alt text used to generate the image
  size: string;         // Image dimensions
  quality: string;      // Image quality level
  cached: boolean;      // Whether the image was served from cache
  createdAt: string;    // ISO timestamp of creation
  usage?: {             // Usage information (if available)
    remaining: number;  // Remaining images in quota
    limit: number;      // Total quota limit
    tier: string;       // Subscription tier
  };
}

🚀 Advanced Usage Patterns

1. Batch Alt Text Processing

// Process multiple alt text descriptions
const altTexts = [
  'A cyberpunk city at night with neon lights',
  'A peaceful forest scene with morning mist',
  'A futuristic robot in a laboratory setting'
];

const results = await Promise.all(
  altTexts.map(altText => 
    client.generateImage({ prompt: altText })
  )
);

console.log('Generated images:', results.map(r => r.url));

2. Alt Text with Dynamic Variables

// Generate personalized images based on user data
const generateUserAvatar = async (user) => {
  const altText = `Professional headshot of a ${user.profession} in ${user.preferredStyle} style`;
  
  try {
    const result = await client.generateImage({ prompt: altText });
    return result.url;
  } catch (error) {
    console.error('Failed to generate avatar:', error);
    return user.defaultAvatar;
  }
};

3. Fallback Image Generation

// Generate fallback images when primary images fail
const getImageWithFallback = async (primarySrc, altText) => {
  try {
    // Try to load primary image
    const response = await fetch(primarySrc);
    if (response.ok) {
      return primarySrc;
    }
  } catch (error) {
    // Primary image failed, generate from alt text
    console.log('Primary image failed, generating from alt text:', altText);
  }
  
  try {
    const result = await client.generateImage({ prompt: altText });
    return result.url;
  } catch (error) {
    console.error('Failed to generate fallback image:', error);
    return '/placeholder.jpg';
  }
};

🔧 Development and Testing

Local Development

# Clone the repository
git clone https://github.com/vlokandre1/app-imagenai.git
cd app-imagenai/packages/core

# Install dependencies
npm install

# Build the package
npm run build

# Run tests
npm test

# Watch mode for development
npm run dev

Testing with Custom Base URL

// For development/testing with local API
const devClient = createImagenaiClient({
  apiKey: 'your-api-key',
  baseUrl: 'http://localhost:3000' // Your local development server
});

// For staging environments
const stagingClient = createImagenaiClient({
  apiKey: 'your-api-key',
  baseUrl: 'https://staging-imagenai.vercel.app'
});

📚 Examples

Check out the examples/ directory for complete working examples:

  • Basic Usage: Simple image generation from alt text
  • HTML Processing: Generate images from HTML alt attributes
  • React Integration: Components with automatic alt text generation
  • Error Handling: Comprehensive error handling examples

🤝 Contributing

We welcome contributions! Please see our Contributing Guide for details.

📄 License

MIT License - see LICENSE for details.

🆘 Support


Never see a broken image again. Your alt text becomes the image. 🎨✨