"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Build a Free AI Image Generator with ReactJS

Build a Free AI Image Generator with ReactJS

Published on 2024-11-08
Browse:269

Hi Devs,
Today, I'm going to show you how to create an image generator using ReactJS, and it's all free to use, thanks to black forest labs and Together AI.

Step 1: Setting Up the Project

For this tutorial, we'll be using Vite to initialize the app and Shadcn for the UI. I'll assume you're already set up the project and installed Shadcn.

Step 2: Intall the Together AI package

We need to install the Together AI package to access the free Flux model for image generation.
Run following command in your terminal

npm i together-ai

Step 3: Building the UI

Now, let's create the UI for our app. Below is the full code for image generator component. it includes a text input for prompts. a dropdown for aspect ratios selection.
Keep in mind, we need to use "black-forest-labs/FLUX.1-schnell-Free" because it's free.

import { useRef, useState } from "react";
import Together from "together-ai";
import { ImagesResponse } from "together-ai";
import { Button } from "@/components/ui/button";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { Textarea } from "@/components/ui/textarea";
import { motion } from "framer-motion";
import { Separator } from "@/components/ui/separator";
import { DownloadIcon } from "@radix-ui/react-icons";
import { save } from "@tauri-apps/plugin-dialog";
import { writeFile } from "@tauri-apps/plugin-fs";

function App() {
  const [input, setInput] = useState("");
  const [imageUrl, setImageUrl] = useState("");
  const [ratio, setRatio] = useState("9:16");
  const [isLoading, setIsLoading] = useState(false);
  const [downloading, setDownloading] = useState(false);
  const imageRef = useRef(null);

  const hRatio = ratio.split(":").map(Number)[0];
  const vRatio = ratio.split(":").map(Number)[1];

  const width = hRatio === 1 ? 512 : hRatio * 64;
  const height = vRatio === 1 ? 512 : vRatio * 64;

  const together = new Together({
    apiKey: import.meta.env.VITE_TOGETHER_API_KEY,
  });

  const handleGenerateImage = async () => {
    setIsLoading(true);

    try {
      console.log(width, height);
      const response: ImagesResponse = await together.images.create({
        model: "black-forest-labs/FLUX.1-schnell-Free",
        prompt: input,
        width: width,
        height: height,
        // @ts-expect-error response_format is not defined in the type
        response_format: "b64_json",
      });

      const base64Image = response.data[0].b64_json;
      const dataUrl = `data:image/png;base64,${base64Image}`;
      setImageUrl(dataUrl);
    } catch (error) {
      console.error("Error generating image:", error);
      // You might want to add some error handling UI here
    } finally {
      setIsLoading(false);
    }
  };

  const handleDownloadImage = async () => {
    if (imageUrl) {
      setDownloading(true);
      try {
        // Remove the data URL prefix
        const base64Data = imageUrl.replace(/^data:image\/\w ;base64,/, "");

        // Convert base64 to binary
        const imageBuffer = Uint8Array.from(atob(base64Data), (c) =>
          c.charCodeAt(0)
        );

        // Open a save dialog
        const filePath = await save({
          filters: [
            {
              name: "Image",
              extensions: ["png"],
            },
          ],
        });

        if (filePath) {
          // Write the file
          await writeFile(filePath, imageBuffer);
          console.log("File saved successfully");
        }
      } catch (error) {
        console.error("Error saving image:", error);
      } finally {
        setDownloading(false);
      }
    }
  };

  return (
    

AI Image Generator for "Thảo"

Generated Image

{imageUrl ? ( Generated
) : (

Your generated image will appear here

)}
); } export default App;

Build a Free AI Image Generator with ReactJS

Build a Free AI Image Generator with ReactJS

Final Thoughts

With this setup, you now have a simple ReactJS app that can generate and download AI-generated images.
Thanks for reading! If you think this post is interesting, don’t hesitate to give it a like. Happy coding!

Release Statement This article is reproduced at: https://dev.to/nhd2106/image-generator-app-for-free-2p0d?1 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3