message
AI/ML Development

Integrating AI Image Generation in Vue.js Using Free APIs

Blog bannerBlog banner

In today's digital landscape, AI-powered image generation has become increasingly popular and accessible. Integrating AI image generation can significantly boost your project's capabilities, whether you're building a creative app, enhancing user experience, or adding visual content to your Vue.js application.

This comprehensive guide will walk you through implementing AI image generation in Vue.js using both free and paid APIs, complete with practical examples and best practices.

Introduction to AI Image Generation

AI image generation uses machine learning models to create images from text descriptions (text-to-image) or transform existing images. Popular models include Stable Diffusion, DALL-E, and Midjourney, which can generate high-quality, creative images based on prompts.

Benefits for Vue.js Applications

  • Enhanced User Experience: Allow users to generate custom visuals
  • Content Creation: Automate image creation for blogs, social media
  • Prototyping: Quickly generate placeholder images or concepts
  • Creative Tools: Build artistic applications and design tools

Integrating AI Image Generation in Vue : What We'll Build

A Vue.js application that generates AI images using free services, with a beautiful UI and multiple fallback options. The app will primarily use Pollinations.ai, which is completely free and requires no registration.

Setting Up Your Vue.js Project

First, let's set up a basic Vue.js project structure for our image generation functionality.

Prerequisites:

  • Node.js 16+ installed (tested with version v18.15.0 and v20.8.0) 
  • NPM version used in this tutorial: 10.1.0
  • Basic knowledge of Vue.js and TypeScript 
  • Understanding of async/await and fetch API

1. Initialize the Project

We will create our project using the Vue CLI, starting by running the following command:

Code

    $ npm create vue@latest

When you run the npm create vue@latest command, you'll be prompted to configure your project. Here's what the setup process looks like:

Recommended selections for this project:

  • TypeScript (essential for this tutorial)

2. Install the dependencies

Code

    $ npm install
            

3. Running the Application

Starts a local development server with hot-reload functionality, allowing developers to see changes instantly without manual refreshes.

Code

    $ npm run dev
            

4. Add CSS Styling via CDN (index.html)

To ensure your application has the proper styling, you need to add the CSS link to your index.html file. This step is crucial for the visual appearance of your AI image generator.

Important: Update your /index.html file to include the CSS CDN link in the <head> section:

Code

    <!DOCTYPE html>
    <html lang="">
        <head>
            <meta charset="UTF-8">
            <link rel="icon" href="/favicon.ico">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <title>Vite App</title>
            <link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/hardikzignuts/ai-image-generation-api-vue-app@main/style.css">
        </head>
        <body>
            <div id="app"></div>
            <script type="module" src="/src/main.ts"></script>
        </body>
    </html>
            

Note: This CDN link provides all the necessary styling for the image generator interface, including responsive design, animations, and modern UI components. Without this CSS file, your application will lack proper styling and visual appeal.

5. Configure Main Application Entry Point (main.ts)

You need to update your main application entry point to properly mount the Vue application. Update your /src/main.ts file with the following code:

Code

    import { createApp } from 'vue'
    import App from './App.vue'
    
    createApp(App).mount('#app')
            

This file is responsible for:

  • Importing the Vue framework
  • Importing your root App component
  • Creating the Vue application instance
  • Mounting the app to the DOM element with id "app"

6. Final Project Structure

After implementing all the components and utilities, your project structure will look like this:

Key Files Explanation

Key Files Explanation

  • components/FreeAIImageGenerator.vue: The main component containing the UI and logic for image generation
  • utils/availableImageGenerator.ts: Contains the Pollinations AI integration and utility functions
  • App.vue: Root component that imports and renders the main image generator
  • main.ts: Application entry point that mounts the Vue app
  • index.html: Contains the CSS CDN link and app mounting point
  • package.json: Defines project dependencies, scripts, and metadata
  • tsconfig.json: TypeScript compiler configuration for type checking
  • vite.config.ts: Vite bundler configuration for development and build processes
Hire Now!

Hire Vue.js Developers Today!

Ready to bring your app vision to life? Start your journey with Zignuts expert iOS developers.

**Hire now**Hire Now**Hire Now**Hire now**Hire now

AI Image Generation Implementation Walkthrough

Now let's create the core components and utilities for our AI image generator. Follow the file locations carefully to ensure proper project structure.

1. Utility Functions (availableImageGenerator.ts)

Create the utils directory inside your src folder:

File Location: Create a new file src/utils/availableImageGenerator.ts

This utility function creates a direct URL to Pollinations.ai's free image generation API by encoding the user's text prompt and adding parameters for image size, random seed, and AI model selection. It includes robust validation by testing if the generated image actually loads properly using an HTML Image element, with a 30-second timeout protection to prevent hanging requests. The freeServices object provides an extensible registry system that allows easy integration of additional free image generation services in the future.

Code

    // Pollinations.ai - Completely Free, No API Key Required
    export async function generateImagePollinations(prompt: string): Promise<string | null> {
        try {
        const encodedPrompt = encodeURIComponent(prompt);
        const seed = Math.floor(Math.random() * 1000000);
        const imageUrl = `https://image.pollinations.ai/prompt/${encodedPrompt}?width=512&height=512&seed=${seed}&model=flux`;
    
        // Test if the image loads properly
        return new Promise((resolve) => {
            const img = new Image();
            img.crossOrigin = 'anonymous';
    
            const timeout = setTimeout(() => {
            resolve(null);
            }, 30000); // 30 second timeout
    
            img.onload = () => {
            clearTimeout(timeout);
            resolve(imageUrl);
            };
    
            img.onerror = () => {
            clearTimeout(timeout);
            resolve(null);
            };
    
            img.src = imageUrl;
        });
        } catch (error) {
        return null;
        }
    }
    
    // Specific service generators for UI selection
    export const freeServices = {
        pollinations: generateImagePollinations,
    };                            
            

2. Create the Main Component (FreeAIImageGenerator.vue)

Create a new file /src/components/FreeAIImageGenerator.vue with the following code:

Template Section:

The template creates a user interface with a text input for image descriptions, a dropdown for service selection, quick-prompt buttons for common requests, and conditional display areas for generated images, loading states, and error messages. It uses Vue's reactive directives like v-model for two-way data binding, v-if for conditional rendering, and @click for event handling.

Code

    <template>
        <div class="image-generator">
            <div class="header">
            <h1>🎨 AI Image Generator</h1>
            <p class="subtitle">Using Pollinations AI • No API keys required!</p>
            </div>
        
            <div class="controls">
            <div class="input-section">
                <label for="prompt-input" class="input-label">
                Describe your image:
                </label>
                <textarea
                id="prompt-input"
                v-model="prompt"
                placeholder="Describe the image you want to generate... e.g., 'A beautiful sunset over mountains with purple clouds'"
                rows="4"
                class="prompt-textarea"
                ></textarea>
            </div>
        
            <div class="button-group">
                <button
                @click="generate"
                :disabled="isGenerating || !prompt.trim()"
                class="generate-btn"
                >
                <span class="btn-icon">{{ isGenerating ? "🔄" : "🚀" }}</span>
                {{ isGenerating ? "Generating..." : "Generate Image" }}
                </button>
            </div>
        
            <!-- Quick test prompts -->
            <div class="quick-prompts">
                <h3 class="quick-title">✨ Quick Start Prompts:</h3>
                <div class="prompt-buttons">
                <button
                    @click="
                    setPrompt(
                        'A peaceful forest path with morning sunlight filtering through trees'
                    )
                    "
                    class="prompt-btn"
                >
                    🌲 Forest
                </button>
                <button
                    @click="
                    setPrompt(
                        'A cute golden retriever puppy playing in green grass with flowers'
                    )
                    "
                    class="prompt-btn"
                >
                    🐕 Puppy
                </button>
                </div>
            </div>
            </div>
        
            <div v-if="error" class="error-message">
            <div class="error-content">
                <span class="error-icon">❌</span>
                <div class="error-text"><strong>Error:</strong> {{ error }}</div>
                <button @click="retryGeneration" class="retry-btn">🔄 Retry</button>
            </div>
            </div>
        
            <div v-if="generationInfo" class="info-message">
            <span class="info-icon">✅</span>
            <strong>Generated using:</strong> {{ generationInfo }}
            <span v-if="generationTime" class="time-info">
                ⏱️ {{ generationTime }}ms
            </span>
            </div>
        
            <div v-if="imageUrl" class="result-section">
            <h2 class="result-title">🎨 Your Generated Image</h2>
            <div class="image-container">
                <div v-if="imageLoading" class="image-loading">
                <div class="loading-spinner"></div>
                <p>Loading your image...</p>
                </div>
                <img
                :src="imageUrl"
                alt="Generated image"
                class="generated-image"
                @load="onImageLoad"
                @error="onImageError"
                :style="{ display: imageLoading ? 'none' : 'block' }"
                />
            </div>
        
            <div class="image-actions">
                <button @click="downloadImage" class="action-btn download-btn">
                💾 Download
                </button>
                <button
                @click="generateSimilar"
                class="action-btn variation-btn"
                :disabled="isGenerating"
                >
                🎲 Similar
                </button>
                <button
                @click="generate"
                class="action-btn regenerate-btn"
                :disabled="isGenerating"
                >
                🔄 Regenerate
                </button>
            </div>
            </div>
        </div>
    </template>     
            

Script Section:

The script manages the application's state using Vue's Composition API with reactive variables (prompt, imageUrl, isGenerating, error) and contains functions to generate images via the Pollinations API, handle user interactions like downloading and creating variations, and manage loading/error states throughout the image generation process.

Code

    <script lang="ts">
        import { defineComponent, ref } from "vue";
        import {
          generateImagePollinations,
          freeServices,
        } from "../utils/availableImageGenerator";
        
        export default defineComponent({
          name: "FreeAIImageGenerator",
          setup() {
            const prompt = ref("");
            const imageUrl = ref(null);
            const isGenerating = ref(false);
            const error = ref(null);
            const generationInfo = ref(null);
            const generationTime = ref(null);
            const selectedService = ref("pollinations");
            const imageLoading = ref(false);
        
            // Function to generate an AI image based on the prompt and selected service
            const generate = async () => {
              if (!prompt.value.trim()) {
                error.value = "Please enter a description for the image";
                return;
              }
        
              // Clear previous results
              isGenerating.value = true;
              error.value = null;
              imageUrl.value = null;
              generationInfo.value = null;
              generationTime.value = null;
        
              try {
                const startTime = Date.now();
                let result;
        
                if (selectedService.value === "auto") {
                  result = await generateImagePollinations(prompt.value);
                } else {
                  const serviceFunc =
                    freeServices[selectedService.value as keyof typeof freeServices];
                  const url = await serviceFunc(prompt.value);
                  result = {
                    url,
                    service: selectedService.value,
                    success: !!url,
                  };
                }
        
                const endTime = Date.now();
                generationTime.value = endTime - startTime;
        
                if (result.url) {
                  imageUrl.value = result.url;
                  generationInfo.value = result.service;
                  imageLoading.value = true;
                } else {
                  error.value =
                    "All services failed to generate an image. Please try a different prompt or try again later.";
                }
              } catch (err: any) {
                error.value =
                  err.message ||
                  "An unexpected error occurred while generating the image.";
              } finally {
                isGenerating.value = false;
              }
            };
        
            // Function to generate a similar image by adding a variation to the original prompt
            const generateSimilar = async () => {
              const variations = [
                " in different lighting",
                " with different colors",
                " from another angle",
                " in a different style",
                " with more detail",
              ];
              const variation =
                variations[Math.floor(Math.random() * variations.length)];
              const originalPrompt = prompt.value;
              prompt.value = originalPrompt + variation;
              await generate();
            };
        
            // Function to retry the image generation using the current prompt
            const retryGeneration = () => {
              generate();
            };
        
            // Function to set the value of the prompt
            const setPrompt = (newPrompt: string) => {
              prompt.value = newPrompt;
            };
        
            // Function to download the generated image
            const downloadImage = () => {
              if (!imageUrl.value) return;
        
              const link = document.createElement("a");
              link.href = imageUrl.value;
              link.download = `ai-generated-${Date.now()}.png`;
              document.body.appendChild(link);
              link.click();
              document.body.removeChild(link);
            };
        
            // Callback function when image is successfully loaded
            const onImageLoad = () => {
              imageLoading.value = false;
            };
        
            // Callback function when image fails to load
            const onImageError = () => {
              imageLoading.value = false;
              error.value = "Failed to load the generated image. Please try again.";
            };
        
            return {
              prompt,
              imageUrl,
              isGenerating,
              error,
              generationInfo,
              generationTime,
              selectedService,
              imageLoading,
              generate,
              generateSimilar,
              retryGeneration,
              setPrompt,
              downloadImage,
              onImageLoad,
              onImageError,
            };
          },
        });
    </script>

3. Update App.vue

Now that we have created our FreeAIImageGenerator.vue component with all the image generation logic and UI (as implemented and presented in the previous step), we need to update our existing App.vue file to use this component.

Code

    <template>
        <FreeAIImageGenerator />
    </template>
        
    <script lang="ts">
    import { defineComponent } from "vue";
    import FreeAIImageGenerator from "./components/FreeAIImageGenerator.vue";
    
    export default defineComponent({
        name: "App",
        components: {
            FreeAIImageGenerator,
        },
    });
    </script>

This is your root component that serves as the entry point for your entire application and displays the AI image generator interface.

Hire Now!

Hire AI Developers Today!

Ready to harness AI for transformative results? Start your project with Zignuts expert AI developers.

**Hire now**Hire Now**Hire Now**Hire now**Hire now

How AI Image Generation Works

1. Pollinations AI Integration

  • URL-based API: No authentication required
  • FLUX Model: High-quality image generation
  • Customizable: Width, height, seed, and model parameters
  • Cross-origin friendly: Works with CORS

2. Features Included

  • Real-time image generation
  • Download functionality
  • Generate similar variations
  • Quick prompt templates
  • Loading states and error handling

Customization Options:

To add more free services, extend the freeServices object:

Code

    export const freeServices = {
        pollinations: generateImagePollinations,
            // Add your new service here
        newService: generateImageNewService,
    };
            

Free APIs For AI Image Generation (No Cost, No Registration)

Pollinations AI

  • Cost: Completely free with unlimited usage
  • Features: High-quality AI image generation using FLUX model, customizable parameters (width, height, seed)
  • Setup: No API key or registration required - simple URL-based requests
  • Quality: Excellent for most use cases

Picsum Photos

  • Cost: Free
  • Features: Random stock photos with deterministic seeding
  • Setup: No registration needed
  • Use Case: Fallback option when AI generation fails

Paid APIs For AI Image Generation (Require API Keys & Payment)

Hugging Face

  • Cost: https://huggingface.co/pricing
  • Features: Multiple AI models, higher quality outputs, faster generation speeds
  • Setup: Free account registration and API token required

Stability AI

OpenAI DALL-E

  • Cost: https://openai.com/api/pricing/
  • Features: Excellent image quality, consistent style, advanced prompt understanding
  • Setup: OpenAI account and API key required

Replicate

  • Cost: https://replicate.com/pricing
  • Features: Multiple available models, custom fine-tuning options, flexible pricing
  • Setup: Account registration and API key required

Conclusion

You now have a fully functional, free AI image generator built with Vue.js! The app uses Pollinations AI as the primary service and includes comprehensive error handling and user experience features.

The implementation focuses on reliability and user experience while keeping costs at zero. For production applications with higher quality requirements, consider the paid alternatives mentioned in the comparison section.

Key Takeaways:

  • Pollinations AI provides excellent free image generation
  • Always implement fallback mechanisms
  • User experience is crucial for AI applications
  • Vue 3 + TypeScript provides an excellent developer experience

Ready to bring powerful AI features into your web or mobile app? At Zignuts, we specialize in building intelligent, scalable applications using Vue.js, AI APIs, and modern tech stacks. Whether you're a startup or an enterprise, we can help you integrate next-gen features like AI image generation into your digital products.

👉 Contact us today to hire expert Developers and turn your ideas into reality.

card user img
Twitter iconLinked icon

Passionate developer with expertise in building scalable web applications and solving complex problems. Loves exploring new technologies and sharing coding insights.

card user img
Twitter iconLinked icon

Passionate developer with expertise in building scalable web applications and solving complex problems. Loves exploring new technologies and sharing coding insights.

Book a FREE Consultation

No strings attached, just valuable insights for your project

Valid number
Please complete the reCAPTCHA verification.
Claim My Spot!
Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.
download ready
Thank You
Your submission has been received.
We will be in touch and contact you soon!

Our Latest Blogs

View All Blogs