feat: backend route for removing backgrounds from images with imgly

This commit is contained in:
theoleuthardt 2025-02-22 14:29:36 +01:00
parent 91125204b5
commit e368155cdb
4 changed files with 1580 additions and 2 deletions

View file

@ -0,0 +1,43 @@
import { FastifyInstance, FastifyReply, FastifyRequest } from "fastify";
import { Config, removeBackground } from "@imgly/background-removal-node";
import sharp from "sharp";
export async function removeBG(app: FastifyInstance) {
app.post(
"/api/remove-bg",
async (request: FastifyRequest, reply: FastifyReply) => {
try {
const parts = request.parts();
let fileBuffer: Buffer | null = null;
for await (const part of parts) {
if (part.type === "file") {
fileBuffer = await part.toBuffer();
}
}
if (!fileBuffer) {
return reply.status(400).send({ error: "No file uploaded!" });
}
console.log("Received file, buffer length:", fileBuffer.length);
const rightFileBuffer = await sharp(fileBuffer)
.toFormat("png")
.toBuffer();
console.log("Converted file:", rightFileBuffer);
const convertedBuffer = await removeBackground(rightFileBuffer);
reply
.header("Content-Type", "image/png")
.header("Content-Disposition", `attachment; filename="converted.png"`)
.status(200)
.send(convertedBuffer);
} catch (error) {
console.error("Convert error:", error);
reply.status(500).send({ error: "Error while converting!" });
}
},
);
}