2026-03-25 09:27:12 +08:00
|
|
|
import { extname } from "node:path";
|
|
|
|
|
import { convert } from "@stirling-image/image-engine";
|
|
|
|
|
import type { FastifyInstance } from "fastify";
|
|
|
|
|
import sharp from "sharp";
|
2026-03-22 03:56:34 +08:00
|
|
|
import { z } from "zod";
|
|
|
|
|
import { createToolRoute } from "../tool-factory.js";
|
|
|
|
|
|
|
|
|
|
const FORMAT_CONTENT_TYPES: Record<string, string> = {
|
|
|
|
|
jpg: "image/jpeg",
|
|
|
|
|
png: "image/png",
|
|
|
|
|
webp: "image/webp",
|
|
|
|
|
avif: "image/avif",
|
|
|
|
|
tiff: "image/tiff",
|
|
|
|
|
gif: "image/gif",
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
const settingsSchema = z.object({
|
|
|
|
|
format: z.enum(["jpg", "png", "webp", "avif", "tiff", "gif"]),
|
|
|
|
|
quality: z.number().min(1).max(100).optional(),
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
export function registerConvert(app: FastifyInstance) {
|
|
|
|
|
createToolRoute(app, {
|
|
|
|
|
toolId: "convert",
|
|
|
|
|
settingsSchema,
|
|
|
|
|
process: async (inputBuffer, settings, filename) => {
|
|
|
|
|
const image = sharp(inputBuffer);
|
|
|
|
|
const result = await convert(image, settings);
|
|
|
|
|
const buffer = await result.toBuffer();
|
|
|
|
|
|
|
|
|
|
// Change filename extension to match the output format
|
|
|
|
|
const ext = extname(filename);
|
|
|
|
|
const baseName = ext ? filename.slice(0, -ext.length) : filename;
|
|
|
|
|
const outputFilename = `${baseName}.${settings.format}`;
|
|
|
|
|
|
2026-03-25 09:27:12 +08:00
|
|
|
const contentType = FORMAT_CONTENT_TYPES[settings.format] || "application/octet-stream";
|
2026-03-22 03:56:34 +08:00
|
|
|
|
|
|
|
|
return { buffer, filename: outputFilename, contentType };
|
|
|
|
|
},
|
|
|
|
|
});
|
|
|
|
|
}
|