-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
70 lines (56 loc) · 1.94 KB
/
index.js
File metadata and controls
70 lines (56 loc) · 1.94 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
const express = require("express");
const multer = require("multer");
const cors = require("cors");
const fs = require("fs");
const path = require("path");
const { removeBackground } = require("@imgly/background-removal-node");
const app = express();
const port = process.env.PORT || 3000;
// Enable CORS
app.use(cors());
// Configure multer for memory storage
const storage = multer.memoryStorage();
const upload = multer({ storage: storage });
// Create uploads directory if it doesn't exist
const uploadsDir = path.join(__dirname, "uploads");
if (!fs.existsSync(uploadsDir)) {
fs.mkdirSync(uploadsDir, { recursive: true });
}
// Serve static files
app.use(express.static("public"));
// Simple home route
app.get("/", (req, res) => {
res.send(
"Background Removal API - Use POST /remove-background to process images"
);
});
// Background removal endpoint
app.post("/remove-background", upload.single("image"), async (req, res) => {
try {
if (!req.file) {
return res.status(400).json({ error: "No image file uploaded" });
}
// Save the uploaded file temporarily
const inputPath = path.join(uploadsDir, `input-${Date.now()}.png`);
fs.writeFileSync(inputPath, req.file.buffer);
// Process the image with background removal
const outputBlob = await removeBackground(inputPath);
// Convert Blob to Buffer
const arrayBuffer = await outputBlob.arrayBuffer();
const outputBuffer = Buffer.from(arrayBuffer);
// Convert Buffer to base64 and add data URI prefix
const base64Image = `data:image/png;base64,${outputBuffer.toString(
"base64"
)}`;
// Clean up temporary file
fs.unlinkSync(inputPath);
// Return the base64 string
res.json({ base64Image });
} catch (error) {
console.error("Error processing image:", error);
res.status(500).json({ error: "Failed to process image" });
}
});
app.listen(port, () => {
console.log(`Server running at http://localhost:${port}`);
});