开发者们大家好,
今天,我将向您展示如何使用 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中文网其他相关文章!

不同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广泛应用于网页交互、单页面应用和服务器端开发,极大地提升了用户体验和跨平台开发的灵活性。

Python更适合数据科学和机器学习,JavaScript更适合前端和全栈开发。 1.Python以简洁语法和丰富库生态着称,适用于数据分析和Web开发。 2.JavaScript是前端开发核心,Node.js支持服务器端编程,适用于全栈开发。


热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

AI Hentai Generator
免费生成ai无尽的。

热门文章

热工具

螳螂BT
Mantis是一个易于部署的基于Web的缺陷跟踪工具,用于帮助产品缺陷跟踪。它需要PHP、MySQL和一个Web服务器。请查看我们的演示和托管服务。

MinGW - 适用于 Windows 的极简 GNU
这个项目正在迁移到osdn.net/projects/mingw的过程中,你可以继续在那里关注我们。MinGW:GNU编译器集合(GCC)的本地Windows移植版本,可自由分发的导入库和用于构建本地Windows应用程序的头文件;包括对MSVC运行时的扩展,以支持C99功能。MinGW的所有软件都可以在64位Windows平台上运行。

ZendStudio 13.5.1 Mac
功能强大的PHP集成开发环境

EditPlus 中文破解版
体积小,语法高亮,不支持代码提示功能

禅工作室 13.0.1
功能强大的PHP集成开发环境