mirror of
https://github.com/snapotter-hq/SnapOtter.git
synced 2026-08-03 07:46:42 +02:00
feat(gif-tools): SOTA upgrade with 6 processing modes (#52)
* feat(find-duplicates): upgrade to 128-bit dHash with metadata and thumbnails * feat(find-duplicates): add custom-results display mode and duplicate store * feat(find-duplicates): add results overview grid and detail comparison view * feat(find-duplicates): overhaul settings with sensitivity presets and download actions * feat(find-duplicates): update i18n description * chore: replace jsqr with zxing-wasm for barcode reading * feat(barcode-read): rewrite backend with zxing-wasm for all barcode types * feat(barcode-read): rewrite frontend with multi-file, results table, progress, export - Multi-file sequential processing with per-file progress - Structured results table with type badges and copy per-result - Copy All and Export CSV functionality - Thorough scan toggle (maps to tryHarder in zxing-wasm) - Before/after view shows annotated image with bounding boxes - Updated tool description in constants and i18n * feat(stitch): update tool name and description for redesign * feat(stitch): add grid layout, alignment, border, radius, quality, and new resize modes * feat(stitch): redesign settings UI with grid, alignment, border, radius, quality * test(stitch): add stitch to e2e tool navigation suite * feat(vectorize): redesign with dual-engine backend and preset-driven UI - Backend: potrace for B&W, VTracer (@neplex/vectorizer) for full-color vectorization - Frontend: 5 presets (logo, illustration, photo, sketch, custom) - Settings: color precision, gradient step, detail, smoothing, corner threshold, invert - Updated OpenAPI spec and i18n description * feat(border): redesign with presets, shadow, padding color, swatches - Add 8 one-click presets (Clean White, Gallery Black, Shadow, Rounded, Polaroid, Vintage, Minimal, Cinematic) - Implement proper shadow rendering with blur, offset X/Y, color, opacity - Add padding color control (was hardcoded white) - Add color swatches for quick color selection - Wrap in form for Enter key submission - Add smart validation (requires at least one effect active) - Align frontend/backend slider ranges - Organize UI with sections and collapsible shadow toggle * feat(split): overhaul image splitting with live grid overlay and tile preview - Add interactive-split display mode with SplitCanvas component - Live SVG grid overlay on uploaded image showing split boundaries - Two split modes: Grid (NxM) and Tile Size (px dimensions) - 9 grid presets (2x1, 1x2, 2x2, 3x1, 1x3, 3x3, 2x3, 3x2, 4x4) - Output format selection (original/PNG/JPG/WebP) with quality slider - Post-split tile preview thumbnails with individual download - Download All as ZIP button - HEIC/HEIF preview with loading spinner - Backend: tile-size mode, output format conversion, quality control - Zustand store for split state management * feat(split): rewrite backend and frontend settings Backend: tile-size mode, output format conversion, quality control. Frontend: split modes, presets, format selector, tile preview grid. * feat(border): add live CSS preview and remove before/after slider - Add imageWrapperStyle prop to ImageViewer for live border preview - Add onImageStyle callback through tool-page to settings components - Change border displayMode to no-comparison (no slider) - BorderControls sends live CSS styles (border, padding, radius, shadow) - Preview updates instantly as user adjusts sliders or clicks presets * fix: repair i18n file corrupted by formatter during merge conflict resolution * feat(border): enable live CSS preview in right pane as settings change * fix(border): keep CSS preview visible after processing for WYSIWYG consistency * chore(gif-tools): scaffold for SOTA upgrade - Add animated GIF test fixture (3 frames, 100x100) - Update tool description to reflect new capabilities - Add fflate dependency to API for ZIP creation * feat(gif-tools): rewrite backend with 6 processing modes Modes: resize (with percentage), optimize (colors/dither/effort), speed (delay manipulation), reverse (frame reorder), extract (single/range/all with ZIP), rotate (90/180/270 + flip). Adds /api/v1/tools/gif-tools/info metadata endpoint. * test(gif-tools): add integration tests for all 6 modes Tests metadata endpoint, resize (pixel + percentage), optimize, speed, reverse, extract (single/range/all), and rotate (angle + flip). Fix animated.gif fixture to be a real 3-frame animation (was a single 100x300 frame). Fix reverse and rotate modes to process frames individually and reassemble via GIF binary concatenation, since Sharp 0.33.x loses page-height metadata when reconstructing from raw pixel data. * feat(gif-tools): rewrite frontend with tabbed 6-mode UI - useGifInfo hook for metadata (frame count, dimensions, duration) - Info bar showing GIF properties - 3x2 mode grid: Resize, Optimize, Speed, Reverse, Extract, Rotate - Animation modes disabled for static images - Loop control (infinite/once/custom) - Batch processing support * test(gif-tools): add to representative tools in e2e suite --------- Co-authored-by: Siddharth Kumar Sah <siddharth123sk@gmail.com>
This commit is contained in:
co-authored by
Siddharth Kumar Sah
parent
4e99150a08
commit
a1e11dff74
@@ -12,14 +12,19 @@ import { createWorkspace } from "../../lib/workspace.js";
|
||||
const MAX_CANVAS_PIXELS = 100_000_000;
|
||||
|
||||
const settingsSchema = z.object({
|
||||
direction: z.enum(["horizontal", "vertical"]).default("horizontal"),
|
||||
resize: z.enum(["fit", "original"]).default("fit"),
|
||||
gap: z.number().min(0).max(100).default(0),
|
||||
direction: z.enum(["horizontal", "vertical", "grid"]).default("horizontal"),
|
||||
gridColumns: z.number().int().min(2).max(10).default(2),
|
||||
resizeMode: z.enum(["fit", "original", "stretch", "crop"]).default("fit"),
|
||||
alignment: z.enum(["start", "center", "end"]).default("center"),
|
||||
gap: z.number().min(0).max(200).default(0),
|
||||
border: z.number().min(0).max(50).default(0),
|
||||
cornerRadius: z.number().min(0).max(50).default(0),
|
||||
backgroundColor: z
|
||||
.string()
|
||||
.regex(/^#[0-9a-fA-F]{6}$/)
|
||||
.default("#FFFFFF"),
|
||||
format: z.enum(["png", "jpeg", "webp"]).default("png"),
|
||||
quality: z.number().min(1).max(100).default(90),
|
||||
});
|
||||
|
||||
function parseHexColor(hex: string): { r: number; g: number; b: number } {
|
||||
@@ -30,6 +35,12 @@ function parseHexColor(hex: string): { r: number; g: number; b: number } {
|
||||
};
|
||||
}
|
||||
|
||||
interface PreparedImage {
|
||||
buffer: Buffer;
|
||||
width: number;
|
||||
height: number;
|
||||
}
|
||||
|
||||
export function registerStitch(app: FastifyInstance) {
|
||||
app.post("/api/v1/tools/stitch", async (request, reply) => {
|
||||
const files: Array<{ buffer: Buffer; filename: string }> = [];
|
||||
@@ -65,7 +76,6 @@ export function registerStitch(app: FastifyInstance) {
|
||||
return reply.status(400).send({ error: "At least 2 images are required for stitching" });
|
||||
}
|
||||
|
||||
// Validate all files and decode HEIC/HEIF
|
||||
for (const file of files) {
|
||||
const validation = await validateImageBuffer(file.buffer);
|
||||
if (!validation.valid) {
|
||||
@@ -89,7 +99,6 @@ export function registerStitch(app: FastifyInstance) {
|
||||
}
|
||||
|
||||
try {
|
||||
// Read metadata for all images
|
||||
const imageMetas = await Promise.all(
|
||||
files.map(async (file) => {
|
||||
const meta = await sharp(file.buffer).metadata();
|
||||
@@ -101,85 +110,80 @@ export function registerStitch(app: FastifyInstance) {
|
||||
}),
|
||||
);
|
||||
|
||||
// Resize images if needed
|
||||
const isHorizontal = settings.direction === "horizontal";
|
||||
let prepared: Array<{ buffer: Buffer; width: number; height: number }>;
|
||||
const isGrid = settings.direction === "grid";
|
||||
|
||||
if (settings.resize === "fit") {
|
||||
if (isHorizontal) {
|
||||
// Find min height, scale taller images down
|
||||
const minHeight = Math.min(...imageMetas.map((m) => m.height));
|
||||
prepared = await Promise.all(
|
||||
imageMetas.map(async (img) => {
|
||||
if (img.height > minHeight) {
|
||||
const scaledWidth = Math.round((img.width * minHeight) / img.height);
|
||||
const resized = await sharp(img.buffer).resize(scaledWidth, minHeight).toBuffer();
|
||||
return { buffer: resized, width: scaledWidth, height: minHeight };
|
||||
}
|
||||
return img;
|
||||
}),
|
||||
);
|
||||
} else {
|
||||
// Find min width, scale wider images down
|
||||
const minWidth = Math.min(...imageMetas.map((m) => m.width));
|
||||
prepared = await Promise.all(
|
||||
imageMetas.map(async (img) => {
|
||||
if (img.width > minWidth) {
|
||||
const scaledHeight = Math.round((img.height * minWidth) / img.width);
|
||||
const resized = await sharp(img.buffer).resize(minWidth, scaledHeight).toBuffer();
|
||||
return { buffer: resized, width: minWidth, height: scaledHeight };
|
||||
}
|
||||
return img;
|
||||
}),
|
||||
);
|
||||
}
|
||||
let prepared: PreparedImage[];
|
||||
|
||||
if (isGrid) {
|
||||
prepared = await prepareForGrid(imageMetas, settings);
|
||||
} else if (isHorizontal) {
|
||||
prepared = await prepareForHorizontal(imageMetas, settings.resizeMode);
|
||||
} else {
|
||||
prepared = imageMetas;
|
||||
prepared = await prepareForVertical(imageMetas, settings.resizeMode);
|
||||
}
|
||||
|
||||
// Calculate canvas dimensions
|
||||
const n = prepared.length;
|
||||
let canvasWidth: number;
|
||||
let canvasHeight: number;
|
||||
const composites: sharp.OverlayOptions[] = [];
|
||||
|
||||
if (isHorizontal) {
|
||||
canvasWidth = prepared.reduce((sum, img) => sum + img.width, 0) + settings.gap * (n - 1);
|
||||
canvasHeight = Math.max(...prepared.map((img) => img.height));
|
||||
if (isGrid) {
|
||||
const cols = Math.min(settings.gridColumns, prepared.length);
|
||||
const rows = Math.ceil(prepared.length / cols);
|
||||
const cellWidth = Math.max(...prepared.map((img) => img.width));
|
||||
const cellHeight = Math.max(...prepared.map((img) => img.height));
|
||||
|
||||
canvasWidth = cols * cellWidth + (cols - 1) * settings.gap + 2 * settings.border;
|
||||
canvasHeight = rows * cellHeight + (rows - 1) * settings.gap + 2 * settings.border;
|
||||
|
||||
for (let i = 0; i < prepared.length; i++) {
|
||||
const col = i % cols;
|
||||
const row = Math.floor(i / cols);
|
||||
const img = prepared[i];
|
||||
|
||||
const cellLeft = settings.border + col * (cellWidth + settings.gap);
|
||||
const cellTop = settings.border + row * (cellHeight + settings.gap);
|
||||
|
||||
const left = cellLeft + alignOffset(cellWidth, img.width, settings.alignment);
|
||||
const top = cellTop + alignOffset(cellHeight, img.height, settings.alignment);
|
||||
|
||||
composites.push({ input: img.buffer, left, top });
|
||||
}
|
||||
} else if (isHorizontal) {
|
||||
const totalImgWidth = prepared.reduce((sum, img) => sum + img.width, 0);
|
||||
const maxHeight = Math.max(...prepared.map((img) => img.height));
|
||||
|
||||
canvasWidth = totalImgWidth + (prepared.length - 1) * settings.gap + 2 * settings.border;
|
||||
canvasHeight = maxHeight + 2 * settings.border;
|
||||
|
||||
let offset = settings.border;
|
||||
for (const img of prepared) {
|
||||
const top = settings.border + alignOffset(maxHeight, img.height, settings.alignment);
|
||||
composites.push({ input: img.buffer, left: offset, top });
|
||||
offset += img.width + settings.gap;
|
||||
}
|
||||
} else {
|
||||
canvasWidth = Math.max(...prepared.map((img) => img.width));
|
||||
canvasHeight = prepared.reduce((sum, img) => sum + img.height, 0) + settings.gap * (n - 1);
|
||||
const maxWidth = Math.max(...prepared.map((img) => img.width));
|
||||
const totalImgHeight = prepared.reduce((sum, img) => sum + img.height, 0);
|
||||
|
||||
canvasWidth = maxWidth + 2 * settings.border;
|
||||
canvasHeight = totalImgHeight + (prepared.length - 1) * settings.gap + 2 * settings.border;
|
||||
|
||||
let offset = settings.border;
|
||||
for (const img of prepared) {
|
||||
const left = settings.border + alignOffset(maxWidth, img.width, settings.alignment);
|
||||
composites.push({ input: img.buffer, left, top: offset });
|
||||
offset += img.height + settings.gap;
|
||||
}
|
||||
}
|
||||
|
||||
// Canvas size check
|
||||
if (canvasWidth * canvasHeight > MAX_CANVAS_PIXELS) {
|
||||
return reply.status(422).send({
|
||||
error: `Canvas too large: ${canvasWidth}x${canvasHeight} (${Math.round((canvasWidth * canvasHeight) / 1_000_000)}MP exceeds 100MP limit)`,
|
||||
});
|
||||
}
|
||||
|
||||
// Build composites
|
||||
const background = parseHexColor(settings.backgroundColor);
|
||||
const composites: sharp.OverlayOptions[] = [];
|
||||
let offset = 0;
|
||||
|
||||
for (const img of prepared) {
|
||||
let left: number;
|
||||
let top: number;
|
||||
|
||||
if (isHorizontal) {
|
||||
left = offset;
|
||||
top = Math.round((canvasHeight - img.height) / 2);
|
||||
offset += img.width + settings.gap;
|
||||
} else {
|
||||
left = Math.round((canvasWidth - img.width) / 2);
|
||||
top = offset;
|
||||
offset += img.height + settings.gap;
|
||||
}
|
||||
|
||||
composites.push({ input: img.buffer, left, top });
|
||||
}
|
||||
|
||||
// Create canvas and composite
|
||||
let pipeline = sharp({
|
||||
create: {
|
||||
width: canvasWidth,
|
||||
@@ -189,16 +193,41 @@ export function registerStitch(app: FastifyInstance) {
|
||||
},
|
||||
}).composite(composites);
|
||||
|
||||
// Output in requested format
|
||||
if (settings.format === "jpeg") {
|
||||
pipeline = pipeline.jpeg({ quality: 90 });
|
||||
pipeline = pipeline.jpeg({ quality: settings.quality });
|
||||
} else if (settings.format === "webp") {
|
||||
pipeline = pipeline.webp({ quality: 90 });
|
||||
pipeline = pipeline.webp({ quality: settings.quality });
|
||||
} else {
|
||||
pipeline = pipeline.png();
|
||||
}
|
||||
|
||||
const result = await pipeline.toBuffer();
|
||||
let result = await pipeline.toBuffer();
|
||||
|
||||
if (settings.cornerRadius > 0) {
|
||||
const meta = await sharp(result).metadata();
|
||||
const w = meta.width!;
|
||||
const h = meta.height!;
|
||||
const r = Math.min(settings.cornerRadius, Math.floor(Math.min(w, h) / 2));
|
||||
|
||||
const mask = Buffer.from(
|
||||
`<svg width="${w}" height="${h}"><rect x="0" y="0" width="${w}" height="${h}" rx="${r}" ry="${r}" fill="white"/></svg>`,
|
||||
);
|
||||
|
||||
result = await sharp(result)
|
||||
.ensureAlpha()
|
||||
.composite([{ input: mask, blend: "dest-in" }])
|
||||
.png()
|
||||
.toBuffer();
|
||||
|
||||
if (settings.format === "jpeg") {
|
||||
result = await sharp(result)
|
||||
.flatten({ background: { r: background.r, g: background.g, b: background.b } })
|
||||
.jpeg({ quality: settings.quality })
|
||||
.toBuffer();
|
||||
} else if (settings.format === "webp") {
|
||||
result = await sharp(result).webp({ quality: settings.quality }).toBuffer();
|
||||
}
|
||||
}
|
||||
|
||||
const jobId = randomUUID();
|
||||
const workspacePath = await createWorkspace(jobId);
|
||||
@@ -220,3 +249,130 @@ export function registerStitch(app: FastifyInstance) {
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function alignOffset(containerSize: number, itemSize: number, alignment: string): number {
|
||||
if (alignment === "start") return 0;
|
||||
if (alignment === "end") return containerSize - itemSize;
|
||||
return Math.round((containerSize - itemSize) / 2);
|
||||
}
|
||||
|
||||
async function prepareForHorizontal(
|
||||
images: PreparedImage[],
|
||||
resizeMode: string,
|
||||
): Promise<PreparedImage[]> {
|
||||
if (resizeMode === "original") return images;
|
||||
|
||||
const minHeight = Math.min(...images.map((m) => m.height));
|
||||
|
||||
return Promise.all(
|
||||
images.map(async (img) => {
|
||||
if (img.height === minHeight && resizeMode === "fit") return img;
|
||||
|
||||
if (resizeMode === "fit") {
|
||||
const scaledWidth = Math.round((img.width * minHeight) / img.height);
|
||||
const resized = await sharp(img.buffer).resize(scaledWidth, minHeight).toBuffer();
|
||||
return { buffer: resized, width: scaledWidth, height: minHeight };
|
||||
}
|
||||
|
||||
if (resizeMode === "stretch") {
|
||||
const resized = await sharp(img.buffer)
|
||||
.resize(img.width, minHeight, { fit: "fill" })
|
||||
.toBuffer();
|
||||
return { buffer: resized, width: img.width, height: minHeight };
|
||||
}
|
||||
|
||||
if (resizeMode === "crop") {
|
||||
const scaledWidth = Math.round((img.width * minHeight) / img.height);
|
||||
const resized = await sharp(img.buffer)
|
||||
.resize(scaledWidth, minHeight, { fit: "cover" })
|
||||
.toBuffer();
|
||||
return { buffer: resized, width: scaledWidth, height: minHeight };
|
||||
}
|
||||
|
||||
return img;
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
async function prepareForVertical(
|
||||
images: PreparedImage[],
|
||||
resizeMode: string,
|
||||
): Promise<PreparedImage[]> {
|
||||
if (resizeMode === "original") return images;
|
||||
|
||||
const minWidth = Math.min(...images.map((m) => m.width));
|
||||
|
||||
return Promise.all(
|
||||
images.map(async (img) => {
|
||||
if (img.width === minWidth && resizeMode === "fit") return img;
|
||||
|
||||
if (resizeMode === "fit") {
|
||||
const scaledHeight = Math.round((img.height * minWidth) / img.width);
|
||||
const resized = await sharp(img.buffer).resize(minWidth, scaledHeight).toBuffer();
|
||||
return { buffer: resized, width: minWidth, height: scaledHeight };
|
||||
}
|
||||
|
||||
if (resizeMode === "stretch") {
|
||||
const resized = await sharp(img.buffer)
|
||||
.resize(minWidth, img.height, { fit: "fill" })
|
||||
.toBuffer();
|
||||
return { buffer: resized, width: minWidth, height: img.height };
|
||||
}
|
||||
|
||||
if (resizeMode === "crop") {
|
||||
const scaledHeight = Math.round((img.height * minWidth) / img.width);
|
||||
const resized = await sharp(img.buffer)
|
||||
.resize(minWidth, scaledHeight, { fit: "cover" })
|
||||
.toBuffer();
|
||||
return { buffer: resized, width: minWidth, height: scaledHeight };
|
||||
}
|
||||
|
||||
return img;
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
async function prepareForGrid(
|
||||
images: PreparedImage[],
|
||||
settings: { gridColumns: number; resizeMode: string },
|
||||
): Promise<PreparedImage[]> {
|
||||
if (settings.resizeMode === "original") return images;
|
||||
|
||||
const medianWidth = median(images.map((m) => m.width));
|
||||
const medianHeight = median(images.map((m) => m.height));
|
||||
|
||||
return Promise.all(
|
||||
images.map(async (img) => {
|
||||
if (settings.resizeMode === "fit") {
|
||||
const scale = Math.min(medianWidth / img.width, medianHeight / img.height);
|
||||
if (scale >= 1) return img;
|
||||
const newW = Math.round(img.width * scale);
|
||||
const newH = Math.round(img.height * scale);
|
||||
const resized = await sharp(img.buffer).resize(newW, newH).toBuffer();
|
||||
return { buffer: resized, width: newW, height: newH };
|
||||
}
|
||||
|
||||
if (settings.resizeMode === "stretch") {
|
||||
const resized = await sharp(img.buffer)
|
||||
.resize(medianWidth, medianHeight, { fit: "fill" })
|
||||
.toBuffer();
|
||||
return { buffer: resized, width: medianWidth, height: medianHeight };
|
||||
}
|
||||
|
||||
if (settings.resizeMode === "crop") {
|
||||
const resized = await sharp(img.buffer)
|
||||
.resize(medianWidth, medianHeight, { fit: "cover" })
|
||||
.toBuffer();
|
||||
return { buffer: resized, width: medianWidth, height: medianHeight };
|
||||
}
|
||||
|
||||
return img;
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
function median(values: number[]): number {
|
||||
const sorted = [...values].sort((a, b) => a - b);
|
||||
const mid = Math.floor(sorted.length / 2);
|
||||
return sorted.length % 2 === 0 ? Math.round((sorted[mid - 1] + sorted[mid]) / 2) : sorted[mid];
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user