/** * ImageEditor — fabric.js 图片编辑器 * 工具:选择 / 文字(大小·颜色·发光·旋转·透明度)/ 表情 / 自媒体文字模板 / * 贴图(添加图片)/ 水印(单个·平铺)/ AI(高清·去背景·抠图·去水印涂抹·换脸) * 裁剪(比例·三分线·拖拽)/ 旋转翻转 / 图像大小 / 调色(亮度·对比度·饱和度·色相·模糊·黑白·反色·复古·自动色阶) * 保存:覆盖原图 / 另存为新图(后端转码并重建缩略图) */ import { useState, useEffect, useRef } from 'react'; import { Canvas, FabricImage, IText, Shadow, ActiveSelection, Point } from 'fabric'; import { MousePointer2, Type, Smile, LayoutTemplate, ImagePlus, Stamp, Sparkles, Pencil, X, Trash2, Loader2, Eraser, Wand2, LayoutGrid, Undo2, Redo2, Crop, SlidersHorizontal, RotateCw, RotateCcw, FlipHorizontal, FlipVertical, Maximize2 } from 'lucide-react'; import { useUIStore } from '../stores/useUIStore'; import { useLibraryStore } from '../stores/useLibraryStore'; import { useImageStore } from '../stores/useImageStore'; import { imageAPI } from '../api'; import { getToken } from '../api/client'; import MergeCollage from './MergeCollage'; const EMOJIS = [ '😀', '😂', '🤣', '😍', '🥰', '😎', '🤔', '😭', '😅', '😡', '🥳', '😱', '👍', '👎', '👏', '🙏', '💪', '🤝', '✌️', '👌', '🤙', '❤️', '🔥', '⭐', '✨', '💯', '🎉', '🎊', '💰', '📈', '📉', '🎯', '📌', '💡', '📸', '🎵', '🚀', '🏆', '🥇', '✅', '🍉', '🍔', '☕', '🐶', '🐱', '🌈', '⏰', '📝' ]; const TEMPLATES = [ { label: '爆款标题', text: '爆款标题', style: { fontSize: 72, fill: '#fff200', stroke: '#1a1a1a', strokeWidth: 6, paintFirst: 'stroke', fontWeight: 'bold' } }, { label: '干货满满', text: '干货满满', style: { fontSize: 56, fill: '#ffffff', textBackgroundColor: '#e11d48', fontWeight: 'bold' } }, { label: '点击关注', text: '点击关注', style: { fontSize: 48, fill: '#ffffff', textBackgroundColor: '#2563eb', fontWeight: 'bold' } }, { label: '限时免费', text: '限时免费', style: { fontSize: 52, fill: '#ffffff', textBackgroundColor: '#f59e0b', fontWeight: 'bold' } }, { label: '建议收藏', text: '建议收藏', style: { fontSize: 44, fill: '#ffffff', textBackgroundColor: '#16a34a', fontWeight: 'bold' } }, { label: '文末有惊喜', text: '文末有惊喜', style: { fontSize: 44, fill: '#fff200', stroke: '#1a1a1a', strokeWidth: 4, paintFirst: 'stroke', fontWeight: 'bold' } }, { label: '每日更新', text: '每日更新', style: { fontSize: 40, fill: '#a21caf', textBackgroundColor: '#fce7f3', fontWeight: 'bold' } }, { label: '全网最全', text: '全网最全', style: { fontSize: 48, fill: '#0ea5e9', stroke: '#ffffff', strokeWidth: 3, paintFirst: 'stroke', fontWeight: 'bold' } }, { label: '关注不迷路', text: '关注我,不迷路', style: { fontSize: 40, fill: '#ffffff', textBackgroundColor: '#111827', fontWeight: 'bold' } }, { label: '记得点赞', text: '记得点赞', style: { fontSize: 40, fill: '#e11d48', fontWeight: 'bold' } } ]; const ASPECTS = [ { key: 'free', label: '自由', r: 0 }, { key: '1:1', label: '1:1', r: 1 }, { key: '4:3', label: '4:3', r: 4 / 3 }, { key: '3:2', label: '3:2', r: 1.5 }, { key: '16:9', label: '16:9', r: 16 / 9 }, { key: '9:16', label: '9:16', r: 9 / 16 } ]; const ADJ_DEFAULT = { brightness: 0, contrast: 0, saturate: 0, hue: 0, blur: 0, grayscale: false, invert: false, sepia: false, autoLevel: false }; const ADJ_SLIDERS = [ { k: 'brightness', label: '亮度', min: -100, max: 100 }, { k: 'contrast', label: '对比度', min: -100, max: 100 }, { k: 'saturate', label: '饱和度', min: -100, max: 100 }, { k: 'hue', label: '色相', min: 0, max: 360, unit: '°' }, { k: 'blur', label: '模糊', min: 0, max: 20, unit: 'px' } ]; const ADJ_TOGGLES = [ { k: 'grayscale', label: '黑白' }, { k: 'invert', label: '反色' }, { k: 'sepia', label: '复古' }, { k: 'autoLevel', label: '自动色阶' } ]; const TOOLS = [ { id: 'select', icon: MousePointer2, label: '选择' }, { id: 'text', icon: Type, label: '文字' }, { id: 'sticker', icon: Smile, label: '表情' }, { id: 'template', icon: LayoutTemplate, label: '模板' }, { id: 'image', icon: ImagePlus, label: '贴图' }, { id: 'watermark', icon: Stamp, label: '水印' }, { id: 'merge', icon: LayoutGrid, label: '合拼' }, { id: 'crop', icon: Crop, label: '裁剪' }, { id: 'adjust', icon: SlidersHorizontal, label: '调色' }, { id: 'ai', icon: Sparkles, label: 'AI工具' } ]; function ImageEditor() { const { editingImage, setEditingImage } = useUIStore(); const { currentLibraryId } = useLibraryStore(); const { updateImage, bumpRefresh } = useImageStore(); const canvasElRef = useRef(null); const maskCanvasRef = useRef(null); const stickerInputRef = useRef(null); const faceInputRef = useRef(null); const fabricRef = useRef(null); const baseInfoRef = useRef({ naturalW: 0, naturalH: 0, displayW: 0, displayH: 0 }); const baseBlobRef = useRef(null); const dirtyRef = useRef(false); const drawingRef = useRef(false); const lastPtRef = useRef(null); const [size, setSize] = useState({ w: 0, h: 0 }); const [loading, setLoading] = useState(false); const [error, setError] = useState(''); const [activeTool, setActiveTool] = useState('select'); const [selProps, setSelProps] = useState(null); const [aiBusy, setAiBusy] = useState(''); const [saving, setSaving] = useState(false); const [status, setStatus] = useState(''); // 文字工具 const [newFontSize, setNewFontSize] = useState(48); // 水印 const [wmText, setWmText] = useState('我的水印'); const [wmSize, setWmSize] = useState(5); const [wmOpacity, setWmOpacity] = useState(30); // 去水印涂抹 const [maskMode, setMaskMode] = useState(false); const [brushSize, setBrushSize] = useState(30); // 抠图底色 const [bgColor, setBgColor] = useState('#ffffff'); // 裁剪 const [cropAspect, setCropAspect] = useState('free'); const [cropRect, setCropRect] = useState(null); const [resizeW, setResizeW] = useState(''); const cropDragRef = useRef(null); // 调色 const [adj, setAdj] = useState(ADJ_DEFAULT); const [adjBusy, setAdjBusy] = useState(false); const adjSourceRef = useRef(null); // 调色基准图(Blob) const adjImgRef = useRef(null); // 解码后的基准图(预览复用) const adjDirtyRef = useRef(false); // 有未应用的调色预览 const adjSeqRef = useRef(0); // 预览序号(丢弃过期渲染) // ---------- 初始化画布 ---------- useEffect(() => { if (!editingImage || !currentLibraryId || !canvasElRef.current) return; let disposed = false; (async () => { setLoading(true); setError(''); try { const url = imageAPI.getOriginalUrl(currentLibraryId, editingImage.path); const headers = getToken() ? { Authorization: `Bearer ${getToken()}` } : {}; const resp = await fetch(url, { headers }); if (!resp.ok) throw new Error(`原图加载失败 (${resp.status})`); const blob = await resp.blob(); if (disposed) return; baseBlobRef.current = blob; const objUrl = URL.createObjectURL(blob); const img = await FabricImage.fromURL(objUrl); URL.revokeObjectURL(objUrl); if (disposed) return; // 适配显示尺寸(小图适度放大便于编辑,导出时按原始分辨率输出) const maxW = 900; const maxH = 640; const scale = Math.min(maxW / img.width, maxH / img.height, 4); const w = Math.max(1, Math.round(img.width * scale)); const h = Math.max(1, Math.round(img.height * scale)); setSize({ w, h }); baseInfoRef.current = { naturalW: img.width, naturalH: img.height, displayW: w, displayH: h }; const canvas = new Canvas(canvasElRef.current, { width: w, height: h, backgroundColor: 'transparent', preserveObjectStacking: true, selection: true }); img.set({ left: 0, top: 0, scaleX: scale, scaleY: scale }); canvas.backgroundImage = img; canvas.requestRenderAll(); const syncProps = () => { const obj = canvas.getActiveObject(); if (!obj) return setSelProps(null); if (obj.type === 'activeSelection') return setSelProps({ type: 'multi' }); setSelProps({ type: obj.type, text: obj.text ?? '', fontSize: obj.fontSize ?? 48, fill: typeof obj.fill === 'string' ? obj.fill : '#ffffff', angle: Math.round(obj.angle ?? 0), opacity: Math.round((obj.opacity ?? 1) * 100), glowOn: !!obj.shadow, glowColor: (obj.shadow && obj.shadow.color) || '#ffff00', glowBlur: (obj.shadow && obj.shadow.blur) || 20 }); }; canvas.on('selection:created', syncProps); canvas.on('selection:updated', syncProps); canvas.on('selection:cleared', () => setSelProps(null)); canvas.on('object:modified', syncProps); canvas.on('object:added', () => { dirtyRef.current = true; }); canvas.on('object:removed', () => { dirtyRef.current = true; }); fabricRef.current = canvas; dirtyRef.current = false; } catch (err) { if (!disposed) setError(err.message || '初始化失败'); } finally { if (!disposed) setLoading(false); } })(); return () => { disposed = true; if (fabricRef.current) { fabricRef.current.dispose(); fabricRef.current = null; } setSize({ w: 0, h: 0 }); setSelProps(null); setMaskMode(false); dirtyRef.current = false; }; }, [editingImage, currentLibraryId]); // ---------- 裁剪:进入工具时初始化选区 / 离开时清理 ---------- useEffect(() => { if (activeTool !== 'crop') { setCropRect(null); return; } if (!size.w) return; const W = baseInfoRef.current.displayW; const H = baseInfoRef.current.displayH; if (!W || !H) return; const a = ASPECTS.find((x) => x.key === cropAspect); let w = W * 0.84; let h = H * 0.84; if (a && a.r) { w = Math.min(w, h * a.r); h = w / a.r; } setCropRect({ x: Math.round((W - w) / 2), y: Math.round((H - h) / 2), w: Math.round(w), h: Math.round(h) }); setResizeW(String(baseInfoRef.current.naturalW || '')); const cv = fabricRef.current; if (cv) { cv.discardActiveObject(); cv.requestRenderAll(); } setSelProps(null); // eslint-disable-next-line react-hooks/exhaustive-deps }, [activeTool, size.w, editingImage]); // ---------- 调色:进入工具时缓存解码基准图 ---------- useEffect(() => { if (activeTool !== 'adjust' || !editingImage) return; initAdjustSource(); // eslint-disable-next-line react-hooks/exhaustive-deps }, [activeTool, editingImage]); // ---------- 多选「合拼」带图进入:自动切到合拼工具 ---------- useEffect(() => { if (!editingImage) return; const st = useUIStore.getState(); if (st.mergeImages && st.mergeImages.length >= 1) { setActiveTool('merge'); } }, [editingImage]); // ---------- AI 结果替换底层图片(保留文字/贴图叠加层) ---------- const replaceBaseImage = async (blob) => { const canvas = fabricRef.current; if (!canvas) return; const { displayW } = baseInfoRef.current; const objUrl = URL.createObjectURL(blob); try { const img = await FabricImage.fromURL(objUrl); const scale = displayW / img.width; img.set({ left: 0, top: 0, scaleX: scale, scaleY: scale }); canvas.backgroundImage = img; baseInfoRef.current = { ...baseInfoRef.current, naturalW: img.width, naturalH: img.height }; baseBlobRef.current = blob; dirtyRef.current = true; canvas.requestRenderAll(); syncAdjustSource(blob); } finally { URL.revokeObjectURL(objUrl); } }; // ---------- 合拼结果替换底图(宽高比可能变化,需同步画布尺寸) ---------- const replaceBaseImageSized = async (blob) => { const canvas = fabricRef.current; if (!canvas) return; const objUrl = URL.createObjectURL(blob); try { const img = await FabricImage.fromURL(objUrl); // 与初始化一致的显示适配规则 const maxW = 900; const maxH = 640; const scale = Math.min(maxW / img.width, maxH / img.height, 4); const w = Math.max(1, Math.round(img.width * scale)); const h = Math.max(1, Math.round(img.height * scale)); const oldW = baseInfoRef.current.displayW || w; const oldH = baseInfoRef.current.displayH || h; canvas.setDimensions({ width: w, height: h }); setSize({ w, h }); // 已有叠加对象按新旧尺寸比例迁移位置/大小 const rx = oldW ? w / oldW : 1; const ry = oldH ? h / oldH : 1; canvas.getObjects().forEach((o) => { o.set({ left: (o.left || 0) * rx, top: (o.top || 0) * ry, scaleX: (o.scaleX || 1) * rx, scaleY: (o.scaleY || 1) * ry }); o.setCoords(); }); img.set({ left: 0, top: 0, scaleX: scale, scaleY: scale }); canvas.backgroundImage = img; baseInfoRef.current = { naturalW: img.width, naturalH: img.height, displayW: w, displayH: h }; baseBlobRef.current = blob; dirtyRef.current = true; canvas.requestRenderAll(); syncAdjustSource(blob); } finally { URL.revokeObjectURL(objUrl); } }; const callAI = async (action, buildForm, label) => { setAiBusy(label); setStatus(''); try { await ensureAdjustCommitted(); const fd = new FormData(); fd.append('action', action); buildForm(fd); const resp = await fetch('/api/edit/ai', { method: 'POST', headers: getToken() ? { Authorization: `Bearer ${getToken()}` } : {}, body: fd }); if (!resp.ok) { let msg = `AI 处理失败 (${resp.status})`; try { const j = await resp.json(); if (j.error) msg = j.error; } catch (_) { /* 非 JSON */ } throw new Error(msg); } const blob = await resp.blob(); await replaceBaseImage(blob); setStatus(`${label}完成`); } catch (err) { setStatus(err.message || 'AI 处理失败'); } finally { setAiBusy(''); } }; // ---------- 对象操作 ---------- const getActive = () => fabricRef.current && fabricRef.current.getActiveObject(); const updateActive = (patch) => { const canvas = fabricRef.current; const obj = getActive(); if (!canvas || !obj || obj.type === 'activeSelection') return; obj.set(patch); obj.setCoords(); canvas.requestRenderAll(); // 重新同步 setSelProps((prev) => (prev ? { ...prev, ...patch, angle: Math.round(patch.angle ?? obj.angle ?? 0), opacity: patch.opacity ?? prev.opacity } : prev)); }; const setGlow = (on, color, blur) => { const canvas = fabricRef.current; const obj = getActive(); if (!canvas || !obj) return; obj.set('shadow', on ? new Shadow({ color, blur, offsetX: 0, offsetY: 0 }) : null); canvas.requestRenderAll(); setSelProps((prev) => (prev ? { ...prev, glowOn: on, glowColor: color, glowBlur: blur } : prev)); }; const removeActive = () => { const canvas = fabricRef.current; const obj = getActive(); if (!canvas || !obj) return; if (obj.type === 'activeSelection') { obj.getObjects().forEach((o) => canvas.remove(o)); } else { canvas.remove(obj); } canvas.discardActiveObject(); canvas.requestRenderAll(); setSelProps(null); }; const addText = (text, style = {}) => { const canvas = fabricRef.current; if (!canvas) return; const { displayW, displayH } = baseInfoRef.current; const t = new IText(text, { left: displayW / 2, top: displayH / 2, originX: 'center', originY: 'center', fontSize: Math.round(displayH * 0.09), fill: '#ffffff', stroke: '#000000', strokeWidth: 2, paintFirst: 'stroke', fontFamily: 'sans-serif', angle: 0, ...style }); canvas.add(t); canvas.setActiveObject(t); canvas.requestRenderAll(); try { t.enterEditing(); t.selectAll(); } catch (_) { /* 双击可再次编辑 */ } setActiveTool('select'); }; const addEmoji = (ch) => { const canvas = fabricRef.current; if (!canvas) return; const { displayW, displayH } = baseInfoRef.current; const t = new IText(ch, { left: displayW / 2, top: displayH / 2, originX: 'center', originY: 'center', fontSize: Math.round(displayH * 0.16), strokeWidth: 0, angle: 0 }); canvas.add(t); canvas.setActiveObject(t); canvas.requestRenderAll(); setActiveTool('select'); }; const addStickerImage = async (e) => { const file = e.target.files && e.target.files[0]; e.target.value = ''; const canvas = fabricRef.current; if (!file || !canvas) return; const objUrl = URL.createObjectURL(file); try { const img = await FabricImage.fromURL(objUrl); const { displayW, displayH } = baseInfoRef.current; const scale = (displayW * 0.4) / img.width; img.set({ left: displayW / 2, top: displayH / 2, originX: 'center', originY: 'center', scaleX: scale, scaleY: scale }); canvas.add(img); canvas.setActiveObject(img); canvas.requestRenderAll(); setActiveTool('select'); } catch (err) { setStatus('贴图加载失败: ' + (err.message || '')); } finally { URL.revokeObjectURL(objUrl); } }; const addWatermark = (tile) => { const canvas = fabricRef.current; if (!canvas) return; const { displayW, displayH } = baseInfoRef.current; const base = { fill: '#ffffff', strokeWidth: 0, opacity: wmOpacity / 100, angle: -25, fontFamily: 'sans-serif', isWatermark: true }; if (!tile) { const t = new IText(wmText || '水印', { left: displayW / 2, top: displayH / 2, originX: 'center', originY: 'center', fontSize: Math.round(displayH * (wmSize / 100)), ...base }); canvas.add(t); canvas.setActiveObject(t); } else { const fontSize = Math.round(displayH * (wmSize / 100)); const gapX = Math.max(fontSize * (wmText || '水印').length * 0.7, 160); const gapY = Math.max(fontSize * 2.4, 140); const objs = []; for (let y = gapY * 0.4; y < displayH; y += gapY) { for (let x = gapX * 0.3; x < displayW; x += gapX) { objs.push(new IText(wmText || '水印', { left: x, top: y, originX: 'left', originY: 'top', fontSize, ...base })); } } objs.forEach((o) => canvas.add(o)); if (objs[0]) canvas.setActiveObject(objs[0]); } canvas.requestRenderAll(); setActiveTool('select'); }; const clearWatermarks = () => { const canvas = fabricRef.current; if (!canvas) return; canvas.getObjects().filter((o) => o.isWatermark).forEach((o) => canvas.remove(o)); canvas.discardActiveObject(); canvas.requestRenderAll(); setSelProps(null); }; // ---------- 去水印涂抹 ---------- const enterMaskMode = () => { const canvas = fabricRef.current; if (!canvas) return; canvas.discardActiveObject(); canvas.selection = false; canvas.skipTargetFind = true; canvas.requestRenderAll(); setSelProps(null); setMaskMode(true); }; const exitMaskMode = (clear = true) => { const canvas = fabricRef.current; if (canvas) { canvas.selection = true; canvas.skipTargetFind = false; canvas.requestRenderAll(); } if (clear && maskCanvasRef.current) { const ctx = maskCanvasRef.current.getContext('2d'); ctx.clearRect(0, 0, maskCanvasRef.current.width, maskCanvasRef.current.height); } setMaskMode(false); }; const maskPoint = (e) => { const c = maskCanvasRef.current; const rect = c.getBoundingClientRect(); return { x: (e.clientX - rect.left) * (c.width / rect.width), y: (e.clientY - rect.top) * (c.height / rect.height) }; }; const onMaskDown = (e) => { e.currentTarget.setPointerCapture(e.pointerId); drawingRef.current = true; lastPtRef.current = maskPoint(e); }; const onMaskMove = (e) => { if (!drawingRef.current) return; const c = maskCanvasRef.current; const ctx = c.getContext('2d'); const pt = maskPoint(e); const rect = c.getBoundingClientRect(); ctx.strokeStyle = '#ffffff'; ctx.lineWidth = brushSize * (c.width / rect.width); ctx.lineCap = 'round'; ctx.lineJoin = 'round'; ctx.beginPath(); ctx.moveTo(lastPtRef.current.x, lastPtRef.current.y); ctx.lineTo(pt.x, pt.y); ctx.stroke(); lastPtRef.current = pt; }; const onMaskUp = () => { drawingRef.current = false; lastPtRef.current = null; }; const clearMask = () => { const c = maskCanvasRef.current; if (c) c.getContext('2d').clearRect(0, 0, c.width, c.height); }; const applyInpaint = async () => { const c = maskCanvasRef.current; const base = baseBlobRef.current; if (!c || !base) return; const { naturalW, naturalH } = baseInfoRef.current; const off = document.createElement('canvas'); off.width = naturalW; off.height = naturalH; const ctx = off.getContext('2d'); ctx.fillStyle = '#000000'; ctx.fillRect(0, 0, naturalW, naturalH); ctx.drawImage(c, 0, 0, naturalW, naturalH); const maskBlob = await new Promise((resolve) => off.toBlob(resolve, 'image/png')); if (!maskBlob) { setStatus('蒙版导出失败'); return; } await callAI( 'inpaint', (fd) => { fd.append('image', base, 'base.png'); fd.append('mask', maskBlob, 'mask.png'); }, '去水印修复' ); clearMask(); exitMaskMode(false); }; // ---------- 其余 AI ---------- const runUpscale = (scale) => { const base = baseBlobRef.current; if (!base) return; callAI('upscale', (fd) => { fd.append('image', base, 'base.png'); fd.append('scale', String(scale)); }, `AI 高清 ×${scale}`); }; const runRemoveBg = (mode, color) => { const base = baseBlobRef.current; if (!base) return; callAI('removebg', (fd) => { fd.append('image', base, 'base.png'); fd.append('mode', mode); if (mode === 'color' && color) fd.append('bg_color', color); }, mode === 'transparent' ? '去背景' : '抠图'); }; const runFaceSwap = async (e) => { const file = e.target.files && e.target.files[0]; e.target.value = ''; const base = baseBlobRef.current; if (!file || !base) return; await callAI('faceswap', (fd) => { fd.append('source', file, file.name || 'face.png'); fd.append('target', base, 'target.png'); }, '换脸'); }; // ================= 裁剪 / 旋转翻转 / 图像大小 / 调色 ================= const blobToImage = (blob) => new Promise((resolve, reject) => { const u = URL.createObjectURL(blob); const img = new Image(); img.onload = () => { URL.revokeObjectURL(u); resolve(img); }; img.onerror = (e) => { URL.revokeObjectURL(u); reject(new Error('图片解码失败')); }; img.src = u; }); const blobFromCanvas = (c, mime) => new Promise((resolve) => { c.toBlob((b) => resolve(b), mime || 'image/png', (mime || 'image/png') === 'image/jpeg' ? 0.95 : undefined); }); const pickMime = (blob) => { const t = blob && blob.type; if (t === 'image/jpeg' || t === 'image/webp' || t === 'image/png') return t; return 'image/png'; }; // ---------- 调色 ---------- const buildFilterStr = (a, blurPx) => { const p = []; if (a.brightness) p.push(`brightness(${1 + a.brightness / 100})`); if (a.contrast) p.push(`contrast(${1 + a.contrast / 100})`); if (a.saturate) p.push(`saturate(${1 + a.saturate / 100})`); if (a.hue) p.push(`hue-rotate(${a.hue}deg)`); if (blurPx > 0) p.push(`blur(${blurPx}px)`); if (a.grayscale) p.push('grayscale(1)'); if (a.invert) p.push('invert(1)'); if (a.sepia) p.push('sepia(1)'); return p.join(' '); }; const applyAutoLevel = (ctx, w, h) => { const d = ctx.getImageData(0, 0, w, h); const px = d.data; const mn = [255, 255, 255]; const mx = [0, 0, 0]; for (let i = 0; i < px.length; i += 4) { for (let c = 0; c < 3; c++) { const v = px[i + c]; if (v < mn[c]) mn[c] = v; if (v > mx[c]) mx[c] = v; } } const gain = [0, 0, 0]; for (let c = 0; c < 3; c++) gain[c] = mx[c] > mn[c] ? 255 / (mx[c] - mn[c]) : 1; for (let i = 0; i < px.length; i += 4) { for (let c = 0; c < 3; c++) px[i + c] = (px[i + c] - mn[c]) * gain[c]; } ctx.putImageData(d, 0, 0); }; // 底图变化时同步调色状态(清空预览、恢复默认值) const syncAdjustSource = (blob) => { adjSourceRef.current = blob; adjImgRef.current = null; adjDirtyRef.current = false; adjSeqRef.current++; setAdj(ADJ_DEFAULT); }; const initAdjustSource = async () => { if (adjSourceRef.current !== baseBlobRef.current) { adjSourceRef.current = baseBlobRef.current; adjImgRef.current = null; } if (!adjImgRef.current && baseBlobRef.current) { try { adjImgRef.current = await blobToImage(baseBlobRef.current); } catch (_) { /* 预览时再试 */ } } if (adjDirtyRef.current) renderAdjustPreview(adj); }; const renderAdjustPreview = async (a) => { const canvas = fabricRef.current; if (!canvas || !baseBlobRef.current) return; if (adjSourceRef.current !== baseBlobRef.current) { adjSourceRef.current = baseBlobRef.current; adjImgRef.current = null; } if (!adjImgRef.current) { try { adjImgRef.current = await blobToImage(baseBlobRef.current); } catch (_) { return; } } const seq = ++adjSeqRef.current; const { displayW, displayH, naturalW } = baseInfoRef.current; const c = document.createElement('canvas'); c.width = displayW; c.height = displayH; const ctx = c.getContext('2d'); // 预览在显示分辨率绘制,模糊按比例换算,所见即所得 const blurPx = naturalW ? a.blur * (displayW / naturalW) : a.blur; const f = buildFilterStr(a, blurPx); if (f) ctx.filter = f; ctx.drawImage(adjImgRef.current, 0, 0, displayW, displayH); ctx.filter = 'none'; if (a.autoLevel) applyAutoLevel(ctx, displayW, displayH); const blob = await blobFromCanvas(c, 'image/png'); if (!blob || seq !== adjSeqRef.current) return; // 过期请求丢弃 const u = URL.createObjectURL(blob); try { const fi = await FabricImage.fromURL(u); if (seq !== adjSeqRef.current) return; fi.set({ left: 0, top: 0, scaleX: 1, scaleY: 1 }); canvas.backgroundImage = fi; adjDirtyRef.current = true; dirtyRef.current = true; canvas.requestRenderAll(); } finally { URL.revokeObjectURL(u); } }; const previewTimerRef = useRef(null); const onAdjChange = (patch) => { const next = { ...adj, ...patch }; setAdj(next); clearTimeout(previewTimerRef.current); previewTimerRef.current = setTimeout(() => renderAdjustPreview(next), 90); }; // 全分辨率烘焙调色(保存/AI/裁剪/旋转前调用) const applyAdjustFull = async () => { const canvas = fabricRef.current; if (!canvas || !adjDirtyRef.current || !baseBlobRef.current) return; if (!adjImgRef.current) { try { adjImgRef.current = await blobToImage(adjSourceRef.current || baseBlobRef.current); } catch (_) { return; } } const { naturalW, naturalH } = baseInfoRef.current; const c = document.createElement('canvas'); c.width = naturalW; c.height = naturalH; const ctx = c.getContext('2d'); const f = buildFilterStr(adj, adj.blur); if (f) ctx.filter = f; ctx.drawImage(adjImgRef.current, 0, 0, naturalW, naturalH); ctx.filter = 'none'; if (adj.autoLevel) applyAutoLevel(ctx, naturalW, naturalH); const blob = await blobFromCanvas(c, pickMime(baseBlobRef.current)); if (!blob) return; adjDirtyRef.current = false; await replaceBaseImage(blob); // 内部 syncAdjustSource 清空预览状态 setStatus('调整已应用'); }; const ensureAdjustCommitted = async () => { if (adjDirtyRef.current) await applyAdjustFull(); }; const cancelAdjust = async () => { adjSeqRef.current++; adjDirtyRef.current = false; setAdj(ADJ_DEFAULT); const wasDirty = dirtyRef.current; if (baseBlobRef.current) { await replaceBaseImage(baseBlobRef.current); // 恢复未预览的原图 dirtyRef.current = wasDirty; // 仅取消调色不算修改 } }; // ---------- 裁剪 ---------- const onCropPointerDown = (e, mode) => { e.stopPropagation(); e.preventDefault(); if (!cropRect) return; cropDragRef.current = { mode, sx: e.clientX, sy: e.clientY, r0: { ...cropRect } }; e.currentTarget.setPointerCapture && e.currentTarget.setPointerCapture(e.pointerId); }; const onCropPointerMove = (e) => { const d = cropDragRef.current; if (!d || !cropRect) return; const W = size.w; const H = size.h; const MIN = 48; const dx = e.clientX - d.sx; const dy = e.clientY - d.sy; const r0 = d.r0; const a = ASPECTS.find((x) => x.key === cropAspect); const ratio = a && a.r ? a.r : 0; let r; if (d.mode === 'move') { r = { x: Math.min(Math.max(0, r0.x + dx), W - r0.w), y: Math.min(Math.max(0, r0.y + dy), H - r0.h), w: r0.w, h: r0.h }; } else { // 角点缩放:对角为锚点 const ax = d.mode === 'se' || d.mode === 'ne' ? r0.x : r0.x + r0.w; const ay = d.mode === 'se' || d.mode === 'sw' ? r0.y : r0.y + r0.h; const anchorLeft = d.mode === 'se' || d.mode === 'ne'; const anchorTop = d.mode === 'se' || d.mode === 'sw'; let w = anchorLeft ? r0.w + dx : r0.w - dx; let h = anchorTop ? r0.h + dy : r0.h - dy; w = Math.max(MIN, w); h = Math.max(MIN, h); const maxW = anchorLeft ? W - ax : ax; const maxH = anchorTop ? H - ay : ay; if (ratio) { if (Math.abs(dx) >= Math.abs(dy)) h = w / ratio; else w = h * ratio; w = Math.min(w, maxW); h = w / ratio; if (h > maxH) { h = maxH; w = h * ratio; } w = Math.min(w, maxW); } else { w = Math.min(w, maxW); h = Math.min(h, maxH); } r = { x: anchorLeft ? ax : ax - w, y: anchorTop ? ay : ay - h, w: Math.round(w), h: Math.round(h) }; } setCropRect(r); }; const onCropPointerUp = () => { cropDragRef.current = null; }; const setAspect = (key) => { setCropAspect(key); const a = ASPECTS.find((x) => x.key === key); if (!a || !a.r || !cropRect) return; const W = size.w; const H = size.h; const cx = cropRect.x + cropRect.w / 2; const cy = cropRect.y + cropRect.h / 2; let w = Math.min(cropRect.w, cropRect.h * a.r); let h = w / a.r; if (h > H) { h = H; w = h * a.r; } w = Math.min(w, W); h = w / a.r; let x = Math.round(cx - w / 2); let y = Math.round(cy - h / 2); x = Math.min(Math.max(0, x), W - Math.round(w)); y = Math.min(Math.max(0, y), H - Math.round(h)); setCropRect({ x, y, w: Math.round(w), h: Math.round(h) }); }; const applyCrop = async () => { const canvas = fabricRef.current; if (!canvas || !cropRect || saving) return; const { naturalW, naturalH, displayW, displayH } = baseInfoRef.current; if (!naturalW || !displayW) return; const kx = naturalW / displayW; const ky = naturalH / displayH; let sx = Math.round(cropRect.x * kx); let sy = Math.round(cropRect.y * ky); let sw = Math.round(cropRect.w * kx); let sh = Math.round(cropRect.h * ky); sx = Math.min(Math.max(0, sx), naturalW - 1); sy = Math.min(Math.max(0, sy), naturalH - 1); sw = Math.max(1, Math.min(sw, naturalW - sx)); sh = Math.max(1, Math.min(sh, naturalH - sy)); const base = baseBlobRef.current; if (!base) return; setAiBusy('裁剪中…'); try { await ensureAdjustCommitted(); // 调色预览先烘焙 const img = await blobToImage(baseBlobRef.current); const c = document.createElement('canvas'); c.width = sw; c.height = sh; c.getContext('2d').drawImage(img, sx, sy, sw, sh, 0, 0, sw, sh); const blob = await blobFromCanvas(c, pickMime(base)); if (!blob) throw new Error('裁剪失败'); // 叠加层:整体平移,删掉完全落在裁剪区外的对象 canvas.discardActiveObject(); setSelProps(null); const cw = cropRect.w; const ch = cropRect.h; canvas.getObjects().forEach((o) => { o.set({ left: (o.left || 0) - cropRect.x, top: (o.top || 0) - cropRect.y }); o.setCoords(); const b = o.getBoundingRect(); if (b.left + b.width < 0 || b.top + b.height < 0 || b.left > cw || b.top > ch) canvas.remove(o); }); // 预先把显示基准切到裁剪区域,复用尺寸自适应替换逻辑 baseInfoRef.current = { ...baseInfoRef.current, displayW: cw, displayH: ch }; await replaceBaseImageSized(blob); setCropRect(null); setActiveTool('select'); setStatus(`已裁剪 ${sw}×${sh}`); } catch (err) { setStatus(err.message || '裁剪失败'); } finally { setAiBusy(''); } }; // ---------- 旋转 / 翻转 ---------- const transformBase = async (kind) => { const canvas = fabricRef.current; const base = baseBlobRef.current; if (!canvas || !base || aiBusy) return; setAiBusy(kind === 'fliph' || kind === 'flipv' ? '翻转中…' : '旋转中…'); try { await ensureAdjustCommitted(); const srcBlob = baseBlobRef.current; const { naturalW: nw0, naturalH: nh0, displayW, displayH } = baseInfoRef.current; const img = await blobToImage(srcBlob); const swap = kind === 'cw90' || kind === 'ccw90'; const c = document.createElement('canvas'); c.width = swap ? nh0 : nw0; c.height = swap ? nw0 : nh0; const ctx = c.getContext('2d'); if (kind === 'cw90') { ctx.translate(c.width, 0); ctx.rotate(Math.PI / 2); } else if (kind === 'ccw90') { ctx.translate(0, c.height); ctx.rotate(-Math.PI / 2); } else if (kind === 'r180') { ctx.translate(c.width, c.height); ctx.rotate(Math.PI); } else if (kind === 'fliph') { ctx.translate(c.width, 0); ctx.scale(-1, 1); } else { ctx.translate(0, c.height); ctx.scale(1, -1); } ctx.drawImage(img, 0, 0); const blob = await blobFromCanvas(c, pickMime(srcBlob)); if (!blob) throw new Error('处理失败'); // 叠加层同步几何变换(以对象中心计算,兼容不同原点) canvas.discardActiveObject(); setSelProps(null); canvas.getObjects().forEach((o) => { const ctr = o.getCenterPoint(); let nx = ctr.x; let ny = ctr.y; let na = o.angle || 0; if (kind === 'cw90') { nx = displayH - ctr.y; ny = ctr.x; na += 90; } else if (kind === 'ccw90') { nx = ctr.y; ny = displayW - ctr.x; na -= 90; } else if (kind === 'r180') { nx = displayW - ctr.x; ny = displayH - ctr.y; na += 180; } else if (kind === 'fliph') { nx = displayW - ctr.x; ny = ctr.y; na = -na; } else { nx = ctr.x; ny = displayH - ctr.y; na = -na; } if (kind === 'fliph') o.set('scaleX', -(o.scaleX || 1)); if (kind === 'flipv') o.set('scaleY', -(o.scaleY || 1)); o.set('angle', na); const ctr2 = o.getCenterPoint(); o.set({ left: (o.left || 0) + (nx - ctr2.x), top: (o.top || 0) + (ny - ctr2.y) }); o.setCoords(); }); const ndW = swap ? displayH : displayW; const ndH = swap ? displayW : displayH; canvas.setDimensions({ width: ndW, height: ndH }); setSize({ w: ndW, h: ndH }); const u = URL.createObjectURL(blob); let bg; try { bg = await FabricImage.fromURL(u); } finally { URL.revokeObjectURL(u); } const scale = ndW / bg.width; bg.set({ left: 0, top: 0, scaleX: scale, scaleY: scale }); canvas.backgroundImage = bg; baseInfoRef.current = { naturalW: bg.width, naturalH: bg.height, displayW: ndW, displayH: ndH }; baseBlobRef.current = blob; dirtyRef.current = true; canvas.requestRenderAll(); syncAdjustSource(blob); setStatus(kind === 'cw90' ? '已顺时针旋转 90°' : kind === 'ccw90' ? '已逆时针旋转 90°' : kind === 'r180' ? '已旋转 180°' : kind === 'fliph' ? '已水平翻转' : '已垂直翻转'); } catch (err) { setStatus(err.message || '处理失败'); } finally { setAiBusy(''); } }; // ---------- 图像大小(按宽度等比缩放) ---------- const applyResize = async () => { const canvas = fabricRef.current; const base = baseBlobRef.current; const { naturalW: W, naturalH: H } = baseInfoRef.current; const target = Math.round(Number(resizeW)); if (!canvas || !base || !W) return; if (!target || target < 16 || target > 12000) { setStatus('宽度需在 16~12000 之间'); return; } if (target === W) { setStatus('宽度未变化'); return; } const targetH = Math.max(1, Math.round(H * target / W)); if (target * targetH > 80000000) { setStatus('目标尺寸过大(超过 8000 万像素)'); return; } setAiBusy('缩放中…'); try { await ensureAdjustCommitted(); const img = await blobToImage(baseBlobRef.current); const c = document.createElement('canvas'); c.width = target; c.height = targetH; const ctx = c.getContext('2d'); ctx.imageSmoothingEnabled = true; ctx.imageSmoothingQuality = 'high'; ctx.drawImage(img, 0, 0, target, targetH); const blob = await blobFromCanvas(c, pickMime(base)); if (!blob) throw new Error('缩放失败'); canvas.discardActiveObject(); setSelProps(null); await replaceBaseImageSized(blob); setResizeW(String(target)); setStatus(`已缩放为 ${target}×${targetH}`); } catch (err) { setStatus(err.message || '缩放失败'); } finally { setAiBusy(''); } }; // ---------- 保存 ---------- const doSave = async (mode) => { const canvas = fabricRef.current; if (!canvas || saving) return; const { naturalW, displayW } = baseInfoRef.current; if (!naturalW) return; setSaving(true); setStatus(''); try { await ensureAdjustCommitted(); const multiplier = naturalW / displayW; const dataURL = canvas.toDataURL({ format: 'png', multiplier }); const blob = await (await fetch(dataURL)).blob(); const fd = new FormData(); fd.append('image', blob, 'edit.png'); fd.append('libraryId', currentLibraryId); fd.append('path', editingImage.path); fd.append('mode', mode); const resp = await fetch('/api/edit/save', { method: 'POST', headers: getToken() ? { Authorization: `Bearer ${getToken()}` } : {}, body: fd }); const j = await resp.json().catch(() => ({})); if (!resp.ok) throw new Error(j.error || `保存失败 (${resp.status})`); if (j.mode === 'overwrite') { updateImage(editingImage.path, { size: j.size, modifiedAt: j.modifiedAt }); setStatus('已覆盖保存'); } else { bumpRefresh(); imageAPI.getFolders(currentLibraryId) .then((r) => useImageStore.getState().setFolders(r.folders)) .catch(() => {}); setStatus(`已另存为 ${j.filename}`); } dirtyRef.current = false; setTimeout(() => setEditingImage(null), 700); } catch (err) { setStatus(err.message || '保存失败'); } finally { setSaving(false); } }; const handleClose = () => { if (dirtyRef.current && !window.confirm('有未保存的修改,确定关闭?')) return; setEditingImage(null); }; // ---------- 快捷键 ---------- useEffect(() => { if (!editingImage) return; const onKeyDown = (e) => { const tag = document.activeElement && document.activeElement.tagName; if (tag === 'INPUT' || tag === 'TEXTAREA') return; const obj = fabricRef.current && fabricRef.current.getActiveObject(); if (obj && obj.isEditing) return; if (e.key === 'Escape') { if (maskMode) exitMaskMode(); else if (activeTool === 'crop') setActiveTool('select'); else handleClose(); } else if ((e.key === 'Delete' || e.key === 'Backspace') && obj && !maskMode && activeTool !== 'crop') { e.preventDefault(); removeActive(); } }; window.addEventListener('keydown', onKeyDown); return () => window.removeEventListener('keydown', onKeyDown); }, [editingImage, maskMode, activeTool]); if (!editingImage) return null; const isTextSel = selProps && (selProps.type === 'i-text' || selProps.type === 'textbox' || selProps.type === 'text'); const isImgSel = selProps && selProps.type === 'image'; return (
拖动选区移动,拖四角缩放;比例可锁定。Esc 退出。
底图和文字、贴图一起变换。
按宽度等比缩放(16~12000 px)。
拖动即时预览;保存、裁剪、AI 处理时自动按原分辨率应用。
添加后可设置大小、颜色、发光、旋转、透明度
点击插入,插入后可继续修改
插入后可拖拽、缩放、旋转
在图片上涂抹水印区域,然后点击修复
源=所选人脸照片,目标=当前图片(替换最大人脸)
AI 操作只作用于底图,已添加的文字/贴图会保留在上层。