ReactJS로 무료 AI 이미지 생성기 구축

Patricia Arquette
풀어 주다: 2024-10-15 12:23:30
원래의
694명이 탐색했습니다.

개발자 여러분, 안녕하세요.
오늘은 ReactJS를 사용하여 이미지 생성기를 만드는 방법을 보여드리겠습니다. Black Forest Labs와 Together AI 덕분에 모두 무료로 사용할 수 있습니다.

1단계: 프로젝트 설정

이 튜토리얼에서는 Vite를 사용하여 앱을 초기화하고 Shadcn을 UI로 사용하겠습니다. 이미 프로젝트를 설정하고 Shadcn을 설치했다고 가정하겠습니다.

2단계: Together AI 패키지 설치

이미지 생성을 위한 무료 Flux 모델에 액세스하려면 Together AI 패키지를 설치해야 합니다.
터미널에서 다음 명령을 실행하세요

npm i together-ai
로그인 후 복사

3단계: UI 구축

이제 앱의 UI를 만들어 보겠습니다. 다음은 이미지 생성기 구성 요소의 전체 코드입니다. 여기에는 프롬프트에 대한 텍스트 입력이 포함됩니다. 종횡비 선택을 위한 드롭다운입니다.
"black-forest-labs/FLUX.1-schnell-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 for "Thảo"
            </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;
로그인 후 복사

Build a Free AI Image Generator with ReactJS

Build a Free AI Image Generator with ReactJS

최종 생각

이 설정을 통해 이제 AI 생성 이미지를 생성하고 다운로드할 수 있는 간단한 ReactJS 앱을 갖게 되었습니다.
읽어주셔서 감사합니다! 이 게시물이 흥미롭다고 생각하시면 주저하지 말고 좋아요를 눌러주세요. 즐거운 코딩하세요!

위 내용은 ReactJS로 무료 AI 이미지 생성기 구축의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

원천:dev.to
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
저자별 최신 기사
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!