Add image processing route with color extraction using node-vibrant

This commit is contained in:
wont-stream 2025-04-05 02:29:23 -04:00
parent 7b30305ac8
commit 5e5174df5d
3 changed files with 40 additions and 1 deletions

1
.gitignore vendored
View file

@ -1,3 +1,4 @@
/node_modules
bun.lock
.env
logs/

View file

@ -28,6 +28,7 @@
"typescript": "^5.8.2"
},
"dependencies": {
"ejs": "^3.1.10"
"ejs": "^3.1.10",
"node-vibrant": "^4.0.3"
}
}

37
src/routes/img.ts Normal file
View file

@ -0,0 +1,37 @@
import { Vibrant } from "node-vibrant/node";
const routeDef: RouteDef = {
method: "GET",
accepts: "*/*",
returns: "application/json",
};
async function handler(request: ExtendedRequest): Promise<Response> {
const req = await fetch(request.query.url);
if (!req.ok) {
return Response.json({ error: "Failed to fetch image" }, { status: 500 });
}
const type = req.headers.get("content-type")
if (!type?.includes("image/")) {
return Response.json({ error: "Not an image" }, { status: 400 });
}
const imageBuffer = await req.arrayBuffer()
const colors = await Vibrant.from(Buffer.from(imageBuffer)).getPalette();
return new Response(Bun.gzipSync(JSON.stringify({
img: `data:${type};base64,${Buffer.from(imageBuffer).toString("base64")}`,
colors,
})), {
headers: {
"Content-Type": "application/json",
"Content-Encoding": "gzip",
"Cache-Control": "public, max-age=31536000, immutable",
}
})
}
export { handler, routeDef };