feat(v1.3.0): 图片编辑器(裁剪/旋转/图像大小/调色) + 批量水印 + AI生图 + 收藏体系 + 图片新窗口打开按钮 + 合拼拼图 + 返回顶部
This commit is contained in:
1 parent
e345456abf
commit
94ac94436c
46 files changed
+6521
-114
No files matched your search
@@ -0,0 +1,403 @@
|
||||
/**
|
||||
* 文件夹批量水印路由
|
||||
* - POST /api/batch/start 启动批量任务(加水印 / 去水印),返回 taskId 立即返回
|
||||
* - GET /api/batch/status/:id 查询任务进度
|
||||
* - POST /api/batch/cancel/:id 取消任务
|
||||
*
|
||||
* 加水印:sharp 合成 SVG 文字水印(九宫格 / 平铺、透明度、旋转、字号按图宽百分比)
|
||||
* 去水印:按百分比矩形区域生成 mask → 调 flypic-ai sidecar 的 LaMa /inpaint
|
||||
*/
|
||||
|
||||
const express = require('express');
|
||||
const router = express.Router();
|
||||
const path = require('path');
|
||||
const fs = require('fs');
|
||||
const sharp = require('sharp');
|
||||
const { asyncHandler, ValidationError, NotFoundError } = require('../middleware/errorHandler');
|
||||
const { processImage } = require('../../utils/scanner');
|
||||
const ImageModel = require('../models/ImageModel');
|
||||
const logger = require('../utils/logger');
|
||||
|
||||
const AI_BASE = process.env.AI_BASE_URL || 'http://127.0.0.1:15003';
|
||||
|
||||
const IMAGE_EXTS = new Set(['.jpg', '.jpeg', '.png', '.webp']);
|
||||
const SHARP_FMT = { '.jpg': 'jpeg', '.jpeg': 'jpeg', '.png': 'png', '.webp': 'webp' };
|
||||
|
||||
// ---------- 任务表(内存) ----------
|
||||
const tasks = new Map();
|
||||
let taskSeq = 0;
|
||||
|
||||
function newTask(type, payload) {
|
||||
const id = `bt_${Date.now()}_${++taskSeq}`;
|
||||
const task = {
|
||||
id,
|
||||
type, // 'add' | 'remove'
|
||||
status: 'running', // running | done | cancelled | error
|
||||
total: 0,
|
||||
done: 0,
|
||||
failed: 0,
|
||||
skipped: 0,
|
||||
current: '',
|
||||
errors: [],
|
||||
cancelled: false,
|
||||
startedAt: Date.now(),
|
||||
finishedAt: null,
|
||||
payload
|
||||
};
|
||||
tasks.set(id, task);
|
||||
return task;
|
||||
}
|
||||
|
||||
// 完成的任务 30 分钟后清理
|
||||
setInterval(() => {
|
||||
const cutoff = Date.now() - 30 * 60 * 1000;
|
||||
for (const [id, t] of tasks) {
|
||||
if (t.finishedAt && t.finishedAt < cutoff) tasks.delete(id);
|
||||
}
|
||||
}, 60 * 1000).unref();
|
||||
|
||||
// ---------- 工具 ----------
|
||||
|
||||
/** 按百分比区域生成 mask(白色=待修复)→ 渲染为 PNG(PIL 不认 SVG) */
|
||||
async function makeMaskBuffer(width, height, region) {
|
||||
const x = Math.max(0, Math.round((width * region.x) / 100));
|
||||
const y = Math.max(0, Math.round((height * region.y) / 100));
|
||||
const w = Math.max(1, Math.min(width - x, Math.round((width * region.w) / 100)));
|
||||
const h = Math.max(1, Math.min(height - y, Math.round((height * region.h) / 100)));
|
||||
const svg = `<svg width="${width}" height="${height}" xmlns="http://www.w3.org/2000/svg">` +
|
||||
`<rect width="${width}" height="${height}" fill="black"/>` +
|
||||
`<rect x="${x}" y="${y}" width="${w}" height="${h}" fill="white"/></svg>`;
|
||||
return sharp(Buffer.from(svg)).png().toBuffer();
|
||||
}
|
||||
|
||||
/** 生成文字水印 SVG(支持九宫格单个 / 平铺) */
|
||||
function makeWatermarkSvg(width, height, opts) {
|
||||
const text = String(opts.text || '').trim();
|
||||
const fontSize = Math.max(8, Math.round((width * (opts.fontSizePct || 4)) / 100));
|
||||
const opacity = Math.max(0, Math.min(100, opts.opacity ?? 50)) / 100;
|
||||
const color = opts.color || '#ffffff';
|
||||
const margin = Math.round((width * (opts.marginPct ?? 2)) / 100);
|
||||
const stroke = opts.stroke ? ` stroke="#000000" stroke-opacity="${opacity * 0.5}" stroke-width="${Math.max(1, fontSize / 14)}"` : '';
|
||||
const fill = color.startsWith('#')
|
||||
? (color.length === 4 || color.length === 7 ? color : '#ffffff')
|
||||
: color;
|
||||
const escape = (s) => s.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>')
|
||||
.replace(/"/g, '"').replace(/'/g, ''');
|
||||
const esc = escape(text);
|
||||
|
||||
const font = "font-family=\"Noto Sans CJK SC, Noto Sans SC, WenQuanYi Zen Hei, sans-serif\"";
|
||||
const items = [];
|
||||
|
||||
if (opts.tile) {
|
||||
// 平铺:按角度旋转整块排布
|
||||
const rotate = Number(opts.rotate ?? -30);
|
||||
const gapX = fontSize * 8;
|
||||
const gapY = fontSize * 5;
|
||||
let row = 0;
|
||||
for (let y = -height; y < height * 2; y += gapY) {
|
||||
const offset = row % 2 === 0 ? 0 : gapX / 2;
|
||||
for (let x = -width; x < width * 2; x += gapX) {
|
||||
items.push(
|
||||
`<text x="${x + offset}" y="${y}" font-size="${fontSize}" ${font} ` +
|
||||
`fill="${fill}" fill-opacity="${opacity}"${stroke}>${esc}</text>`
|
||||
);
|
||||
}
|
||||
row++;
|
||||
}
|
||||
const cx = width / 2;
|
||||
const cy = height / 2;
|
||||
return `<svg width="${width}" height="${height}" xmlns="http://www.w3.org/2000/svg">` +
|
||||
`<g transform="rotate(${rotate} ${cx} ${cy})">${items.join('')}</g></svg>`;
|
||||
}
|
||||
|
||||
// 单个水印:九宫格定位
|
||||
const pos = opts.position || 'bottom-right';
|
||||
const [va, ha] = pos.split('-');
|
||||
const rotate = Number(opts.rotate || 0);
|
||||
|
||||
let x, y, anchor;
|
||||
if (ha === 'left') { x = margin; anchor = 'start'; }
|
||||
else if (ha === 'right') { x = width - margin; anchor = 'end'; }
|
||||
else { x = width / 2; anchor = 'middle'; }
|
||||
|
||||
if (va === 'top') y = margin + fontSize;
|
||||
else if (va === 'middle') y = height / 2;
|
||||
else y = height - margin;
|
||||
|
||||
const transform = rotate ? ` transform="rotate(${rotate} ${x} ${y})"` : '';
|
||||
items.push(
|
||||
`<text x="${x}" y="${y}" font-size="${fontSize}" ${font} text-anchor="${anchor}" ` +
|
||||
`fill="${fill}" fill-opacity="${opacity}"${stroke}${transform}>${esc}</text>`
|
||||
);
|
||||
return `<svg width="${width}" height="${height}" xmlns="http://www.w3.org/2000/svg">` +
|
||||
items.join('') + `</svg>`;
|
||||
}
|
||||
|
||||
/** 结果 buffer 按原格式落盘(覆盖原图或另存) */
|
||||
async function writeResult(absPath, pngBuffer, opts = {}) {
|
||||
const ext = path.extname(absPath).toLowerCase();
|
||||
const fmt = SHARP_FMT[ext];
|
||||
if (!fmt) throw new Error(`不支持的格式: ${ext}`);
|
||||
|
||||
let target = absPath;
|
||||
if (opts.mode === 'new') {
|
||||
const base = absPath.slice(0, absPath.length - ext.length);
|
||||
const suffix = opts.suffix || '_wm';
|
||||
target = `${base}${suffix}${ext}`;
|
||||
let n = 1;
|
||||
while (fs.existsSync(target)) {
|
||||
target = `${base}${suffix}${n}${ext}`;
|
||||
n++;
|
||||
}
|
||||
}
|
||||
|
||||
const pipeline = sharp(pngBuffer);
|
||||
if (fmt === 'jpeg') await pipeline.jpeg({ quality: 92 }).toFile(target);
|
||||
else if (fmt === 'webp') await pipeline.webp({ quality: 92 }).toFile(target);
|
||||
else await pipeline.png().toFile(target);
|
||||
return target;
|
||||
}
|
||||
|
||||
/** 串行并发池 */
|
||||
async function runPool(items, concurrency, worker) {
|
||||
let idx = 0;
|
||||
const runners = Array.from({ length: Math.max(1, Math.min(concurrency, items.length)) }, async () => {
|
||||
for (;;) {
|
||||
const i = idx++;
|
||||
if (i >= items.length) break;
|
||||
await worker(items[i], i);
|
||||
}
|
||||
});
|
||||
await Promise.all(runners);
|
||||
}
|
||||
|
||||
/** 调 sidecar 去水印 */
|
||||
async function callInpaint(imageBuffer, maskBuffer) {
|
||||
const form = new FormData();
|
||||
form.append('image', new Blob([imageBuffer], { type: 'image/png' }), 'image.png');
|
||||
form.append('mask', new Blob([maskBuffer], { type: 'image/png' }), 'mask.png');
|
||||
const resp = await fetch(`${AI_BASE}/inpaint`, {
|
||||
method: 'POST',
|
||||
body: form,
|
||||
signal: AbortSignal.timeout(300 * 1000)
|
||||
});
|
||||
if (!resp.ok) {
|
||||
let msg = `AI 服务错误 (${resp.status})`;
|
||||
try {
|
||||
const j = await resp.json();
|
||||
msg = j.detail || j.error || msg;
|
||||
} catch (_) { /* 非 JSON */ }
|
||||
throw new Error(msg);
|
||||
}
|
||||
return Buffer.from(await resp.arrayBuffer());
|
||||
}
|
||||
|
||||
/** 收集文件夹内图片(含子文件夹) */
|
||||
function collectImages(req, libraryId, folder) {
|
||||
const configManager = req.app.get('configManager');
|
||||
const dbPool = req.app.get('dbPool');
|
||||
if (!configManager || !dbPool) throw new ValidationError('服务未初始化');
|
||||
|
||||
const config = configManager.load();
|
||||
const library = config.libraries.find((l) => String(l.id) === String(libraryId));
|
||||
if (!library) throw new NotFoundError('Library', libraryId);
|
||||
|
||||
const db = dbPool.acquire(library.path);
|
||||
try {
|
||||
const model = new ImageModel(db.db);
|
||||
const { images } = model.search({ folder }, null);
|
||||
return { library, images };
|
||||
} finally {
|
||||
dbPool.release(library.path);
|
||||
}
|
||||
}
|
||||
|
||||
/** 每张图处理完后重建缩略图并更新 DB(每张独立 acquire,避免长占连接) */
|
||||
async function reindex(req, libraryPath, absPath) {
|
||||
const dbPool = req.app.get('dbPool');
|
||||
const db = dbPool.acquire(libraryPath);
|
||||
try {
|
||||
await processImage(absPath, libraryPath, db);
|
||||
} finally {
|
||||
dbPool.release(libraryPath);
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- 任务执行 ----------
|
||||
|
||||
async function runAddWatermark(req, task) {
|
||||
const { library, images } = collectImages(req, task.payload.libraryId, task.payload.folder);
|
||||
const opts = task.payload.options;
|
||||
const outMode = task.payload.output === 'new' ? 'new' : 'overwrite';
|
||||
task.total = images.length;
|
||||
|
||||
const targets = [];
|
||||
for (const img of images) {
|
||||
const abs = path.join(library.path, img.path);
|
||||
const ext = path.extname(abs).toLowerCase();
|
||||
if (!IMAGE_EXTS.has(ext) || !fs.existsSync(abs)) {
|
||||
task.skipped++;
|
||||
continue;
|
||||
}
|
||||
targets.push({ img, abs, ext });
|
||||
}
|
||||
task.total = targets.length + task.skipped;
|
||||
|
||||
await runPool(targets, 3, async ({ img, abs, ext }) => {
|
||||
if (task.cancelled) return;
|
||||
task.current = img.path;
|
||||
try {
|
||||
const base = sharp(abs);
|
||||
const meta = await base.metadata();
|
||||
const w = meta.width || 1024;
|
||||
const h = meta.height || 1024;
|
||||
const svg = makeWatermarkSvg(w, h, opts);
|
||||
let out = await base.rotate().composite([{ input: Buffer.from(svg), top: 0, left: 0 }]).png().toBuffer();
|
||||
|
||||
// rotate() 可能改变尺寸(EXIF),重取
|
||||
const m2 = await sharp(out).metadata();
|
||||
if (m2.width !== w || m2.height !== h) {
|
||||
const svg2 = makeWatermarkSvg(m2.width, m2.height, opts);
|
||||
out = await sharp(out).composite([{ input: Buffer.from(svg2), top: 0, left: 0 }]).png().toBuffer();
|
||||
}
|
||||
|
||||
await writeResult(abs, out, { mode: outMode, suffix: '_wm' });
|
||||
await reindex(req, library.path, abs);
|
||||
task.done++;
|
||||
} catch (err) {
|
||||
task.failed++;
|
||||
if (task.errors.length < 20) task.errors.push({ path: img.path, error: err.message });
|
||||
logger.warn(`⚠️ 批量加水印失败 ${img.path}: ${err.message}`);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
async function runRemoveWatermark(req, task) {
|
||||
const { library, images } = collectImages(req, task.payload.libraryId, task.payload.folder);
|
||||
const region = task.payload.options.region;
|
||||
const outMode = task.payload.output === 'new' ? 'new' : 'overwrite';
|
||||
task.total = images.length;
|
||||
|
||||
const targets = [];
|
||||
for (const img of images) {
|
||||
const abs = path.join(library.path, img.path);
|
||||
const ext = path.extname(abs).toLowerCase();
|
||||
if (!IMAGE_EXTS.has(ext) || !fs.existsSync(abs)) {
|
||||
task.skipped++;
|
||||
continue;
|
||||
}
|
||||
targets.push({ img, abs, ext });
|
||||
}
|
||||
task.total = targets.length + task.skipped;
|
||||
|
||||
// LaMa CPU 推理较慢且 sidecar 为单模型,串行处理
|
||||
await runPool(targets, 1, async ({ img, abs }) => {
|
||||
if (task.cancelled) return;
|
||||
task.current = img.path;
|
||||
try {
|
||||
const srcBuf = fs.readFileSync(abs);
|
||||
const meta = await sharp(srcBuf).metadata();
|
||||
const w = meta.width || 1024;
|
||||
const h = meta.height || 1024;
|
||||
const mask = await makeMaskBuffer(w, h, region);
|
||||
const result = await callInpaint(srcBuf, mask);
|
||||
await writeResult(abs, result, { mode: outMode, suffix: '_nowm' });
|
||||
await reindex(req, library.path, abs);
|
||||
task.done++;
|
||||
} catch (err) {
|
||||
task.failed++;
|
||||
if (task.errors.length < 20) task.errors.push({ path: img.path, error: err.message });
|
||||
logger.warn(`⚠️ 批量去水印失败 ${img.path}: ${err.message}`);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// ---------- 路由 ----------
|
||||
|
||||
/**
|
||||
* POST /api/batch/start
|
||||
* body: { libraryId, folder, type: 'add'|'remove', output?: 'overwrite'|'new', options }
|
||||
* add options: { text, tile?, position?, fontSizePct?, opacity?, color?, marginPct?, rotate?, stroke? }
|
||||
* remove options: { region: { x, y, w, h } // 图片宽高的百分比 }
|
||||
*/
|
||||
router.post(
|
||||
'/start',
|
||||
asyncHandler(async (req, res) => {
|
||||
const { libraryId, folder, type, output, options } = req.body || {};
|
||||
if (!libraryId || !folder) throw new ValidationError('缺少 libraryId 或 folder');
|
||||
if (type !== 'add' && type !== 'remove') throw new ValidationError('type 必须是 add 或 remove');
|
||||
|
||||
if (type === 'add') {
|
||||
if (!options || !String(options.text || '').trim()) throw new ValidationError('水印文字不能为空');
|
||||
} else {
|
||||
const r = options && options.region;
|
||||
if (!r || [r.x, r.y, r.w, r.h].some((v) => typeof v !== 'number' || v < 0)) {
|
||||
throw new ValidationError('缺少水印区域 region {x,y,w,h}(百分比)');
|
||||
}
|
||||
if (r.w <= 0 || r.h <= 0) throw new ValidationError('水印区域宽高必须大于 0');
|
||||
}
|
||||
|
||||
const { images } = collectImages(req, libraryId, folder);
|
||||
if (images.length === 0) throw new ValidationError('该文件夹下没有图片');
|
||||
|
||||
const task = newTask(type, { libraryId, folder, output, options });
|
||||
task.total = images.length;
|
||||
logger.info(`▶️ 批量${type === 'add' ? '加水印' : '去水印'}启动: ${folder} (${images.length} 张)`);
|
||||
|
||||
// 立即返回,后台执行
|
||||
const runner = type === 'add' ? runAddWatermark : runRemoveWatermark;
|
||||
runner(req, task)
|
||||
.then(() => {
|
||||
task.status = task.cancelled ? 'cancelled' : 'done';
|
||||
})
|
||||
.catch((err) => {
|
||||
task.status = 'error';
|
||||
task.errors.push({ path: '', error: err.message });
|
||||
logger.error(`❌ 批量任务异常: ${err.message}`);
|
||||
})
|
||||
.finally(() => {
|
||||
task.current = '';
|
||||
task.finishedAt = Date.now();
|
||||
});
|
||||
|
||||
res.json({ taskId: task.id, total: images.length });
|
||||
})
|
||||
);
|
||||
|
||||
/** GET /api/batch/status/:id */
|
||||
router.get(
|
||||
'/status/:id',
|
||||
asyncHandler(async (req, res) => {
|
||||
const task = tasks.get(req.params.id);
|
||||
if (!task) throw new NotFoundError('Task', req.params.id);
|
||||
res.json({
|
||||
id: task.id,
|
||||
type: task.type,
|
||||
status: task.status,
|
||||
total: task.total,
|
||||
done: task.done,
|
||||
failed: task.failed,
|
||||
skipped: task.skipped,
|
||||
current: task.current,
|
||||
errors: task.errors,
|
||||
startedAt: task.startedAt,
|
||||
finishedAt: task.finishedAt
|
||||
});
|
||||
})
|
||||
);
|
||||
|
||||
/** POST /api/batch/cancel/:id */
|
||||
router.post(
|
||||
'/cancel/:id',
|
||||
asyncHandler(async (req, res) => {
|
||||
const task = tasks.get(req.params.id);
|
||||
if (!task) throw new NotFoundError('Task', req.params.id);
|
||||
if (task.status === 'running') {
|
||||
task.cancelled = true;
|
||||
task.status = 'cancelled';
|
||||
}
|
||||
res.json({ ok: true, status: task.status });
|
||||
})
|
||||
);
|
||||
|
||||
module.exports = router;
|
||||
Reference in new issue
Block a user