feat(v1.3.0): 图片编辑器(裁剪/旋转/图像大小/调色) + 批量水印 + AI生图 + 收藏体系 + 图片新窗口打开按钮 + 合拼拼图 + 返回顶部

This commit is contained in:
jinghui committed 2026-11-17 23:36:32 +08:00
1 parent e345456abf
commit 94ac94436c
46 files changed
+6521 -114

No files matched your search

+452
View File
@@ -0,0 +1,452 @@
/**
* MergeCollage — 多图合拼面板
* - 常见合拼布局模板(横排/竖排/品字/宫格/一大N小)
* - 槽位从图库选图(搜索 + 分页)
* - 填了模型 KEY 后可 AI 自动从图库找相似图并自动合拼
* - 合成结果通过 onMerge(blob) 交还编辑器替换底图
*/
import { useState, useEffect, useCallback } from 'react';
import { X, Loader2, Sparkles } from 'lucide-react';
import { imageAPI, settingsAPI } from '../api';
import { getToken } from '../api/client';
import { useUIStore } from '../stores/useUIStore';
/** 布局模板:cells 为归一化矩形 [x, y, w, h],aspect 为输出画布宽高比 */
const LAYOUTS = [
{ id: '2h', name: '两图横排', aspect: 2, cells: [[0, 0, 0.5, 1], [0.5, 0, 0.5, 1]] },
{ id: '2v', name: '两图竖排', aspect: 0.5, cells: [[0, 0, 1, 0.5], [0, 0.5, 1, 0.5]] },
{ id: '3h', name: '三图横排', aspect: 3, cells: [[0, 0, 1/3, 1], [1/3, 0, 1/3, 1], [2/3, 0, 1/3, 1]] },
{ id: '3v', name: '三图竖排', aspect: 1/3, cells: [[0, 0, 1, 1/3], [0, 1/3, 1, 1/3], [0, 2/3, 1, 1/3]] },
{ id: '1+2', name: '一大两小', aspect: 1.5, cells: [[0, 0, 0.6, 1], [0.6, 0, 0.4, 0.5], [0.6, 0.5, 0.4, 0.5]] },
{ id: '2+1', name: '两小一大', aspect: 1.5, cells: [[0, 0, 0.5, 0.5], [0.5, 0, 0.5, 0.5], [0, 0.5, 1, 0.5]] },
{ id: '2x2', name: '四宫格', aspect: 1, cells: [[0, 0, 0.5, 0.5], [0.5, 0, 0.5, 0.5], [0, 0.5, 0.5, 0.5], [0.5, 0.5, 0.5, 0.5]] },
{ id: '1+3', name: '一大三小', aspect: 1, cells: [[0, 0, 0.5, 1], [0.5, 0, 0.5, 1/3], [0.5, 1/3, 0.5, 1/3], [0.5, 2/3, 0.5, 1/3]] },
{ id: '3x2', name: '六宫格', aspect: 1.5, cells: [[0, 0, 1/3, 0.5], [1/3, 0, 1/3, 0.5], [2/3, 0, 1/3, 0.5], [0, 0.5, 1/3, 0.5], [1/3, 0.5, 1/3, 0.5], [2/3, 0.5, 1/3, 0.5]] },
{ id: '3x3', name: '九宫格', aspect: 1, cells: Array.from({ length: 9 }, (_, i) => [(i % 3) / 3, Math.floor(i / 3) / 3, 1/3, 1/3]) }
];
/** 按图片数量选默认布局:先找槽位数完全一致的,否则取能容纳的最小布局 */
function layoutForCount(n) {
if (n <= 1) return '2h';
const exact = LAYOUTS.find((l) => l.cells.length === n);
if (exact) return exact.id;
const bigger = LAYOUTS
.filter((l) => l.cells.length > n)
.sort((a, b) => a.cells.length - b.cells.length);
return bigger[0] ? bigger[0].id : '3x3';
}
const GAP_OPTIONS = [
{ value: 0, label: '无' },
{ value: 16, label: '细' },
{ value: 32, label: '粗' }
];
/** 缩略图 URL(无缩略图时回退原图) */
function thumbUrl(libId, rec) {
if (!rec) return '';
if (rec.thumbnailPath) {
const fn = rec.thumbnailPath.replace(/\\/g, '/').split('/').pop();
return imageAPI.getThumbnailUrl(libId, fn, rec.modifiedAt);
}
return imageAPI.getOriginalUrl(libId, rec.path);
}
function loadImg(src) {
return new Promise((resolve, reject) => {
const im = new Image();
im.onload = () => resolve(im);
im.onerror = () => reject(new Error('图片加载失败: ' + src));
im.src = src;
});
}
export default function MergeCollage({ image, libraryId, onMerge, setStatus, setBusy }) {
const [layoutId, setLayoutId] = useState('2h');
const [slots, setSlots] = useState([image, null]);
const [gap, setGap] = useState(16);
const [keyReady, setKeyReady] = useState(null); // null=未检查
const [pickerFor, setPickerFor] = useState(null); // 正在选图的槽位下标
const [pickQuery, setPickQuery] = useState('');
const [pickImages, setPickImages] = useState([]);
const [pickOffset, setPickOffset] = useState(0);
const [pickHasMore, setPickHasMore] = useState(false);
const [pickLoading, setPickLoading] = useState(false);
const layout = LAYOUTS.find((l) => l.id === layoutId) || LAYOUTS[0];
const filled = slots.filter(Boolean).length;
// 打开时:有多选种子图则自动填槽 + 选布局;否则当前图为第 1 格
useEffect(() => {
const st = useUIStore.getState();
const seeds = st.mergeImages;
if (seeds && seeds.length >= 1) {
const lid = layoutForCount(seeds.length);
const L = LAYOUTS.find((l) => l.id === lid);
setLayoutId(lid);
setSlots(L.cells.map((_, i) => seeds[i] || null));
st.setMergeImages(null);
} else {
setLayoutId('2h');
setSlots([image, null]);
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [image && image.path]);
// 检查模型 KEY 是否已配置
useEffect(() => {
settingsAPI.getSettings()
.then((d) => setKeyReady(!!(d.online && d.online.configured)))
.catch(() => setKeyReady(null));
}, []);
// 退出时清掉未消费的种子,避免下次误触发
useEffect(() => () => useUIStore.getState().setMergeImages(null), []);
const changeLayout = useCallback((id) => {
setLayoutId(id);
const L = LAYOUTS.find((l) => l.id === id);
setSlots((prev) => L.cells.map((_, i) => prev[i] || null));
}, []);
// ---------- 图库选择器 ----------
const loadPicker = useCallback(async (offset, kw) => {
setPickLoading(true);
try {
const params = { offset, limit: 48 };
if (kw && kw.trim()) params.keywords = kw.trim();
const r = await imageAPI.search(libraryId, params);
setPickImages((prev) => (offset === 0 ? r.images : [...prev, ...r.images]));
setPickOffset(offset + (r.images ? r.images.length : 0));
setPickHasMore(!!r.hasMore);
} catch (e) {
setStatus('加载图库失败: ' + (e.message || ''));
} finally {
setPickLoading(false);
}
}, [libraryId, setStatus]);
const openPicker = (idx) => {
setPickerFor(idx);
setPickQuery('');
setPickImages([]);
setPickOffset(0);
loadPicker(0, '');
};
const pickSearch = () => {
setPickImages([]);
loadPicker(0, pickQuery);
};
const assignSlot = (rec) => {
setSlots((prev) => {
const next = [...prev];
next[pickerFor] = rec;
return next;
});
setPickerFor(null);
};
// ---------- 合成渲染 ----------
const doRender = useCallback(async (slotList) => {
const cells = layout.cells;
const list = slotList || slots;
const usable = list.filter(Boolean);
if (usable.length < 2) {
setStatus('至少需要 2 张图片才能合拼');
return;
}
let W, H;
if (layout.aspect >= 1) { W = 2000; H = Math.round(2000 / layout.aspect); }
else { H = 2000; W = Math.round(2000 * layout.aspect); }
const off = document.createElement('canvas');
off.width = W;
off.height = H;
const ctx = off.getContext('2d');
ctx.fillStyle = '#ffffff';
ctx.fillRect(0, 0, W, H);
const g = gap;
try {
let done = 0;
for (let i = 0; i < cells.length; i++) {
const rec = list[i];
if (!rec) continue;
done += 1;
setBusy(`合拼生成中 ${done}/${usable.length}`);
const [cx, cy, cw, ch] = cells[i];
const x = cx * W + g / 2;
const y = cy * H + g / 2;
const w = cw * W - g;
const h = ch * H - g;
const im = await loadImg(imageAPI.getOriginalUrl(libraryId, rec.path));
const s = Math.max(w / im.width, h / im.height);
const dw = im.width * s;
const dh = im.height * s;
ctx.save();
ctx.beginPath();
ctx.rect(x, y, w, h);
ctx.clip();
ctx.drawImage(im, x + (w - dw) / 2, y + (h - dh) / 2, dw, dh);
ctx.restore();
im.onload = null;
im.src = '';
}
const blob = await new Promise((res, rej) =>
off.toBlob((b) => (b ? res(b) : rej(new Error('画布导出失败'))), 'image/png')
);
await onMerge(blob);
setStatus(`合拼完成(${usable.length} 张 · ${W}×${H}),可继续编辑后保存`);
} catch (e) {
setStatus('合拼失败: ' + (e.message || ''));
} finally {
setBusy('');
}
}, [layout, slots, gap, libraryId, onMerge, setStatus, setBusy]);
// ---------- AI 自动找相似图并合拼 ----------
const aiAutoMerge = async () => {
const emptyIdx = slots.map((s, i) => (s ? null : i)).filter((i) => i !== null);
if (!emptyIdx.length) {
return doRender(slots);
}
const seedRec = slots.find(Boolean) || image;
if (keyReady === false) {
setStatus('未配置模型 KEY:请到 设置 → OCR 识别 填写线上模型接口和 KEY');
return;
}
setBusy('AI 正在图库中找相似图');
try {
const resp = await fetch('/api/edit/find-similar', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `*** ${getToken()}`
},
body: JSON.stringify({
libraryId,
seedPath: seedRec.path,
count: emptyIdx.length,
excludePaths: slots.filter(Boolean).map((s) => s.path)
})
});
const j = await resp.json().catch(() => ({}));
if (!resp.ok) {
throw new Error((j.error && j.error.message) || `请求失败 (${resp.status})`);
}
const next = [...slots];
(j.images || []).forEach((img, k) => {
if (k < emptyIdx.length) next[emptyIdx[k]] = img;
});
setSlots(next);
setStatus(`AI 找到 ${(j.images || []).length} 张相似图,正在合拼…`);
await doRender(next);
} catch (e) {
setStatus('AI 合拼失败: ' + (e.message || ''));
setBusy('');
}
};
return (
<div className="space-y-3">
{/* 布局模板 */}
<div className="text-xs font-semibold text-gray-600 dark:text-gray-300">合拼布局</div>
<div className="grid grid-cols-2 gap-1.5">
{LAYOUTS.map((L) => {
const active = L.id === layoutId;
return (
<button
key={L.id}
onClick={() => changeLayout(L.id)}
className={`p-1.5 rounded-lg border transition-colors ${
active
? 'border-blue-500 bg-blue-50 dark:bg-blue-900/30'
: 'border-gray-200 dark:border-gray-600 hover:border-blue-300'
}`}
>
<div
className="relative w-full bg-gray-100 dark:bg-gray-700 rounded overflow-hidden"
style={{ paddingBottom: `${(1 / L.aspect) * 100}%` }}
>
{L.cells.map((c, i) => (
<span
key={i}
className={`absolute ${active ? 'bg-blue-400' : 'bg-gray-300 dark:bg-gray-500'}`}
style={{
left: `${c[0] * 100}%`,
top: `${c[1] * 100}%`,
width: `${c[2] * 100}%`,
height: `${c[3] * 100}%`,
border: '1px solid rgba(255,255,255,0.85)',
boxSizing: 'border-box'
}}
/>
))}
</div>
<div className={`text-[10px] text-center mt-1 ${active ? 'text-blue-600 dark:text-blue-400' : 'text-gray-500'}`}>
{L.name} · {L.cells.length}图
</div>
</button>
);
})}
</div>
{/* 槽位 */}
<div className="flex items-center justify-between">
<div className="text-xs font-semibold text-gray-600 dark:text-gray-300">图片槽位</div>
<div className="text-[10px] text-gray-400">{filled}/{layout.cells.length} 已选</div>
</div>
<div className="grid grid-cols-3 gap-1.5">
{layout.cells.map((_, i) => {
const rec = slots[i];
return (
<div key={i} className="relative group aspect-square">
<button
onClick={() => openPicker(i)}
className="w-full h-full rounded border border-dashed border-gray-300 dark:border-gray-600 overflow-hidden hover:border-blue-400 transition-colors flex items-center justify-center bg-gray-50 dark:bg-gray-700/50"
title={rec ? '点击换图' : '点击从图库选图'}
>
{rec ? (
<img src={thumbUrl(libraryId, rec)} alt="" className="w-full h-full object-cover" />
) : (
<span className="text-gray-400 text-lg">+</span>
)}
</button>
{rec && (
<button
onClick={() => setSlots((prev) => { const n = [...prev]; n[i] = null; return n; })}
className="absolute -top-1 -right-1 w-4 h-4 rounded-full bg-red-500 text-white items-center justify-center hidden group-hover:flex leading-none text-[10px]"
title="清空此槽"
>
<X className="w-3 h-3" />
</button>
)}
</div>
);
})}
</div>
{/* 间距 */}
<div className="flex items-center gap-2">
<span className="text-xs text-gray-500 dark:text-gray-400">图片间距</span>
<div className="flex gap-1">
{GAP_OPTIONS.map((o) => (
<button
key={o.value}
onClick={() => setGap(o.value)}
className={`px-2 py-0.5 rounded text-[11px] border transition-colors ${
gap === o.value
? 'border-blue-500 text-blue-600 bg-blue-50 dark:bg-blue-900/30'
: 'border-gray-200 dark:border-gray-600 text-gray-500'
}`}
>
{o.label}
</button>
))}
</div>
</div>
{/* AI 自动合拼 */}
<button
onClick={aiAutoMerge}
disabled={filled < 1}
className="w-full py-2 rounded-lg bg-gradient-to-r from-violet-500 to-fuchsia-500 text-white text-sm hover:opacity-90 disabled:opacity-50 transition-opacity flex items-center justify-center gap-1.5"
>
<Sparkles className="w-4 h-4" />
AI 自动找相似图并合拼
</button>
{keyReady === false && (
<p className="text-[11px] text-amber-600 dark:text-amber-400 leading-relaxed">
未配置模型 KEY:到 设置 → OCR 识别 填写线上模型接口和 API Key 后,AI 可自动从图库找相似图。
</p>
)}
<p className="text-[11px] text-gray-400 leading-relaxed">
「AI 自动合拼」以第 1 张为参考,从图库找相似图填满空槽并直接生成;也可手动点槽选图后点下方按钮生成。
</p>
<button
onClick={() => doRender(slots)}
disabled={filled < 2}
className="w-full py-2 rounded-lg bg-blue-600 text-white text-sm hover:bg-blue-700 disabled:opacity-50 transition-colors"
>
生成合拼({filled} 张)
</button>
{/* 图库选择器 */}
{pickerFor !== null && (
<div
className="fixed inset-0 z-[60] bg-black/60 flex items-center justify-center p-4"
onClick={() => setPickerFor(null)}
>
<div
className="bg-white dark:bg-gray-800 rounded-xl shadow-2xl w-full max-w-3xl max-h-[80vh] flex flex-col"
onClick={(e) => e.stopPropagation()}
>
<div className="flex items-center gap-2 px-4 py-3 border-b border-gray-200 dark:border-gray-700">
<span className="text-sm font-medium text-gray-700 dark:text-gray-200 flex-shrink-0">
选择图片(第 {pickerFor + 1} 格)
</span>
<input
value={pickQuery}
onChange={(e) => setPickQuery(e.target.value)}
onKeyDown={(e) => e.key === 'Enter' && pickSearch()}
placeholder="搜索文件名…"
className="flex-1 min-w-0 text-sm rounded border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-700 px-2 py-1.5 outline-none focus:border-blue-400"
/>
<button
onClick={pickSearch}
className="px-3 py-1.5 text-sm rounded bg-blue-600 text-white hover:bg-blue-700 flex-shrink-0"
>
搜索
</button>
<button
onClick={() => setPickerFor(null)}
className="p-1.5 rounded text-gray-400 hover:text-gray-600 hover:bg-gray-100 dark:hover:bg-gray-700 flex-shrink-0"
>
<X className="w-4 h-4" />
</button>
</div>
<div className="flex-1 overflow-y-auto p-3">
<div className="grid grid-cols-4 sm:grid-cols-6 gap-2">
{pickImages.map((img) => (
<button
key={img.path}
onClick={() => assignSlot(img)}
className="aspect-square rounded overflow-hidden border border-gray-200 dark:border-gray-600 hover:border-blue-500 hover:ring-1 hover:ring-blue-500 transition-all"
title={img.filename}
>
<img
src={thumbUrl(libraryId, img)}
alt={img.filename}
loading="lazy"
className="w-full h-full object-cover"
/>
</button>
))}
{!pickImages.length && !pickLoading && (
<div className="col-span-full text-center text-sm text-gray-400 py-8">没有找到图片</div>
)}
{pickLoading && (
<div className="col-span-full flex items-center justify-center gap-2 text-sm text-gray-400 py-8">
<Loader2 className="w-4 h-4 animate-spin" /> 加载中…
</div>
)}
</div>
</div>
{pickHasMore && (
<div className="px-4 py-2.5 border-t border-gray-200 dark:border-gray-700 text-center">
<button
onClick={() => loadPicker(pickOffset, pickQuery)}
disabled={pickLoading}
className="px-4 py-1.5 text-sm rounded border border-gray-300 dark:border-gray-600 text-gray-600 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-700 disabled:opacity-50"
>
加载更多(已 {pickImages.length} 张)
</button>
</div>
)}
</div>
</div>
)}
</div>
);
}