開發者們大家好,
今天,我將向您展示如何使用 ReactJS 創建圖像生成器,並且完全可以免費使用,這要感謝黑森林實驗室和 Together AI。
第 1 步:設定項目
在本教程中,我們將使用 Vite 來初始化應用程式並使用 Shadcn 來初始化 UI。我假設您已經設定了專案並安裝了 Shadcn。
第 2 步:安裝 Together AI 軟體包
我們需要安裝 Together AI 套件才能存取免費的 Flux 模型來產生映像。
在終端機中執行以下命令
npm i together-ai
第 3 步:建立使用者介面
現在,讓我們為我們的應用程式建立 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: y: animate="{{" transition="{{" duration: 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"></selectvalue> </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 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> </textarea> </div> </div> <separator orientation="vertical" classname="hidden md:block"></separator> <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: scale: animate="{{" transition="{{" duration: classname="flex-grow flex flex-col items-center justify-center"> <img src="/static/imghwm/default1.png" data-src="https://img.php.cn/upload/article/000/000/000/172896621558474.jpg?x-oss-process=image/resize,p_40" class="lazy" ref="{imageRef}" 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></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; </htmlimageelement>
最後的想法
透過此設置,您現在擁有一個簡單的 ReactJS 應用程序,可以產生和下載 AI 生成的圖像。
感謝您的閱讀!如果您覺得這篇文章有趣,請不要猶豫,按個讚。快樂編碼!
以上是使用 ReactJS 建立免費的 AI 圖像生成器的詳細內容。更多資訊請關注PHP中文網其他相關文章!

從C/C 轉向JavaScript需要適應動態類型、垃圾回收和異步編程等特點。 1)C/C 是靜態類型語言,需手動管理內存,而JavaScript是動態類型,垃圾回收自動處理。 2)C/C 需編譯成機器碼,JavaScript則為解釋型語言。 3)JavaScript引入閉包、原型鍊和Promise等概念,增強了靈活性和異步編程能力。

不同JavaScript引擎在解析和執行JavaScript代碼時,效果會有所不同,因為每個引擎的實現原理和優化策略各有差異。 1.詞法分析:將源碼轉換為詞法單元。 2.語法分析:生成抽象語法樹。 3.優化和編譯:通過JIT編譯器生成機器碼。 4.執行:運行機器碼。 V8引擎通過即時編譯和隱藏類優化,SpiderMonkey使用類型推斷系統,導致在相同代碼上的性能表現不同。

JavaScript在現實世界中的應用包括服務器端編程、移動應用開發和物聯網控制:1.通過Node.js實現服務器端編程,適用於高並發請求處理。 2.通過ReactNative進行移動應用開發,支持跨平台部署。 3.通過Johnny-Five庫用於物聯網設備控制,適用於硬件交互。

我使用您的日常技術工具構建了功能性的多租戶SaaS應用程序(一個Edtech應用程序),您可以做同樣的事情。 首先,什麼是多租戶SaaS應用程序? 多租戶SaaS應用程序可讓您從唱歌中為多個客戶提供服務

本文展示了與許可證確保的後端的前端集成,並使用Next.js構建功能性Edtech SaaS應用程序。 前端獲取用戶權限以控制UI的可見性並確保API要求遵守角色庫

JavaScript是現代Web開發的核心語言,因其多樣性和靈活性而廣泛應用。 1)前端開發:通過DOM操作和現代框架(如React、Vue.js、Angular)構建動態網頁和單頁面應用。 2)服務器端開發:Node.js利用非阻塞I/O模型處理高並發和實時應用。 3)移動和桌面應用開發:通過ReactNative和Electron實現跨平台開發,提高開發效率。

JavaScript的最新趨勢包括TypeScript的崛起、現代框架和庫的流行以及WebAssembly的應用。未來前景涵蓋更強大的類型系統、服務器端JavaScript的發展、人工智能和機器學習的擴展以及物聯網和邊緣計算的潛力。

JavaScript是現代Web開發的基石,它的主要功能包括事件驅動編程、動態內容生成和異步編程。 1)事件驅動編程允許網頁根據用戶操作動態變化。 2)動態內容生成使得頁面內容可以根據條件調整。 3)異步編程確保用戶界面不被阻塞。 JavaScript廣泛應用於網頁交互、單頁面應用和服務器端開發,極大地提升了用戶體驗和跨平台開發的靈活性。


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

AI Hentai Generator
免費產生 AI 無盡。

熱門文章

熱工具

Dreamweaver CS6
視覺化網頁開發工具

MantisBT
Mantis是一個易於部署的基於Web的缺陷追蹤工具,用於幫助產品缺陷追蹤。它需要PHP、MySQL和一個Web伺服器。請查看我們的演示和託管服務。

DVWA
Damn Vulnerable Web App (DVWA) 是一個PHP/MySQL的Web應用程序,非常容易受到攻擊。它的主要目標是成為安全專業人員在合法環境中測試自己的技能和工具的輔助工具,幫助Web開發人員更好地理解保護網路應用程式的過程,並幫助教師/學生在課堂環境中教授/學習Web應用程式安全性。 DVWA的目標是透過簡單直接的介面練習一些最常見的Web漏洞,難度各不相同。請注意,該軟體中

MinGW - Minimalist GNU for Windows
這個專案正在遷移到osdn.net/projects/mingw的過程中,你可以繼續在那裡關注我們。 MinGW:GNU編譯器集合(GCC)的本機Windows移植版本,可自由分發的導入函式庫和用於建置本機Windows應用程式的頭檔;包括對MSVC執行時間的擴展,以支援C99功能。 MinGW的所有軟體都可以在64位元Windows平台上運作。

SecLists
SecLists是最終安全測試人員的伙伴。它是一個包含各種類型清單的集合,這些清單在安全評估過程中經常使用,而且都在一個地方。 SecLists透過方便地提供安全測試人員可能需要的所有列表,幫助提高安全測試的效率和生產力。清單類型包括使用者名稱、密碼、URL、模糊測試有效載荷、敏感資料模式、Web shell等等。測試人員只需將此儲存庫拉到新的測試機上,他就可以存取所需的每種類型的清單。