2026-04-24 18:02:21 +08:00
|
|
|
import { crop } 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-06 12:53:53 +08:00
|
|
|
import { resolveOutputFormat } from "../../lib/output-format.js";
|
2026-03-22 03:56:34 +08:00
|
|
|
import { createToolRoute } from "../tool-factory.js";
|
|
|
|
|
|
|
|
|
|
const settingsSchema = z.object({
|
2026-04-11 14:47:46 +08:00
|
|
|
left: z.number().min(0),
|
|
|
|
|
top: z.number().min(0),
|
|
|
|
|
width: z.number().positive(),
|
|
|
|
|
height: z.number().positive(),
|
|
|
|
|
unit: z.enum(["px", "percent"]).optional(),
|
2026-03-22 03:56:34 +08:00
|
|
|
});
|
|
|
|
|
|
|
|
|
|
export function registerCrop(app: FastifyInstance) {
|
|
|
|
|
createToolRoute(app, {
|
|
|
|
|
toolId: "crop",
|
|
|
|
|
settingsSchema,
|
|
|
|
|
process: async (inputBuffer, settings, filename) => {
|
2026-04-06 12:53:53 +08:00
|
|
|
const outputFormat = await resolveOutputFormat(inputBuffer, filename);
|
2026-03-22 03:56:34 +08:00
|
|
|
const image = sharp(inputBuffer);
|
|
|
|
|
const result = await crop(image, settings);
|
2026-04-06 12:53:53 +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
|
|
|
},
|
|
|
|
|
});
|
|
|
|
|
}
|