How to Build an AI Image Generator Using Puter.js
Want to create stunning AI-generated images from text prompts? In this post, you'll learn how to build a responsive, high-quality image generator using Puter.js, a lightweight AI tool for developers. We’ll walk through the entire process step-by-step and provide a full HTML code example you can use right away.
What You’ll Learn
- How to use
puter.ai.txt2imgto convert text prompts into images - How to create an elegant UI with prompt input and image preview
- How to add a download button to save AI images
- How to monetize your app or tool with ads
Live Code (Copy & Use)
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" lang="en">
<head>
<meta charset="UTF-8" />
<title>AI Image Generator</title>
<script src="https://js.puter.com/v2/"></script>
<style type="text/css">
/* UI styling */
body {
font-family: Arial, sans-serif;
background: #1e1e2f;
color: #fff;
display: flex;
flex-direction: column;
align-items: center;
padding: 40px;
margin: 0;
}
input, button {
padding: 12px;
margin: 10px;
font-size: 16px;
border-radius: 8px;
border: none;
}
button {
background-color: #00bfa6;
color: white;
}
#image-container {
margin-top: 30px;
}
img {
max-width: 100%;
border-radius: 12px;
margin-top: 20px;
}
</style>
</head>
<body>
<h1>AI Image Generator</h1>
<input type="text" id="prompt" placeholder="Enter your image prompt here" />
<button onclick="generateImage()">Generate Image</button>
<div id="image-container"></div>
<script type="text/javascript">
function generateImage() {
var prompt = document.getElementById("prompt").value.trim();
if (!prompt) return alert("Enter a prompt.");
var container = document.getElementById("image-container");
container.innerHTML = "Generating image...";
puter.ai.txt2img(prompt)
.then(function(image) {
container.innerHTML = "";
container.appendChild(image);
var downloadBtn = document.createElement("button");
downloadBtn.textContent = "Download Image";
downloadBtn.onclick = function() {
var link = document.createElement("a");
link.href = image.src;
link.download = "ai-generated.png";
link.click();
};
container.appendChild(downloadBtn);
})
.catch(function(err) {
container.innerHTML = "Failed to generate image.";
});
}
</script>
</body>
</html>
Why Use Puter.js?
Puter.js makes it incredibly easy to integrate AI capabilities directly into any web application. With just a single function call, you can generate beautiful images, automate tasks, or add powerful machine learning features — all from the browser.
Final Thoughts
Whether you're building a creative tool, a productivity app, or a fun side project, this Puter.js-powered image generator is a great way to learn and showcase the power of browser-based AI. Don’t forget to explore other APIs from Puter to supercharge your projects!
Comments
Post a Comment