Project directory structure is:
stable-diffusion-api-nodejs/
client/
└── src/
└── app/
├── layout.js
└── page.js
└── components/
└── generate-image.js
server/
├── components/
└── generate-image.js
└── server.mjs
client side:
layout.js
import { Inter } from "next/font/google";
import "./globals.css";
const inter = Inter({ subsets: ["latin"] });
export const metadata = {
title: "Stable Diffusion API",
description: "Connect To Stable Diffusion",
};
export default function RootLayout({ children }) {
return (
<html lang="en">
<body className={inter.className}>{children}</body>
</html>
);
}
page.js
import ImageGenerator from '../components/generate-image'; // Adjust the path as necessary
export default function Home() {
return (
<>
<ImageGenerator />
</>
);
}
generate_image.js
"use client"
import React, { useState } from 'react';
export default function ImageGenerator() {
const [prompt, setPrompt] = useState('');
const handleSubmit = async (event) => {
event.preventDefault();
const response = await fetch('http://localhost:4000/generate-image', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ prompt }),
});
const data = await response.json();
if (response.ok) {
console.log('Image data received:', data);
// Optionally, handle the image data (e.g., display the image)
} else {
console.error('Failed to fetch the image');
}
};
return (
<div>
<form onSubmit={handleSubmit}>
<label htmlFor="prompt">Enter a prompt for the image:</label>
<input
className='bg-gray-200'
id="prompt"
type="text"
value={prompt}
onChange={(e) => setPrompt(e.target.value)}
/>
<button className='bg-green-200' type="submit">Generate Image</button>
</form>
</div>
);
}
server side:
generate_image.js
import fetch from 'node-fetch';
import fs from 'fs';
import path from 'path';
export async function generateImage(prompt) {
const url = 'http://127.0.0.1:7860/sdapi/v1/txt2img';
const params = {
seed: 1,
steps: 30,
width: 1024,
height: 1024,
cfgScale: 7,
samplerName: "Euler a",
prompt: prompt
};
const response = await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(params)
});
if (!response.ok) {
throw new Error('Failed to generate image: ' + response.statusText);
}
const jsonResponse = await response.json();
const base64ImageData = jsonResponse.images[0];
const imageData = Buffer.from(base64ImageData, 'base64');
const timestamp = Date.now();
const imageName = `image_${timestamp}.png`;
const outputDir = 'images'; // Change this to your desired path
const outputPath = path.join(outputDir, imageName);
await fs.promises.mkdir(outputDir, { recursive: true });
await fs.promises.writeFile(outputPath, imageData);
console.log(`Image saved at: ${outputPath}`);
return { message: `Image saved at: ${outputPath}` };
}
server.mjs
import express from 'express';
import cors from 'cors'; // Use ES module import instead of require
import { generateImage } from './components/generate-image.js';
const app = express(); // Define 'app' before using it
app.use(cors()); // Use CORS middleware correctly after app is defined
app.use(express.json()); // Parse JSON payloads
const PORT = 4000;
app.post('/generate-image', async (req, res) => {
try {
const prompt = req.body.prompt; // Extract the prompt from request body
const imageResponse = await generateImage(prompt); // Generate image based on the prompt
res.json(imageResponse);
} catch (error) {
res.status(500).send(error.message); // Send error message on failure
}
});
app.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}`);
});
now i want you to make chnages in this code and convert this for img2img
http://127.0.0.1:7860/sdapi/v1/txt2img
and make changes in the front end that user will only upload the input image and press the generate button
img2imgapi syntax in stable diffusion:
{
"prompt": "",
"negative_prompt": "",
"styles": [
"string"
],
"seed": -1,
"subseed": -1,
"subseed_strength": 0,
"seed_resize_from_h": -1,
"seed_resize_from_w": -1,
"sampler_name": "string",
"scheduler": "string",
"batch_size": 1,
"n_iter": 1,
"steps": 50,
"cfg_scale": 7,
"width": 512,
"height": 512,
"restore_faces": true,
"tiling": true,
"do_not_save_samples": false,
"do_not_save_grid": false,
"eta": 0,
"denoising_strength": 0.75,
"s_min_uncond": 0,
"s_churn": 0,
"s_tmax": 0,
"s_tmin": 0,
"s_noise": 0,
"override_settings": {},
"override_settings_restore_afterwards": true,
"refiner_checkpoint": "string",
"refiner_switch_at": 0,
"disable_extra_networks": false,
"firstpass_image": "string",
"comments": {},
"init_images": [
"string"
],
"resize_mode": 0,
"image_cfg_scale": 0,
"mask": "string",
"mask_blur_x": 4,
"mask_blur_y": 4,
"mask_blur": 0,
"mask_round": true,
"inpainting_fill": 0,
"inpaint_full_res": true,
"inpaint_full_res_padding": 0,
"inpainting_mask_invert": 0,
"initial_noise_multiplier": 0,
"latent_mask": "string",
"force_task_id": "string",
"sampler_index": "Euler",
"include_init_images": false,
"script_name": "string",
"script_args": [],
"send_images": true,
"save_images": false,
"alwayson_scripts": {},
"infotext": "string"
}
these are the parameters to set only along with user input image:
prompt: Transform your imagination into a 3D cartoon masterpiece, with endless possibilities for unique and diverse characters and settings, match face features to input image, modern disney style
neg_prompt:Blurry face, missing facial features, deformed face, asymmetrical eyes, unnatural skin color, bad anatomy, extra limbs, missing eyes, lack of facial depth, distorted facial structure, uneven or misplaced facial elements, inconsistent lighting on face, and artifacts or distortions
sampling method: DPM ++2M Karras
sampling steps: 50
width: 756
height: 1008
cfg scale: 14
Denoising strength: 0.3
seed:1637648563