Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

Sorry, you do not have permission to ask a question, You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please type your username.

Please type your E-Mail.

Please choose an appropriate title for the post.

Please choose the appropriate section so your post can be easily searched.

Please choose suitable Keywords Ex: post, video.

Browse

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Logo Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Logo

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Navigation

  • Home
  • About Us
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • About Us
  • Contact Us
Home/ Questions/Q 7898

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Latest Questions

Author
  • 60k
Author
Asked: November 28, 20242024-11-28T08:06:08+00:00 2024-11-28T08:06:08+00:00

Build a Free AI Image Generator with ReactJS

  • 60k

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 
Enter fullscreen mode Exit fullscreen mode

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<HTMLImageElement>(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 (     <div className="bg-gradient-to-br from-indigo-100 via-purple-100 to-pink-100 p-10 md:p-8">       <motion.div         initial={{ opacity: 0, y: 20 }}         animate={{ opacity: 1, y: 0 }}         transition={{ duration: 0.5 }}         className="max-w-7xl mx-auto bg-white/80 backdrop-blur-sm rounded-3xl shadow-2xl overflow-y-auto"       >         <div className="flex flex-col md:flex-row h-[calc(100vh-4rem)]">           <div className="w-full md:w-1/2 p-6 flex flex-col">             <h2 className="text-3xl font-bold mb-6 text-gray-800 bg-clip-text text-transparent bg-gradient-to-r from-indigo-500 to-purple-600">               AI Image Generator             </h2>             <div className="flex-grow flex flex-col justify-center">               <Textarea                 value={input}                 onChange={(e) => setInput(e.target.value)}                 placeholder="Describe the image you want to create..."                 className="mb-4 resize-none rounded-2xl border-2 border-indigo-200 focus:border-indigo-500 transition-colors"                 rows={5}               />               <div className="flex items-center space-x-4 mb-6">                 <Select value={ratio} onValueChange={setRatio}>                   <SelectTrigger className="w-full rounded-full border-2 border-purple-200 focus:border-purple-500 transition-colors">                     <SelectValue placeholder="Select ratio" />                   </SelectTrigger>                   <SelectContent>                     <SelectItem value="1:1">1:1</SelectItem>                     <SelectItem value="4:3">4:3</SelectItem>                     <SelectItem value="16:9">16:9</SelectItem>                     <SelectItem value="3:4">3:4</SelectItem>                     <SelectItem value="9:16">9:16</SelectItem>                   </SelectContent>                 </Select>                  <Button                   onClick={handleGenerateImage}                   disabled={isLoading}                   className="flex-shrink-0 bg-gradient-to-r from-indigo-500 to-purple-600 hover:from-indigo-600 hover:to-purple-700 text-white font-semibold py-2 px-4 rounded-full transition-all duration-300 ease-in-out transform hover:scale-105"                 >                  {isLoading ? "Generating..." : "Generate Image"}                 </Button>               </div>             </div>           </div>           <Separator orientation="vertical" className="hidden md:block" />           <div className="w-full md:w-1/2 p-6 bg-gray-50/50 flex flex-col">             <h2 className="text-3xl font-bold mb-6 text-gray-800 bg-clip-text text-transparent bg-gradient-to-r from-purple-500 to-pink-600">               Generated Image             </h2>             {imageUrl ? (               <motion.div                 initial={{ opacity: 0, scale: 0.9 }}                 animate={{ opacity: 1, scale: 1 }}                 transition={{ duration: 0.5 }}                 className="flex-grow flex flex-col items-center justify-center"               >                 <img                   ref={imageRef}                   src={imageUrl}                   alt="Generated"                   className="max-w-full max-h-[60vh] object-contain rounded-lg shadow-lg mb-6"                 />                 <div className="flex space-x-4">                   <Button                     onClick={handleDownloadImage}                     className="rounded-full bg-gradient-to-r from-purple-500 to-pink-600 hover:from-purple-600 hover:to-pink-700 text-white font-semibold py-2 px-4 transition-all duration-300 ease-in-out transform hover:scale-105 flex items-center space-x-2"                   >                     {downloading ? "Downloading..." : <DownloadIcon />}                     <span>Download</span>                   </Button>                 </div>               </motion.div>             ) : (               <div className="flex-grow flex items-center justify-center text-gray-400">                 <p className="text-lg italic">                   Your generated image will appear here                 </p>               </div>             )}           </div>         </div>       </motion.div>     </div>   ); }  export default App; 
Enter fullscreen mode Exit fullscreen mode

UI of Image generator

Test to create the image

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!

aijavascriptreactwebdev
  • 0 0 Answers
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

Sidebar

Ask A Question

Stats

  • Questions 4k
  • Answers 0
  • Best Answers 0
  • Users 1k
  • Popular
  • Answers
  • Author

    How to ensure that all the routes on my Symfony ...

    • 0 Answers
  • Author

    Insights into Forms in Flask

    • 0 Answers
  • Author

    Kick Start Your Next Project With Holo Theme

    • 0 Answers

Top Members

Samantha Carter

Samantha Carter

  • 0 Questions
  • 20 Points
Begginer
Ella Lewis

Ella Lewis

  • 0 Questions
  • 20 Points
Begginer
Isaac Anderson

Isaac Anderson

  • 0 Questions
  • 20 Points
Begginer

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help

Footer

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise

Querify Question Shop: Explore, ask, and connect. Join our vibrant Q&A community today!

About Us

  • About Us
  • Contact Us
  • All Users

Legal Stuff

  • Terms of Use
  • Privacy Policy
  • Cookie Policy

Help

  • Knowledge Base
  • Support

Follow

© 2022 Querify Question. All Rights Reserved

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.