2026-04-24 18:02:21 +08:00
|
|
|
import { resize } from "@snapotter/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-26 03:22:26 +08:00
|
|
|
import { resolveOutputFormat } from "../../lib/output-format.js";
|
2026-03-22 03:56:34 +08:00
|
|
|
import { createToolRoute } from "../tool-factory.js";
|
|
|
|
|
|
2026-05-06 23:21:45 +08:00
|
|
|
const MAX_DIMENSION = 16383;
|
|
|
|
|
|
|
|
|
|
const settingsSchema = z
|
|
|
|
|
.object({
|
|
|
|
|
width: z.number().int().positive().max(MAX_DIMENSION).optional(),
|
|
|
|
|
height: z.number().int().positive().max(MAX_DIMENSION).optional(),
|
|
|
|
|
fit: z.enum(["contain", "cover", "fill", "inside", "outside"]).default("contain"),
|
|
|
|
|
withoutEnlargement: z.boolean().default(false),
|
|
|
|
|
percentage: z.number().positive().optional(),
|
|
|
|
|
})
|
|
|
|
|
.refine((s) => s.width !== undefined || s.height !== undefined || s.percentage !== undefined, {
|
|
|
|
|
message: "At least one of width, height, or percentage is required",
|
|
|
|
|
});
|
2026-03-22 03:56:34 +08:00
|
|
|
|
|
|
|
|
export function registerResize(app: FastifyInstance) {
|
|
|
|
|
createToolRoute(app, {
|
|
|
|
|
toolId: "resize",
|
|
|
|
|
settingsSchema,
|
|
|
|
|
process: async (inputBuffer, settings, filename) => {
|
2026-04-26 03:22:26 +08:00
|
|
|
const outputFormat = await resolveOutputFormat(inputBuffer, filename);
|
2026-03-22 03:56:34 +08:00
|
|
|
const image = sharp(inputBuffer);
|
|
|
|
|
const result = await resize(image, settings);
|
2026-04-26 03:22:26 +08:00
|
|
|
const buffer = await result
|
|
|
|
|
.toFormat(outputFormat.format, { quality: outputFormat.quality })
|
|
|
|
|
.toBuffer();
|
|
|
|
|
return { buffer, filename, contentType: outputFormat.contentType };
|
2026-03-22 03:56:34 +08:00
|
|
|
},
|
|
|
|
|
});
|
|
|
|
|
}
|