491 lines
20 KiB
JavaScript
491 lines
20 KiB
JavaScript
// 图像处理 — 前端页面
|
||
//
|
||
// 接入方式(对照 App.jsx 里"MIC产品上传"菜单项的写法,同一套路):
|
||
//
|
||
// 1. import { ImageToolPage } from './mic-upload/ImageToolPage';
|
||
// (文件放在 mic-upload/ 目录纯粹是为了跟着已有的部署流程走,跟MIC上传
|
||
// 功能本身没有关系,互不依赖)
|
||
//
|
||
// 2. NAV_GROUPS 里"产品"分组,加一行:
|
||
// { id: 'image-tool', label: '图像处理', icon: ImageIcon },
|
||
// ImageIcon 已经在 App.jsx 顶部 import 过了(Image as ImageIcon,看第7行),
|
||
// 不用再加新的图标import。
|
||
//
|
||
// 3. 渲染switch里加:
|
||
// {view === 'image-tool' && <ImageToolPage />}
|
||
//
|
||
// 纯前端实现,不调用任何服务端接口/AI接口,不消耗token。"导出到文件夹"和
|
||
// "覆盖原图"用的是File System Access API(Chrome/Edge支持,Safari/Firefox
|
||
// 不支持——不支持的浏览器会自动隐藏这两个选项,只保留"打包下载")。
|
||
|
||
import React, { useState, useRef, useEffect, useCallback } from 'react';
|
||
|
||
const LOGO_STORAGE_KEY = 'image-tool-logo-settings-v1';
|
||
const SUPPORTS_FS_ACCESS = typeof window !== 'undefined' && 'showDirectoryPicker' in window;
|
||
|
||
function loadLogoSettings() {
|
||
try {
|
||
const raw = localStorage.getItem(LOGO_STORAGE_KEY);
|
||
if (!raw) return null;
|
||
return JSON.parse(raw);
|
||
} catch (e) {
|
||
return null;
|
||
}
|
||
}
|
||
|
||
function saveLogoSettings(settings) {
|
||
try {
|
||
localStorage.setItem(LOGO_STORAGE_KEY, JSON.stringify(settings));
|
||
} catch (e) { /* 存不下就算了(比如隐私模式),不影响当次使用 */ }
|
||
}
|
||
|
||
function loadImageFromDataUrl(dataUrl) {
|
||
return new Promise((resolve, reject) => {
|
||
const img = new Image();
|
||
img.onload = () => resolve(img);
|
||
img.onerror = reject;
|
||
img.src = dataUrl;
|
||
});
|
||
}
|
||
|
||
function fileToDataUrl(file) {
|
||
return new Promise((resolve, reject) => {
|
||
const reader = new FileReader();
|
||
reader.onload = () => resolve(reader.result);
|
||
reader.onerror = reject;
|
||
reader.readAsDataURL(file);
|
||
});
|
||
}
|
||
|
||
function loadImageFromFile(file) {
|
||
return new Promise((resolve, reject) => {
|
||
const url = URL.createObjectURL(file);
|
||
const img = new Image();
|
||
img.onload = () => resolve(img);
|
||
img.onerror = () => reject(new Error('图片加载失败: ' + file.name));
|
||
img.src = url;
|
||
});
|
||
}
|
||
|
||
// 产品居中 + 白底 + (可选)logo水印,一次画完
|
||
function processImage(srcImage, opts, logoImage, logoSettings) {
|
||
const size = opts.size;
|
||
const marginRatio = opts.margin / 100;
|
||
const usable = size * (1 - 2 * marginRatio);
|
||
const scale = Math.min(usable / srcImage.width, usable / srcImage.height);
|
||
const w = Math.max(1, Math.round(srcImage.width * scale));
|
||
const h = Math.max(1, Math.round(srcImage.height * scale));
|
||
|
||
const canvas = document.createElement('canvas');
|
||
canvas.width = size;
|
||
canvas.height = size;
|
||
const ctx = canvas.getContext('2d');
|
||
ctx.fillStyle = '#ffffff';
|
||
ctx.fillRect(0, 0, size, size);
|
||
ctx.imageSmoothingEnabled = true;
|
||
ctx.imageSmoothingQuality = 'high';
|
||
ctx.drawImage(srcImage, (size - w) / 2, (size - h) / 2, w, h);
|
||
|
||
if (logoImage && logoSettings && logoSettings.enabled) {
|
||
const logoW = size * (logoSettings.sizePct / 100);
|
||
const logoH = logoW * (logoImage.height / logoImage.width);
|
||
const marginPx = size * (logoSettings.marginPct / 100);
|
||
let lx = marginPx;
|
||
let ly = marginPx;
|
||
if (logoSettings.position === 'top-right') { lx = size - logoW - marginPx; ly = marginPx; }
|
||
else if (logoSettings.position === 'bottom-left') { lx = marginPx; ly = size - logoH - marginPx; }
|
||
else if (logoSettings.position === 'bottom-right') { lx = size - logoW - marginPx; ly = size - logoH - marginPx; }
|
||
else if (logoSettings.position === 'center') { lx = (size - logoW) / 2; ly = (size - logoH) / 2; }
|
||
ctx.save();
|
||
ctx.globalAlpha = logoSettings.opacity / 100;
|
||
ctx.drawImage(logoImage, lx, ly, logoW, logoH);
|
||
ctx.restore();
|
||
}
|
||
|
||
return new Promise((resolve) => {
|
||
canvas.toBlob((blob) => resolve(blob), 'image/jpeg', opts.quality / 100);
|
||
});
|
||
}
|
||
|
||
function LogoPanel({ logoDataUrl, setLogoDataUrl, logoSettings, setLogoSettings }) {
|
||
const fileInputRef = useRef(null);
|
||
|
||
async function handlePickLogo(e) {
|
||
const file = e.target.files && e.target.files[0];
|
||
if (!file) return;
|
||
const dataUrl = await fileToDataUrl(file);
|
||
setLogoDataUrl(dataUrl);
|
||
setLogoSettings((prev) => ({ ...prev, enabled: true }));
|
||
}
|
||
|
||
return (
|
||
<div style={{ border: '1px solid var(--line, #ddd)', borderRadius: 6, padding: 10, display: 'flex', flexDirection: 'column', gap: 8 }}>
|
||
<div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
|
||
<input
|
||
type="checkbox"
|
||
checked={logoSettings.enabled}
|
||
disabled={!logoDataUrl}
|
||
onChange={(e) => setLogoSettings((prev) => ({ ...prev, enabled: e.target.checked }))}
|
||
/>
|
||
<span style={{ fontSize: 13, fontWeight: 600 }}>加Logo水印</span>
|
||
</div>
|
||
<div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
|
||
{logoDataUrl && (
|
||
<img src={logoDataUrl} alt="logo" style={{ width: 40, height: 40, objectFit: 'contain', border: '1px solid var(--line, #ddd)', background: '#fff' }} />
|
||
)}
|
||
<button className="btn-ghost" onClick={() => fileInputRef.current?.click()}>
|
||
{logoDataUrl ? '换一张logo' : '上传logo图片'}
|
||
</button>
|
||
<input ref={fileInputRef} type="file" accept="image/*" style={{ display: 'none' }} onChange={handlePickLogo} />
|
||
</div>
|
||
<div style={{ fontSize: 11, color: 'var(--ink-soft, #888)' }}>
|
||
logo图片存在这台电脑浏览器里,下次打开还在,不用重新上传。
|
||
</div>
|
||
{logoDataUrl && (
|
||
<>
|
||
<label style={{ fontSize: 12 }}>
|
||
位置:
|
||
<select
|
||
value={logoSettings.position}
|
||
onChange={(e) => setLogoSettings((prev) => ({ ...prev, position: e.target.value }))}
|
||
style={{ marginLeft: 6 }}
|
||
>
|
||
<option value="top-left">左上角</option>
|
||
<option value="top-right">右上角</option>
|
||
<option value="bottom-left">左下角</option>
|
||
<option value="bottom-right">右下角</option>
|
||
<option value="center">居中</option>
|
||
</select>
|
||
</label>
|
||
<label style={{ fontSize: 12 }}>
|
||
大小:{logoSettings.sizePct}% 画布宽度
|
||
<input
|
||
type="range" min="5" max="50" value={logoSettings.sizePct}
|
||
onChange={(e) => setLogoSettings((prev) => ({ ...prev, sizePct: Number(e.target.value) }))}
|
||
style={{ width: '100%' }}
|
||
/>
|
||
</label>
|
||
<label style={{ fontSize: 12 }}>
|
||
透明度:{logoSettings.opacity}%
|
||
<input
|
||
type="range" min="10" max="100" value={logoSettings.opacity}
|
||
onChange={(e) => setLogoSettings((prev) => ({ ...prev, opacity: Number(e.target.value) }))}
|
||
style={{ width: '100%' }}
|
||
/>
|
||
</label>
|
||
<label style={{ fontSize: 12 }}>
|
||
边距:{logoSettings.marginPct}%
|
||
<input
|
||
type="range" min="0" max="15" value={logoSettings.marginPct}
|
||
onChange={(e) => setLogoSettings((prev) => ({ ...prev, marginPct: Number(e.target.value) }))}
|
||
style={{ width: '100%' }}
|
||
/>
|
||
</label>
|
||
</>
|
||
)}
|
||
</div>
|
||
);
|
||
}
|
||
|
||
export function ImageToolPage() {
|
||
const [size, setSize] = useState(1000);
|
||
const [margin, setMargin] = useState(4);
|
||
const [quality, setQuality] = useState(95);
|
||
const [exportMode, setExportMode] = useState('download'); // download | folder | overwrite
|
||
const [items, setItems] = useState([]); // { name, outName, srcImage, blob, url, handle? }
|
||
const [status, setStatus] = useState('');
|
||
const [statusErr, setStatusErr] = useState(false);
|
||
const [busy, setBusy] = useState(false);
|
||
const dropRef = useRef(null);
|
||
const fileInputRef = useRef(null);
|
||
|
||
const [logoDataUrl, setLogoDataUrl] = useState(null);
|
||
const [logoImage, setLogoImage] = useState(null);
|
||
const [logoSettings, setLogoSettings] = useState({
|
||
enabled: false, position: 'bottom-right', sizePct: 18, opacity: 100, marginPct: 4,
|
||
});
|
||
|
||
// 首次挂载时读一下之前存过的logo设置
|
||
useEffect(() => {
|
||
const saved = loadLogoSettings();
|
||
if (saved) {
|
||
if (saved.dataUrl) setLogoDataUrl(saved.dataUrl);
|
||
if (saved.settings) setLogoSettings(saved.settings);
|
||
}
|
||
}, []);
|
||
|
||
// logo图片变了就重新加载成Image对象;设置变了就存进localStorage
|
||
useEffect(() => {
|
||
if (logoDataUrl) {
|
||
loadImageFromDataUrl(logoDataUrl).then(setLogoImage).catch(() => setLogoImage(null));
|
||
} else {
|
||
setLogoImage(null);
|
||
}
|
||
}, [logoDataUrl]);
|
||
|
||
useEffect(() => {
|
||
saveLogoSettings({ dataUrl: logoDataUrl, settings: logoSettings });
|
||
}, [logoDataUrl, logoSettings]);
|
||
|
||
function say(msg, err) {
|
||
setStatus(msg);
|
||
setStatusErr(!!err);
|
||
}
|
||
|
||
const readOpts = useCallback(() => ({
|
||
size: Math.max(100, Math.min(4000, Number(size) || 1000)),
|
||
margin: Math.max(0, Math.min(40, Number(margin) || 0)),
|
||
quality: Math.max(10, Math.min(100, Number(quality) || 95)),
|
||
}), [size, margin, quality]);
|
||
|
||
function outNameFor(originalName, idx) {
|
||
const base = (originalName || ('image_' + idx)).replace(/\.[^.]+$/, '');
|
||
return base + '.jpg';
|
||
}
|
||
|
||
// ---- 模式1/2:普通读取(下载 / 存到新文件夹),源文件只读就够 ----
|
||
async function addFilesReadOnly(fileList) {
|
||
const files = Array.from(fileList).filter((f) => f.type.startsWith('image/'));
|
||
if (!files.length) return;
|
||
setBusy(true);
|
||
say(`处理中... 0/${files.length}`);
|
||
const opts = readOpts();
|
||
const next = [];
|
||
for (let i = 0; i < files.length; i++) {
|
||
const file = files[i];
|
||
try {
|
||
const img = await loadImageFromFile(file);
|
||
const blob = await processImage(img, opts, logoImage, logoSettings);
|
||
const url = URL.createObjectURL(blob);
|
||
next.push({ name: file.name, srcImage: img, outName: outNameFor(file.name, items.length + i), blob, url });
|
||
} catch (e) {
|
||
say(String(e.message || e), true);
|
||
}
|
||
say(`处理中... ${i + 1}/${files.length}`);
|
||
}
|
||
setItems((prev) => [...prev, ...next]);
|
||
say(`完成,共 ${items.length + next.length} 张`);
|
||
setBusy(false);
|
||
}
|
||
|
||
// ---- 模式3:覆盖原图,必须用File System Access拿到可写句柄 ----
|
||
async function pickFilesForOverwrite() {
|
||
if (!SUPPORTS_FS_ACCESS) { say('这个浏览器不支持"覆盖原图",换Chrome/Edge', true); return; }
|
||
let handles;
|
||
try {
|
||
handles = await window.showOpenFilePicker({
|
||
multiple: true,
|
||
types: [{ description: 'Images', accept: { 'image/*': ['.png', '.jpg', '.jpeg', '.webp'] } }],
|
||
});
|
||
} catch (e) {
|
||
return; // 用户取消选择,不算错误
|
||
}
|
||
setBusy(true);
|
||
say(`处理中... 0/${handles.length}`);
|
||
const opts = readOpts();
|
||
const next = [];
|
||
for (let i = 0; i < handles.length; i++) {
|
||
const handle = handles[i];
|
||
try {
|
||
const file = await handle.getFile();
|
||
const img = await loadImageFromFile(file);
|
||
const blob = await processImage(img, opts, logoImage, logoSettings);
|
||
const url = URL.createObjectURL(blob);
|
||
next.push({ name: file.name, srcImage: img, outName: file.name, blob, url, handle });
|
||
} catch (e) {
|
||
say(String(e.message || e), true);
|
||
}
|
||
say(`处理中... ${i + 1}/${handles.length}`);
|
||
}
|
||
setItems((prev) => [...prev, ...next]);
|
||
say(`已处理 ${next.length} 张,点"保存全部"会直接覆盖原文件`);
|
||
setBusy(false);
|
||
}
|
||
|
||
async function reprocessAll() {
|
||
if (!items.length) return;
|
||
setBusy(true);
|
||
say('重新处理中...');
|
||
const opts = readOpts();
|
||
const updated = [];
|
||
for (const it of items) {
|
||
const blob = await processImage(it.srcImage, opts, logoImage, logoSettings);
|
||
URL.revokeObjectURL(it.url);
|
||
updated.push({ ...it, blob, url: URL.createObjectURL(blob) });
|
||
}
|
||
setItems(updated);
|
||
say(`已按新设置重新处理 ${updated.length} 张`);
|
||
setBusy(false);
|
||
}
|
||
|
||
async function handleExport() {
|
||
if (!items.length) { say('还没有图片', true); return; }
|
||
setBusy(true);
|
||
try {
|
||
if (exportMode === 'overwrite') {
|
||
for (const it of items) {
|
||
if (!it.handle) continue;
|
||
const writable = await it.handle.createWritable();
|
||
await writable.write(it.blob);
|
||
await writable.close();
|
||
}
|
||
say(`已覆盖保存 ${items.length} 张原图`);
|
||
} else if (exportMode === 'folder') {
|
||
let dirHandle;
|
||
try {
|
||
dirHandle = await window.showDirectoryPicker();
|
||
} catch (e) {
|
||
setBusy(false);
|
||
return; // 取消选择文件夹
|
||
}
|
||
for (const it of items) {
|
||
const fileHandle = await dirHandle.getFileHandle(it.outName, { create: true });
|
||
const writable = await fileHandle.createWritable();
|
||
await writable.write(it.blob);
|
||
await writable.close();
|
||
}
|
||
say(`已保存 ${items.length} 张到所选文件夹`);
|
||
} else {
|
||
// 兼容所有浏览器的兜底方式:一张张触发普通浏览器下载,不用zip
|
||
// (File System Access不支持的浏览器,比如Safari,走这条路)
|
||
for (const it of items) {
|
||
const a = document.createElement('a');
|
||
a.href = it.url;
|
||
a.download = it.outName;
|
||
document.body.appendChild(a);
|
||
a.click();
|
||
document.body.removeChild(a);
|
||
await new Promise((r) => setTimeout(r, 150)); // 浏览器一次性弹太多下载容易被拦截,错开一点
|
||
}
|
||
say(`已触发下载 ${items.length} 张(看浏览器下载记录/默认下载文件夹)`);
|
||
}
|
||
} catch (e) {
|
||
say(`导出失败: ${e.message || e}`, true);
|
||
} finally {
|
||
setBusy(false);
|
||
}
|
||
}
|
||
|
||
function clearAll() {
|
||
items.forEach((it) => URL.revokeObjectURL(it.url));
|
||
setItems([]);
|
||
say('');
|
||
}
|
||
|
||
function removeOne(idx) {
|
||
setItems((prev) => {
|
||
const next = [...prev];
|
||
URL.revokeObjectURL(next[idx].url);
|
||
next.splice(idx, 1);
|
||
return next;
|
||
});
|
||
}
|
||
|
||
function handleDrop(e) {
|
||
e.preventDefault();
|
||
if (exportMode === 'overwrite') {
|
||
say('"覆盖原图"模式需要点下面的按钮选文件,不支持拖拽(拖拽拿不到可写权限)', true);
|
||
return;
|
||
}
|
||
if (e.dataTransfer?.files) addFilesReadOnly(e.dataTransfer.files);
|
||
}
|
||
|
||
return (
|
||
<div className="panel" style={{ display: 'flex', gap: 16, height: '100%' }}>
|
||
<div style={{ width: 300, flexShrink: 0, display: 'flex', flexDirection: 'column', gap: 12, overflowY: 'auto' }}>
|
||
<div className="panel-title">图像处理</div>
|
||
<div style={{ fontSize: 11, color: 'var(--ink-soft, #888)' }}>
|
||
纯浏览器本地处理,不上传到任何服务器,不消耗AI额度。
|
||
</div>
|
||
|
||
<div style={{ display: 'flex', gap: 8 }}>
|
||
<label style={{ fontSize: 12, flex: 1 }}>
|
||
画布边长
|
||
<input type="number" value={size} onChange={(e) => setSize(e.target.value)} style={{ width: '100%' }} />
|
||
</label>
|
||
<label style={{ fontSize: 12, flex: 1 }}>
|
||
留白%
|
||
<input type="number" value={margin} onChange={(e) => setMargin(e.target.value)} style={{ width: '100%' }} />
|
||
</label>
|
||
<label style={{ fontSize: 12, flex: 1 }}>
|
||
质量%
|
||
<input type="number" value={quality} onChange={(e) => setQuality(e.target.value)} style={{ width: '100%' }} />
|
||
</label>
|
||
</div>
|
||
|
||
<LogoPanel
|
||
logoDataUrl={logoDataUrl}
|
||
setLogoDataUrl={setLogoDataUrl}
|
||
logoSettings={logoSettings}
|
||
setLogoSettings={setLogoSettings}
|
||
/>
|
||
|
||
<div style={{ fontSize: 13, fontWeight: 600 }}>导出方式</div>
|
||
<label style={{ fontSize: 12, display: 'flex', alignItems: 'center', gap: 6 }}>
|
||
<input type="radio" checked={exportMode === 'download'} onChange={() => setExportMode('download')} />
|
||
触发浏览器下载(兼容所有浏览器)
|
||
</label>
|
||
<label style={{ fontSize: 12, display: 'flex', alignItems: 'center', gap: 6, opacity: SUPPORTS_FS_ACCESS ? 1 : 0.4 }}>
|
||
<input type="radio" disabled={!SUPPORTS_FS_ACCESS} checked={exportMode === 'folder'} onChange={() => setExportMode('folder')} />
|
||
存到指定文件夹(比如桌面){!SUPPORTS_FS_ACCESS && '(此浏览器不支持)'}
|
||
</label>
|
||
<label style={{ fontSize: 12, display: 'flex', alignItems: 'center', gap: 6, opacity: SUPPORTS_FS_ACCESS ? 1 : 0.4 }}>
|
||
<input type="radio" disabled={!SUPPORTS_FS_ACCESS} checked={exportMode === 'overwrite'} onChange={() => setExportMode('overwrite')} />
|
||
直接覆盖原图(谨慎,会修改源文件,建议先备份){!SUPPORTS_FS_ACCESS && '(此浏览器不支持)'}
|
||
</label>
|
||
|
||
{exportMode === 'overwrite' ? (
|
||
<button className="btn-primary" disabled={busy} onClick={pickFilesForOverwrite}>选择要覆盖的图片</button>
|
||
) : (
|
||
<div
|
||
ref={dropRef}
|
||
onClick={() => fileInputRef.current?.click()}
|
||
onDragOver={(e) => e.preventDefault()}
|
||
onDrop={handleDrop}
|
||
style={{
|
||
border: '2px dashed var(--line, #ddd)', borderRadius: 8, padding: 16,
|
||
textAlign: 'center', fontSize: 12, color: 'var(--ink-soft, #888)', cursor: 'pointer',
|
||
}}
|
||
>
|
||
拖图片进来,或点击选择(可多选)
|
||
<input
|
||
ref={fileInputRef} type="file" accept="image/*" multiple style={{ display: 'none' }}
|
||
onChange={(e) => addFilesReadOnly(e.target.files)}
|
||
/>
|
||
</div>
|
||
)}
|
||
|
||
{items.length > 0 && (
|
||
<>
|
||
<button className="btn-ghost" disabled={busy} onClick={reprocessAll}>按新设置重新处理已选图片</button>
|
||
<button className="btn-primary" disabled={busy} onClick={handleExport}>
|
||
{exportMode === 'overwrite' ? '保存全部(覆盖原图)' : exportMode === 'folder' ? '保存全部到文件夹' : '下载全部'}
|
||
</button>
|
||
<button className="btn-ghost" onClick={clearAll}>清空</button>
|
||
</>
|
||
)}
|
||
|
||
{status && <div style={{ fontSize: 12, color: statusErr ? 'var(--danger, #d33)' : 'var(--ink-soft, #888)' }}>{status}</div>}
|
||
</div>
|
||
|
||
<div style={{ flex: 1, overflowY: 'auto' }}>
|
||
{items.length === 0 ? (
|
||
<div style={{ color: 'var(--ink-soft, #888)', textAlign: 'center', marginTop: 60 }}>还没有图片</div>
|
||
) : (
|
||
<div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(160px, 1fr))', gap: 12 }}>
|
||
{items.map((it, idx) => (
|
||
<div key={idx} style={{ border: '1px solid var(--line, #ddd)', borderRadius: 8, overflow: 'hidden' }}>
|
||
<img src={it.url} alt={it.outName} style={{ width: '100%', aspectRatio: '1 / 1', objectFit: 'contain', background: '#fff', display: 'block' }} />
|
||
<div style={{ padding: 6, fontSize: 11, color: 'var(--ink-soft, #888)', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
|
||
<span style={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{it.outName}</span>
|
||
<button className="btn-ghost" style={{ fontSize: 11, padding: '2px 6px' }} onClick={() => removeOne(idx)}>移除</button>
|
||
</div>
|
||
</div>
|
||
))}
|
||
</div>
|
||
)}
|
||
</div>
|
||
</div>
|
||
);
|
||
}
|