2026-03-25 09:27:12 +08:00
|
|
|
import { extname } from "node:path";
|
2026-04-14 20:55:42 +08:00
|
|
|
import { convert } from "@ashim/image-engine";
|
2026-03-25 09:27:12 +08:00
|
|
|
import type { FastifyInstance } from "fastify";
|
|
|
|
|
import sharp from "sharp";
|
2026-03-22 03:56:34 +08:00
|
|
|
import { z } from "zod";
|
2026-04-04 21:33:48 +08:00
|
|
|
import { encodeHeic } from "../../lib/heic-converter.js";
|
2026-03-30 11:37:09 +08:00
|
|
|
import { isSvgBuffer } from "../../lib/svg-sanitize.js";
|
2026-03-22 03:56:34 +08:00
|
|
|
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",
|
2026-04-04 21:33:48 +08:00
|
|
|
heic: "image/heic",
|
2026-04-11 23:27:44 +08:00
|
|
|
heif: "image/heif",
|
2026-03-22 03:56:34 +08:00
|
|
|
};
|
|
|
|
|
|
|
|
|
|
const settingsSchema = z.object({
|
2026-04-11 23:27:44 +08:00
|
|
|
format: z.enum(["jpg", "png", "webp", "avif", "tiff", "gif", "heic", "heif"]),
|
2026-03-22 03:56:34 +08:00
|
|
|
quality: z.number().min(1).max(100).optional(),
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
export function registerConvert(app: FastifyInstance) {
|
|
|
|
|
createToolRoute(app, {
|
|
|
|
|
toolId: "convert",
|
|
|
|
|
settingsSchema,
|
|
|
|
|
process: async (inputBuffer, settings, filename) => {
|
2026-03-30 11:37:09 +08:00
|
|
|
const sharpOpts = isSvgBuffer(inputBuffer) ? { density: 300 } : undefined;
|
|
|
|
|
const image = sharp(inputBuffer, sharpOpts);
|
2026-04-04 21:33:48 +08:00
|
|
|
|
|
|
|
|
let buffer: Buffer;
|
2026-04-11 23:27:44 +08:00
|
|
|
if (settings.format === "heic" || settings.format === "heif") {
|
2026-04-04 21:33:48 +08:00
|
|
|
// Sharp cannot encode HEVC. Convert to PNG first, then use heif-enc.
|
|
|
|
|
const pngBuffer = await image.png().toBuffer();
|
|
|
|
|
buffer = await encodeHeic(pngBuffer, settings.quality);
|
|
|
|
|
} else {
|
|
|
|
|
const result = await convert(image, settings);
|
|
|
|
|
buffer = await result.toBuffer();
|
|
|
|
|
}
|
2026-03-22 03:56:34 +08:00
|
|
|
|
|
|
|
|
// 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 };
|
|
|
|
|
},
|
|
|
|
|
});
|
|
|
|
|
}
|