Compare commits

...
Author SHA1 Message Date
jinghui 7b6513c7de feat(ai-gen): 图片编辑器 — 文字发光/旋转、图片叠加、拖角改大小
- 新增 img-editor.vue(670行): 文字图层(大小/发光/旋转/拖动) + 图片图层(叠加/缩放)
- ai-gen.vue 生成结果增加「编辑图片」入口, 1024×1024 导出
2026-11-15 01:56:28 +08:00
jinghui 3aefc2633b fix(pdf-tools): 水印中文显示成??? — 嵌入Droid Sans Fallback中文字体子集
- Helvetica(WinAnsi)无法编码中文被替换为?, 改为含非西文字符时按需加载
  public/fonts/DroidSansFallback.ttf + @cantoo/fontkit embedFont(subset)
- 新增依赖 @cantoo/fontkit; 纯英文水印保持原Helvetica路径不下载字体
- 浏览器端到端验证: 中文文本层HAS_CN=true无???, 英文回归通过
2026-11-14 22:42:27 +08:00
jinghui 78c348198d feat: 后台文件管理按功能查询 — 功能下拉(kind筛选,带计数,与来源组合), 类型列中文化; relay副本同步 2026-11-14 21:46:21 +08:00
9 changed files with 806 additions and 9 deletions

No files matched your search

+23
View File
@@ -89,6 +89,29 @@
- AI 配图复用 `/relay/ai/gen-image` 与每日免费生图额度,按图框宽高比自动匹配上游尺寸档位。
- 完成后一键导出 1080×1440 PNG(旋转图层同步导出)。授权应用,支持每日免费试用。
### 后台文件管理·按功能查询(2026.11 新增)
管理后台「📁 文件管理」在来源筛选旁新增**功能下拉**:按文件的 `kind`(AI 生图 / AI 换脸 / AI 海报 / 文字生图 / 标签设计 / 图片工具 / PDF 工具 / 未分类…)过滤,选项自带计数(如「AI 生图(65)」),计数随来源筛选联动;与「来源」下拉可组合使用,选择后页码自动回到第 1 页。
- 接口:`GET /admin/files?kind=<值>`,新增返回 `kinds: [{k, n}]` 分布统计(kind 过滤前统计,保证计数是当前来源下的全集);`kind=__none__` 表示未分类(无 kind 的用户根目录文件);
- 表格「类型」列同步显示中文功能名(原为 kind 英文原值);
- 仍带 `X-Admin-Token` 鉴权,无令牌 403。
### PDF 水印支持中文(2026.11 修复)
**问题**:PDF 工具「添加水印」输入中文后,生成的 PDF 里中文显示成 `???`。
**原因**:水印文字用 `embedFont('Helvetica')` 绘制——Helvetica 是 PDF 西文标准 14 字体(WinAnsi 编码),无法编码中文,pdf-lib 把超出编码范围的字符全部替换成 `?`。
**修复**(`src/tools/pdf-tools/pdf-tools.vue`):
- 新增依赖 `@cantoo/fontkit`(`@cantoo/pdf-lib` 官方推荐的 fontkit 实现);
- 中文字体 Droid Sans Fallback(4MB,覆盖 CJK,系统自带 `/usr/share/fonts/truetype/droid/`)放入 `public/fonts/DroidSansFallback.ttf`,由 nginx 直接提供;
- 水印文字含非西文字符(`charCodeAt > 0xFF`)时才按需 `fetch` 字体并 `registerFontkit` + `embedFont(bytes, { subset: true })`——子集只嵌入用到的字形,输出 PDF 增量很小(实测 3.5KB);纯英文水印仍走原 Helvetica 路径,不下载字体;
- 字节缓存在模块级变量,同一次页面会话只拉一次。
**验证**(浏览器端到端):上传测试 PDF → 中文水印「内部机密禁止外传」→ 执行 → pdfjs 提取文本层 `HAS_CN=true`、无 `???`;pdftoppm 渲染截图确认斜向水印字形正常;英文水印「CONFIDENTIAL 2026」回归通过(走 Helvetica,输出 1.6KB 无字体子集)。
### 历史记录 100 条上限(2026.11 新增)
所有功能里的历史记录最多显示 100 条(按时间倒序取最新 100 条):
+15 -2
View File
@@ -1396,6 +1396,7 @@ def admin_api(method: str, sub: str, payload: dict, handler):
qs = parse.parse_qs(parse.urlparse(handler.path).query)
username = (qs.get("username") or [""])[0]
scope = (qs.get("scope") or [""])[0]
kind = (qs.get("kind") or [""])[0] # 按功能筛选:gen/face-swap/poster/... 或 __none__=未分类
try:
page = max(1, int((qs.get("page") or ["1"])[0]))
except Exception:
@@ -1430,7 +1431,7 @@ def admin_api(method: str, sub: str, payload: dict, handler):
if not os.path.isdir(fdir):
continue
for root, _d, fs in os.walk(fdir):
kind = os.path.basename(root) if root != fdir else ""
ukind = os.path.basename(root) if root != fdir else ""
for f in fs:
fp = os.path.join(root, f)
try:
@@ -1440,7 +1441,7 @@ def admin_api(method: str, sub: str, payload: dict, handler):
nm, mi = db_meta.get((u, f), (f, ""))
ext = os.path.splitext(nm)[1].lower().lstrip(".")
items.append({
"id": f, "name": nm, "kind": kind, "size": st.st_size,
"id": f, "name": nm, "kind": ukind, "size": st.st_size,
"mtime": int(st.st_mtime), "source": "user", "username": u,
"mime": mi, "is_image": mi.startswith("image/") or ext in IMG_EXT,
"file_type": (ext or (mi.split("/")[-1] if mi else "file") or "file").upper(),
@@ -1499,6 +1500,17 @@ def admin_api(method: str, sub: str, payload: dict, handler):
"file_type": (ext or "file").upper(),
"path": os.path.relpath(fp, DATA_DIR),
})
# 按功能(kind)分布:在 kind 过滤之前统计,下拉计数反映 scope/username 下的全集
_kc: dict = {}
for x in items:
k = str(x.get("kind") or "").strip() or "__none__"
_kc[k] = _kc.get(k, 0) + 1
kinds = sorted(({"k": k, "n": n} for k, n in _kc.items()), key=lambda y: (-y["n"], y["k"]))
if kind:
if kind == "__none__":
items = [x for x in items if not str(x.get("kind") or "").strip()]
else:
items = [x for x in items if str(x.get("kind") or "").strip() == kind]
items.sort(key=lambda x: -x["mtime"])
total = len(items)
total_size = sum(x["size"] for x in items)
@@ -1509,6 +1521,7 @@ def admin_api(method: str, sub: str, payload: dict, handler):
return 200, {"code": 200, "message": "ok", "data": {
"files": page_items, "total": total, "total_size": total_size,
"page": page, "page_size": page_size, "pages": pages, "count": len(page_items),
"kinds": kinds,
}}
if method == "POST" and sub == "/cleanup":
+1
View File
@@ -37,6 +37,7 @@
"release": "node ./scripts/release.mjs"
},
"dependencies": {
"@cantoo/fontkit": "^2.0.12",
"@cantoo/pdf-lib": "^2.11.1",
"@it-tools/bip39": "^0.0.4",
"@it-tools/oggen": "^1.3.0",
+35 -4
View File
@@ -11,6 +11,9 @@ importers:
.:
dependencies:
'@cantoo/fontkit':
specifier: ^2.0.12
version: 2.0.12
'@cantoo/pdf-lib':
specifier: ^2.11.1
version: 2.11.1(html-entities@2.6.0)
@@ -1184,6 +1187,9 @@ packages:
resolution: {integrity: sha512-Vj1jF3cPfxg7OAfoI7QnVKLoILlm2JF9pnVHrX8qx7AHMiYWT+NDAA7jChlNgRS4WTLc/fD1lXLmPixluj+3Gg==}
engines: {node: '>=6.9.0'}
'@cantoo/fontkit@2.0.12':
resolution: {integrity: sha512-B9ZE4pA3cUf3pzn7UaPCtjyejd1ie16SLquCqdlGQiDncFgn8iD29dU9vD3dSgKkxAUx2ttvjg/li9JVkj5+fQ==}
'@cantoo/pdf-lib@2.11.1':
resolution: {integrity: sha512-lYuRJFfXgoP8WVE8HYSeoLfDcnSXmjMLmdZS7YvmYHngbcZfiqDOruHrZBqjYizkrNa4ad1yW4WCrPYyb26T3Q==}
peerDependencies:
@@ -2660,6 +2666,9 @@ packages:
resolution: {integrity: sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA==}
engines: {node: '>=8'}
brotli@1.3.3:
resolution: {integrity: sha512-oTKjJdShmDuGW94SyyaoQvAjf30dZaHnjJ8uAF+u2/vGJkJbJPJAT1gDiOJP5v1Zb6f9KEyW/1HpuaWIXtGHPg==}
browserslist@4.21.9:
resolution: {integrity: sha512-M0MFoZzbUrRU4KNfCrDLnvyE7gub+peetoTid3TBIqtunaDJyXlwhakT+/VkvSXcfIzFfK/nkCs4nmyTmxdNSg==}
engines: {node: ^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7}
@@ -3114,6 +3123,9 @@ packages:
resolution: {integrity: sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==}
engines: {node: '>=8'}
dfa@1.2.0:
resolution: {integrity: sha512-ED3jP8saaweFTjeGX8HQPjeC1YYyZs98jGNZx6IiBvxW7JG5v492kamAQB3m2wop07CvU/RQmzcKr6bgcC5D/Q==}
diff-sequences@29.4.3:
resolution: {integrity: sha512-ofrBgwpPhCD85kMKtE9RYFFq6OC1A89oW2vvgWZNCwxrUpRUILopY7lsYyMDSjc8g6U6aiO0Qubg6r4Wgt5ZnA==}
engines: {node: ^14.15.0 || ^16.10.0 || >=18.0.0}
@@ -3849,6 +3861,7 @@ packages:
image-size@0.5.5:
resolution: {integrity: sha512-6TDAlDPZxUFCv+fuOkIoXT/V/f3Qbq8e37p+YOiYrUv3v9cc3/6x78VdfPgFVaB9dZYeLUfKgHRebpkm/oP2VQ==}
engines: {node: '>=0.10.0'}
deprecated: Please migrate to image-size@2.x
hasBin: true
import-fresh@3.3.0:
@@ -5064,6 +5077,9 @@ packages:
resolution: {integrity: sha512-l+sSefzHpj5qimhFSE5a8nufZYAM3sBSVMAPtYkmC+4EH2anSGaEMXSD0izRQbu9nfyQ9y5JrVmp7E8oZrUjvA==}
engines: {node: '>=8'}
restructure@3.0.2:
resolution: {integrity: sha512-gSfoiOEA0VPE6Tukkrr7I0RBdE0s7H1eFCDBk05l1KIQT1UIKNc5JZy6jdyW6eYH3aR3g5b3PuL77rq0hvwtAw==}
ret@0.1.15:
resolution: {integrity: sha512-TTlYpa+OL+vMMNG24xSlQGEJ3B/RzEfUlLct7b5G/ytav+wPrplCpVMFuwzXbkecJrb6IYo1iFb0S9v37754mg==}
engines: {node: '>=0.12'}
@@ -7295,6 +7311,13 @@ snapshots:
'@babel/helper-string-parser': 7.29.7
'@babel/helper-validator-identifier': 7.29.7
'@cantoo/fontkit@2.0.12':
dependencies:
brotli: 1.3.3
dfa: 1.2.0
fflate: 0.8.3
restructure: 3.0.2
'@cantoo/pdf-lib@2.11.1(html-entities@2.6.0)':
dependencies:
culori: 4.0.2
@@ -7461,7 +7484,7 @@ snapshots:
'@eslint/eslintrc@2.1.2':
dependencies:
ajv: 6.12.6
debug: 4.3.4
debug: 4.4.0
espree: 9.6.1
globals: 13.20.0
ignore: 5.2.4
@@ -7477,7 +7500,7 @@ snapshots:
'@humanwhocodes/config-array@0.11.10':
dependencies:
'@humanwhocodes/object-schema': 1.2.1
debug: 4.3.4
debug: 4.4.0
minimatch: 3.1.2
transitivePeerDependencies:
- supports-color
@@ -9018,6 +9041,10 @@ snapshots:
dependencies:
fill-range: 7.1.1
brotli@1.3.3:
dependencies:
base64-js: 1.5.1
browserslist@4.21.9:
dependencies:
caniuse-lite: 1.0.30001504
@@ -9486,6 +9513,8 @@ snapshots:
detect-libc@2.1.2:
optional: true
dfa@1.2.0: {}
diff-sequences@29.4.3: {}
dijkstrajs@1.0.2: {}
@@ -10345,14 +10374,14 @@ snapshots:
dependencies:
'@tootallnate/once': 2.0.0
agent-base: 6.0.2
debug: 4.3.4
debug: 4.4.0
transitivePeerDependencies:
- supports-color
https-proxy-agent@5.0.1:
dependencies:
agent-base: 6.0.2
debug: 4.3.4
debug: 4.4.0
transitivePeerDependencies:
- supports-color
@@ -11690,6 +11719,8 @@ snapshots:
onetime: 5.1.2
signal-exit: 3.0.7
restructure@3.0.2: {}
ret@0.1.15: {}
ret@0.2.2: {}
Binary file not shown.
+18 -1
View File
@@ -109,6 +109,17 @@ async function loadOverview() {
// ============ 文件管理(默认全量聚合,50 条/页自动分页)============
const fileUser = ref(''); // ''=全部, '__gen__'=AI生成, 其他=指定用户
const fileKind = ref(''); // 按功能筛选:''=全部功能, '__none__'=未分类, 其他=kind 原值
const fileKinds = ref<{ k: string; n: number }[]>([]); // 后端返回的 kind 分布(带计数)
const KIND_LABELS: Record<string, string> = {
gen: 'AI 生图', edit: 'AI 图片编辑', 'face-swap': 'AI 换脸', retouch: 'AI 修图',
'text-edit': 'AI 文字编辑', poster: 'AI 海报', 'text-to-image': '文字生图',
'image-lab': 'AI 图片实验室', 'image-tools': '图片工具', 'label-designer': '标签设计',
'pdf-tools': 'PDF 工具', ocr: 'OCR 识别', mcp: 'MCP 产出', __none__: '未分类',
};
function kindLabel(k: string) {
return KIND_LABELS[k] || k || '未分类';
}
const fileList = ref<any[]>([]);
const fileTotal = ref(0); // 合计字节数
const fileCount = ref(0); // 总记录数
@@ -123,10 +134,12 @@ async function loadFiles() {
const q = new URLSearchParams();
if (fileUser.value === '__gen__') q.set('scope', 'gen');
else if (fileUser.value) q.set('username', fileUser.value);
if (fileKind.value) q.set('kind', fileKind.value);
q.set('page', String(filePage.value));
q.set('page_size', String(FILE_PAGE_SIZE));
const b = await api(`/admin/files?${q}`);
fileList.value = b.data?.files ?? [];
fileKinds.value = b.data?.kinds ?? [];
fileTotal.value = b.data?.total_size ?? 0;
fileCount.value = b.data?.total ?? 0;
filePages.value = b.data?.pages ?? 1;
@@ -641,6 +654,10 @@ function switchTab(id: 'overview' | 'files' | 'usage' | 'mcp' | 'storage' | 'rec
<option value="__gen__">仅 AI 生成图片(换脸/生图/海报)</option>
<option v-for="u in users" :key="u.username" :value="u.username">仅 {{ u.username }}</option>
</select>
<select v-model="fileKind" class="adm-select" title="按功能查询文件" @change="filePage = 1; loadFiles()">
<option value="">全部功能</option>
<option v-for="k in fileKinds" :key="k.k" :value="k.k">{{ kindLabel(k.k) }}({{ k.n }})</option>
</select>
<span class="adm-sub">共 {{ fileCount }} 条记录 · 合计 {{ fmtSize(fileTotal) }}</span>
<span v-if="filePages > 1" class="adm-pager">
<button class="adm-btn adm-btn-sm" :disabled="filePage <= 1" @click="gotoFilePage(filePage - 1)">‹ 上一页</button>
@@ -680,7 +697,7 @@ function switchTab(id: 'overview' | 'files' | 'usage' | 'mcp' | 'storage' | 'rec
</td>
<td class="adm-fname" :title="f.prompt || f.name">{{ f.name }}</td>
<td>{{ fileOwner(f) }}</td>
<td>{{ f.kind || '-' }}</td>
<td>{{ kindLabel(f.kind || '__none__') }}</td>
<td>{{ fmtSize(f.size) }}</td>
<td>{{ fmtTime(f.mtime) }}</td>
<td class="adm-ops">
+21
View File
@@ -1,6 +1,7 @@
<script setup lang="ts">
import { getMachineId, licenseHeaders } from '@/tools/license/license';
import { authHdr } from '@/tools/img-hist/img-hist';
import ImgEditor from './img-editor.vue';
const models = ref<{ id: string; i2i: boolean; custom?: boolean }[]>([]);
const model = ref(''); // 打开页面默认选中列表第一个模型
@@ -9,6 +10,9 @@ const loading = ref(false);
const error = ref('');
const resultUrl = ref('');
const promptEn = ref(''); // 中文提示词自动转英文后的实际发送内容
const editorOpen = ref(false); // 图片编辑器(文字发光/旋转、图片叠加、拖角改大小)
// 编辑器导出保存成功 → 刷新右栏历史
function onEdited() { loadHistory(); }
// ---------- 自定义提供商(KEY 只存本机浏览器 localStorage) ----------
const PROVIDER_KEY = 'it-tools-ai-provider';
@@ -479,6 +483,7 @@ async function generate() {
<img :src="resultUrl" alt="生成结果">
<div class="gen-img-acts">
<a class="gen-dl" :href="dlHref" target="_blank" rel="noopener" download>⬇ 下载图片</a>
<button class="gen-dl gen-edit" type="button" @click="editorOpen = true">✏️ 编辑图片</button>
<a class="gen-dl" :href="resultUrl" target="_blank" rel="noopener">🔗 新窗口打开</a>
<span v-if="promptEn" class="gen-tr" :title="promptEn">🌐 已自动转英文发送(悬停查看)</span>
</div>
@@ -507,6 +512,15 @@ async function generate() {
</div>
</div>
</div>
<!-- 图片编辑器:文字发光/旋转、自己的图片叠加、拖角改大小,导出原分辨率并落盘历史 -->
<ImgEditor
v-if="editorOpen && resultUrl"
:src="resultUrl"
:prompt="promptEn || prompt"
@close="editorOpen = false"
@saved="onEdited"
/>
</template>
<style scoped lang="less">
@@ -1031,6 +1045,13 @@ async function generate() {
font-weight: 600;
text-decoration: none;
}
.gen-edit {
border: none;
cursor: pointer;
font-family: inherit;
&:hover { background: rgba(14, 165, 160, 0.22); }
}
}
.gen-empty {
+670
View File
@@ -0,0 +1,670 @@
<script setup lang="ts">
import { computed, onBeforeUnmount, onMounted, ref } from 'vue';
import { getMachineId, licenseHeaders } from '@/tools/license/license';
import { authHdr } from '@/tools/img-hist/img-hist';
// AI 生图结果编辑器:底图=生成图(锁定),叠加文字/图片图层
// 坐标系=底图原始像素,显示按 scale 缩放 → 导出即原图分辨率所见即所得
// 与海报编辑器的差异:拖右下角手柄直接改大小(文字改字号、图片等比),发光+旋转
const props = defineProps<{ src: string; prompt?: string }>();
const emit = defineEmits<{ close: []; saved: [url: string] }>();
const FONT_STACK = '"Microsoft YaHei", "PingFang SC", "Noto Sans SC", sans-serif';
type L = any; // 图层运行时对象(text / image 联合,编辑期动态增删)
const stageEl = ref<HTMLElement | null>(null);
const natW = ref(0);
const natH = ref(0);
const scale = ref(1);
const layers = ref<L[]>([]);
const selId = ref('');
const exporting = ref(false);
const edError = ref('');
const fileEl = ref<HTMLInputElement | null>(null);
let fileMode: 'add' | 'replace' = 'add';
let uid = 0;
let bgImg: HTMLImageElement | null = null;
const sel = computed(() => layers.value.find((l) => l.id === selId.value) || null);
// ---------- 底图加载 / 自适应缩放 ----------
function loadBg() {
const i = new Image();
i.onload = () => {
bgImg = i;
natW.value = i.naturalWidth;
natH.value = i.naturalHeight;
fit();
};
i.onerror = () => { edError.value = '底图加载失败'; };
i.src = props.src;
}
function fit() {
const el = stageEl.value;
if (!el || !natW.value) return;
const w = Math.max(el.clientWidth - 24, 120);
const h = Math.max(el.clientHeight - 24, 120);
scale.value = Math.max(Math.min(w / natW.value, h / natH.value), 0.05);
}
const handleStyle = computed(() => {
const s = scale.value || 1;
const sz = Math.max(14 / s, 10);
return { width: sz + 'px', height: sz + 'px', right: -sz / 2 + 'px', bottom: -sz / 2 + 'px', borderWidth: Math.max(2 / s, 1.5) + 'px' };
});
// ---------- 文字排版(预览与导出共用,保证换行一致) ----------
const mc = document.createElement('canvas');
const mctx = mc.getContext('2d')!;
const wrapCache = new Map<string, string[]>();
const CLOSE_PUNCT = ',。、!?:;)】」』,.!?;:)';
function fontStr(l: L) { return `${l.weight ?? 700} ${l.size}px ${FONT_STACK}`; }
function linesOf(l: L): string[] {
const key = `${l.text}|${l.w}|${fontStr(l)}`;
const hit = wrapCache.get(key);
if (hit) return hit;
mctx.font = fontStr(l);
const out: string[] = [];
for (const para of String(l.text ?? '').split('\n')) {
if (!para) { out.push(''); continue; }
let line = '';
for (const ch of para) {
const test = line + ch;
if (line && mctx.measureText(test).width > l.w && !CLOSE_PUNCT.includes(ch)) {
out.push(line); line = ch;
} else line = test;
}
out.push(line);
}
const res = out.length ? out : [''];
wrapCache.set(key, res);
return res;
}
const maxFontSize = computed(() => Math.max(80, Math.round((natW.value || 1024) * 0.25)));
// ---------- 样式 ----------
function boxStyle(l: L) {
return {
left: l.x + 'px', top: l.y + 'px', width: l.w + 'px',
height: l.type === 'text' ? 'auto' : l.h + 'px',
transform: l.rot ? `rotate(${l.rot}deg)` : undefined,
};
}
function fontStyle(l: L) {
return {
fontFamily: FONT_STACK,
fontSize: l.size + 'px',
fontWeight: String(l.weight ?? 700),
color: l.color,
textAlign: 'center' as const,
lineHeight: l.size * (l.lineHeight ?? 1.25) + 'px',
textShadow: l.glow ? `0 0 ${l.glowBlur ?? 14}px ${l.glowColor ?? '#000000'}` : 'none',
};
}
// ---------- 选中 / 拖动移动 ----------
let drag: { l: L; sx: number; sy: number; lx: number; ly: number } | null = null;
function onDown(e: PointerEvent, l: L) {
selId.value = l.id;
drag = { l, sx: e.clientX, sy: e.clientY, lx: l.x, ly: l.y };
window.addEventListener('pointermove', onMove);
window.addEventListener('pointerup', onUp);
e.preventDefault();
}
function onMove(e: PointerEvent) {
if (!drag) return;
const s = scale.value || 1;
const l = drag.l;
const nx = drag.lx + (e.clientX - drag.sx) / s;
const ny = drag.ly + (e.clientY - drag.sy) / s;
const estH = l.type === 'text' ? linesOf(l).length * l.size * (l.lineHeight ?? 1.25) : l.h;
l.x = Math.min(Math.max(nx, 0), Math.max(natW.value - l.w, 0));
l.y = Math.min(Math.max(ny, 0), Math.max(natH.value - estH, 0));
}
function onUp() {
drag = null;
window.removeEventListener('pointermove', onMove);
window.removeEventListener('pointerup', onUp);
}
// ---------- 拖右下角手柄改大小(位移旋转到图层局部轴,旋转后拖拽方向依然正确) ----------
let rz: { l: L; sx: number; sy: number; w0: number; h0: number; size0: number; rot: number } | null = null;
function onRzDown(e: PointerEvent, l: L) {
selId.value = l.id;
rz = { l, sx: e.clientX, sy: e.clientY, w0: l.w, h0: l.h ?? 0, size0: l.size ?? 48, rot: l.rot ?? 0 };
window.addEventListener('pointermove', onRzMove);
window.addEventListener('pointerup', onRzUp);
e.preventDefault();
e.stopPropagation();
}
function onRzMove(e: PointerEvent) {
if (!rz) return;
const s = scale.value || 1;
const dx = (e.clientX - rz.sx) / s;
const dy = (e.clientY - rz.sy) / s;
const rad = (-rz.rot * Math.PI) / 180;
const ldx = dx * Math.cos(rad) - dy * Math.sin(rad);
const ldy = dx * Math.sin(rad) + dy * Math.cos(rad);
const l = rz.l;
if (l.type === 'image') {
// 拖横向/纵向取位移大的轴驱动,等比缩放(以左上角为锚)
const delta = Math.abs(ldx) >= Math.abs(ldy) ? ldx : ldy;
const nw = Math.max(24, rz.w0 + delta);
const ratio = nw / rz.w0;
l.w = nw;
l.h = Math.max(24, rz.h0 * ratio);
} else {
// 文字:水平拖动改字号,换行宽度同步缩放保持排版比例
const ns = Math.min(Math.max(rz.size0 + ldx, 8), maxFontSize.value);
const ratio = ns / Math.max(1, rz.size0);
l.size = Math.round(ns);
l.w = Math.max(40, Math.round(rz.w0 * ratio));
}
}
function onRzUp() {
rz = null;
window.removeEventListener('pointermove', onRzMove);
window.removeEventListener('pointerup', onRzUp);
}
// ---------- 图层增删 ----------
function addText() {
const w = Math.round(natW.value * 0.8);
const l = {
id: 'l' + ++uid, type: 'text', text: '双击右侧修改文字',
x: Math.round((natW.value - w) / 2), y: Math.round(natH.value * 0.42), w,
size: Math.round(natW.value * 0.07) || 64, color: '#ffffff', weight: 700, lineHeight: 1.25,
glow: true, glowColor: '#000000', glowBlur: 14, rot: 0,
};
layers.value.push(l);
selId.value = l.id;
}
function pickImage() { fileMode = 'add'; fileEl.value?.click(); }
function replaceImage() { fileMode = 'replace'; fileEl.value?.click(); }
function onFile(e: Event) {
const f = (e.target as HTMLInputElement).files?.[0];
const input = e.target as HTMLInputElement;
input.value = '';
if (!f) return;
const url = URL.createObjectURL(f);
const probe = new Image();
probe.onload = () => {
if (fileMode === 'replace') {
const l = sel.value;
if (l && l.type === 'image') l.src = url;
return;
}
const w = Math.round(natW.value * 0.4) || 400;
const h = Math.round((w * probe.naturalHeight) / Math.max(1, probe.naturalWidth));
const l = {
id: 'l' + ++uid, type: 'image', src: url,
x: Math.round((natW.value - w) / 2), y: Math.round((natH.value - h) / 2),
w, h, rot: 0,
};
layers.value.push(l);
selId.value = l.id;
};
probe.src = url;
}
function delSel() {
const i = layers.value.findIndex((l) => l.id === selId.value);
if (i >= 0) layers.value.splice(i, 1);
selId.value = '';
}
function moveLayer(dz: number) {
const i = layers.value.findIndex((l) => l.id === selId.value);
const j = i + dz;
if (i < 0 || j < 0 || j >= layers.value.length) return;
const [l] = layers.value.splice(i, 1);
layers.value.splice(j, 0, l);
}
const selName = computed(() => {
const l = sel.value;
if (!l) return '';
return l.type === 'text' ? String(l.text || '文字').slice(0, 12) : '图片';
});
// ---------- 导出原分辨率 PNG:下载 + 落盘历史(失败不阻断下载) ----------
function loadImg(src: string): Promise<HTMLImageElement | null> {
return new Promise((res) => {
const i = new Image();
i.onload = () => res(i);
i.onerror = () => res(null);
i.src = src;
});
}
function rotAround(ctx: CanvasRenderingContext2D, cx: number, cy: number, deg: number) {
ctx.translate(cx, cy);
ctx.rotate((deg * Math.PI) / 180);
ctx.translate(-cx, -cy);
}
async function drawLayer(ctx: CanvasRenderingContext2D, l: L) {
if (l.type === 'image') {
const img = l.src ? await loadImg(l.src) : null;
if (!img || !img.naturalWidth) return;
ctx.save();
if (l.rot) rotAround(ctx, l.x + l.w / 2, l.y + l.h / 2, l.rot);
ctx.drawImage(img, l.x, l.y, l.w, l.h);
ctx.restore();
return;
}
// 文字
ctx.font = fontStr(l);
ctx.fillStyle = l.color;
const lh = l.size * (l.lineHeight ?? 1.25);
const m = ctx.measureText('字');
const asc = (m as any).fontBoundingBoxAscent ?? l.size * 0.8;
const desc = (m as any).fontBoundingBoxDescent ?? l.size * 0.2;
const lines = linesOf(l);
ctx.save();
if (l.rot) rotAround(ctx, l.x + l.w / 2, l.y + (lines.length * lh) / 2, l.rot);
ctx.textAlign = 'center';
const tx = l.x + l.w / 2;
for (let i = 0; i < lines.length; i++) {
const y = l.y + i * lh + (lh - (asc + desc)) / 2 + asc;
if (l.glow) {
ctx.shadowColor = l.glowColor ?? '#000000';
ctx.shadowBlur = l.glowBlur ?? 14;
ctx.shadowOffsetX = 0;
ctx.shadowOffsetY = 0;
} else {
ctx.shadowColor = 'transparent';
ctx.shadowBlur = 0;
}
ctx.fillText(lines[i], tx, y);
}
ctx.restore();
}
async function exportPng() {
if (!natW.value || !bgImg) return;
exporting.value = true;
edError.value = '';
try {
const c = document.createElement('canvas');
c.width = natW.value;
c.height = natH.value;
const ctx = c.getContext('2d')!;
ctx.drawImage(bgImg, 0, 0, natW.value, natH.value);
for (const l of layers.value) await drawLayer(ctx, l);
const blob: Blob | null = await new Promise((res) => c.toBlob(res, 'image/png'));
if (!blob) throw new Error('画布导出失败');
const a = document.createElement('a');
a.href = URL.createObjectURL(blob);
a.download = 'AI生图-编辑.png';
a.click();
setTimeout(() => URL.revokeObjectURL(a.href), 8000);
// 同步保存到图片历史(kind=gen → 出现在本工具右栏),失败不阻断下载
try {
const b64 = await new Promise<string>((res, rej) => {
const fr = new FileReader();
fr.onload = () => res(String(fr.result || ''));
fr.onerror = () => rej(new Error('读取失败'));
fr.readAsDataURL(blob);
});
const res = await fetch('/relay/ai/img-save', {
method: 'POST',
headers: { 'Content-Type': 'application/json', ...licenseHeaders('ai-gen'), ...authHdr() },
body: JSON.stringify({
machine: getMachineId(), b64, tool: 'ai-gen', kind: 'gen',
model: 'AI生图', prompt: String(props.prompt || '').slice(0, 200) || '图片编辑导出',
}),
});
const j = await res.json().catch(() => ({}) as any);
if (res.ok && j.code === 200) emit('saved', j.data?.img_url || '');
} catch { /* 保存失败不影响本地下载 */ }
} catch (err: any) {
const msg = String(err?.message || err);
edError.value = msg.includes('SecurityError') || msg.includes('tainted')
? '该图片来自外链,浏览器禁止导出(跨域)。请先下载图片,再用「+图片」上传后编辑'
: '导出失败:' + msg;
} finally {
exporting.value = false;
}
}
function onKey(e: KeyboardEvent) {
if (e.key === 'Escape') emit('close');
const t = e.target as HTMLElement | null;
const typing = !!t && (t.tagName === 'INPUT' || t.tagName === 'TEXTAREA');
if (!typing && (e.key === 'Delete' || e.key === 'Backspace') && selId.value) {
e.preventDefault();
delSel();
}
}
let ro: ResizeObserver | null = null;
onMounted(() => {
loadBg();
window.addEventListener('keydown', onKey);
window.addEventListener('resize', fit);
ro = new ResizeObserver(fit);
if (stageEl.value) ro.observe(stageEl.value);
});
onBeforeUnmount(() => {
ro?.disconnect();
window.removeEventListener('keydown', onKey);
window.removeEventListener('resize', fit);
onUp();
onRzUp();
layers.value.forEach((l) => { if (l.type === 'image' && l.src?.startsWith('blob:')) URL.revokeObjectURL(l.src); });
});
</script>
<template>
<div class="ed-root">
<div class="ed-top">
<span class="ed-title">✏️ 编辑图片</span>
<span class="ed-hint">拖动图层移动 · 拖右下角圆点改大小 · Delete 删除 · Esc 关闭</span>
<div class="ed-acts">
<button class="ed-btn" @click="addText">+ 文字</button>
<button class="ed-btn" @click="pickImage">+ 图片</button>
<button class="ed-btn primary" :disabled="exporting" @click="exportPng">
{{ exporting ? '导出中…' : '⬇ 导出 PNG' }}
</button>
<button class="ed-btn ghost" @click="emit('close')">✕ 关闭</button>
</div>
</div>
<div v-if="edError" class="ed-error">⚠️ {{ edError }}</div>
<div class="ed-main">
<section ref="stageEl" class="ed-stage" @click.self="selId = ''">
<div
v-if="natW"
class="ed-frame"
:style="{ width: natW * scale + 'px', height: natH * scale + 'px' }"
>
<div
class="ed-canvas"
:style="{ width: natW + 'px', height: natH + 'px', transform: `scale(${scale})` }"
@click.self="selId = ''"
>
<img class="ed-bg" :src="src" alt="" draggable="false">
<div
v-for="l in layers"
:key="l.id"
class="ed-layer"
:class="{ sel: selId === l.id }"
:style="boxStyle(l)"
@pointerdown.stop="onDown($event, l)"
>
<div v-if="l.type === 'text'" :style="fontStyle(l)">
<div v-for="(ln, i) in linesOf(l)" :key="i">{{ ln || '\u00a0' }}</div>
</div>
<img v-else-if="l.src" class="ed-img" :src="l.src" alt="" draggable="false">
<i
v-if="selId === l.id"
class="ed-rh"
:style="handleStyle"
@pointerdown.stop="onRzDown($event, l)"
></i>
</div>
</div>
</div>
<div v-else class="ed-empty"><n-spin size="large" /><p>底图加载中…</p></div>
</section>
<aside class="ed-panel">
<div class="ed-sec">
<div class="ed-sec-title">图层(上层在前)</div>
<div v-if="!layers.length" class="ed-tip">点上方「+ 文字」「+ 图片」开始编辑,文字可发光、可旋转,拖右下角圆点改大小</div>
<div
v-for="l in [...layers].reverse()"
:key="l.id"
class="ed-li"
:class="{ on: selId === l.id }"
@click="selId = l.id"
>
<span class="ed-li-ico">{{ l.type === 'text' ? 'T' : '🖼' }}</span>
<span class="ed-li-name">{{ l.type === 'text' ? String(l.text || '文字').slice(0, 10) : '图片' }}</span>
<span class="ed-li-ops">
<button title="上移" @click.stop="selId = l.id; moveLayer(1)">▲</button>
<button title="下移" @click.stop="selId = l.id; moveLayer(-1)">▼</button>
<button title="删除" @click.stop="selId = l.id; delSel()">✕</button>
</span>
</div>
</div>
<template v-if="sel && sel.type === 'text'">
<div class="ed-sec">
<div class="ed-sec-title">文字「{{ selName }}」</div>
<textarea v-model="sel.text" class="ed-textarea" rows="3" placeholder="输入文字内容"></textarea>
<label class="ed-row">
<span>字号</span>
<input v-model.number="sel.size" type="range" min="8" :max="maxFontSize">
<em>{{ sel.size }}</em>
</label>
<label class="ed-row">
<span>颜色</span>
<input v-model="sel.color" type="color" class="ed-color">
<span class="ed-flex"></span>
<span>旋转</span>
<input v-model.number="sel.rot" type="range" min="-180" max="180">
<em>{{ sel.rot ?? 0 }}°</em>
<button class="ed-mini" @click="sel.rot = 0">复位</button>
</label>
<label class="ed-row">
<span>发光</span>
<input v-model="sel.glow" type="checkbox">
<input v-if="sel.glow" v-model="sel.glowColor" type="color" class="ed-color">
<template v-if="sel.glow">
<span>强度</span>
<input v-model.number="sel.glowBlur" type="range" min="2" max="60">
<em>{{ sel.glowBlur ?? 14 }}</em>
</template>
</label>
<div class="ed-tip">拖右下角圆点直接改字号;发光为文字外光晕,颜色强度可调</div>
</div>
</template>
<template v-if="sel && sel.type === 'image'">
<div class="ed-sec">
<div class="ed-sec-title">图片</div>
<label class="ed-row">
<span>旋转</span>
<input v-model.number="sel.rot" type="range" min="-180" max="180">
<em>{{ sel.rot ?? 0 }}°</em>
<button class="ed-mini" @click="sel.rot = 0">复位</button>
</label>
<button class="ed-btn wide" @click="replaceImage">替换图片</button>
<div class="ed-tip">拖右下角圆点等比改大小;拖动图层移动位置</div>
</div>
</template>
<div class="ed-sec">
<div class="ed-sec-title">说明</div>
<div class="ed-tip">导出为底图原始分辨率 PNG,同时保存到右侧历史(按你的账号隔离)。底图本身锁定不可删。</div>
</div>
</aside>
</div>
<input ref="fileEl" type="file" accept="image/*" class="ed-hidden" @change="onFile">
</div>
</template>
<style scoped lang="less">
.ed-root {
position: fixed;
inset: 0;
z-index: 5000;
background: rgba(14, 16, 18, 0.97);
display: flex;
flex-direction: column;
color: #e8e8e8;
}
.ed-top {
display: flex;
align-items: center;
gap: 14px;
padding: 12px 18px;
border-bottom: 1px solid rgba(255, 255, 255, 0.1);
flex-shrink: 0;
flex-wrap: wrap;
}
.ed-title { font-size: 16px; font-weight: 700; }
.ed-hint { font-size: 12px; opacity: 0.55; flex: 1; min-width: 160px; }
.ed-acts { display: flex; gap: 8px; flex-wrap: wrap; }
.ed-btn {
padding: 8px 16px;
border-radius: 8px;
border: 1px solid rgba(255, 255, 255, 0.18);
background: rgba(255, 255, 255, 0.08);
color: #e8e8e8;
font-size: 14px;
font-weight: 600;
cursor: pointer;
&:hover { background: rgba(255, 255, 255, 0.16); }
&:disabled { opacity: 0.55; cursor: wait; }
&.primary { background: #0ea5a0; border-color: #0ea5a0; color: #fff; }
&.primary:hover { background: #0c8f8a; }
&.ghost { background: transparent; }
&.wide { width: 100%; margin-top: 6px; }
}
.ed-error {
padding: 8px 18px;
font-size: 13px;
color: #ffb4a2;
background: rgba(255, 120, 100, 0.1);
flex-shrink: 0;
}
.ed-main { flex: 1; min-height: 0; display: flex; }
.ed-stage {
flex: 1;
min-width: 0;
display: flex;
align-items: center;
justify-content: center;
overflow: hidden;
padding: 12px;
}
.ed-empty { text-align: center; opacity: 0.6; font-size: 13.5px; p { margin-top: 12px; } }
.ed-frame {
position: relative;
flex-shrink: 0;
box-shadow: 0 8px 32px rgba(0, 0, 0, 0.5);
border-radius: 4px;
overflow: hidden;
}
.ed-canvas { position: absolute; left: 0; top: 0; transform-origin: 0 0; overflow: hidden; }
.ed-bg {
position: absolute;
inset: 0;
width: 100%;
height: 100%;
object-fit: fill;
pointer-events: none;
user-select: none;
-webkit-user-drag: none;
}
.ed-layer {
position: absolute;
box-sizing: border-box;
user-select: none;
-webkit-user-select: none;
touch-action: none;
cursor: move;
}
.ed-layer.sel { outline: 3px dashed #38bdf8; outline-offset: 2px; }
.ed-img { width: 100%; height: 100%; object-fit: fill; display: block; pointer-events: none; }
.ed-rh {
position: absolute;
box-sizing: border-box;
background: #38bdf8;
border: 2px solid #fff;
border-radius: 50%;
cursor: nwse-resize;
z-index: 5;
touch-action: none;
}
.ed-panel {
width: 320px;
flex-shrink: 0;
min-height: 0;
overflow-y: auto;
border-left: 1px solid rgba(255, 255, 255, 0.1);
padding: 14px;
display: flex;
flex-direction: column;
gap: 14px;
}
.ed-sec { display: flex; flex-direction: column; gap: 8px; }
.ed-sec-title { font-size: 13px; font-weight: 700; opacity: 0.85; }
.ed-tip { font-size: 12.5px; opacity: 0.6; line-height: 1.7; }
.ed-li {
display: flex;
align-items: center;
gap: 6px;
padding: 6px 8px;
border-radius: 6px;
border: 1px solid transparent;
cursor: pointer;
font-size: 13px;
background: rgba(255, 255, 255, 0.06);
&:hover { background: rgba(255, 255, 255, 0.1); }
&.on { border-color: #38bdf8; background: rgba(56, 189, 248, 0.14); }
}
.ed-li-ico { width: 18px; text-align: center; opacity: 0.8; }
.ed-li-name { flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.ed-li-ops { display: inline-flex; gap: 2px; }
.ed-li-ops button {
border: none;
background: transparent;
cursor: pointer;
color: inherit;
padding: 2px 5px;
font-size: 12px;
border-radius: 4px;
&:hover { background: rgba(255, 255, 255, 0.16); }
}
.ed-textarea {
width: 100%;
box-sizing: border-box;
resize: vertical;
min-height: 64px;
background: rgba(255, 255, 255, 0.07);
border: 1px solid rgba(255, 255, 255, 0.16);
border-radius: 8px;
color: inherit;
padding: 8px 10px;
font-size: 13.5px;
font-family: inherit;
&:focus { outline: none; border-color: #38bdf8; }
}
.ed-row {
display: flex;
align-items: center;
gap: 8px;
font-size: 13px;
opacity: 0.92;
input[type='range'] { flex: 1; min-width: 60px; accent-color: #38bdf8; }
input[type='checkbox'] { accent-color: #38bdf8; width: 16px; height: 16px; }
em { font-style: normal; min-width: 40px; text-align: right; opacity: 0.75; font-size: 12.5px; }
}
.ed-flex { flex: 1; }
.ed-color {
width: 42px;
height: 26px;
padding: 0;
border: 1px solid rgba(255, 255, 255, 0.2);
border-radius: 6px;
background: transparent;
cursor: pointer;
}
.ed-mini {
padding: 3px 8px;
border-radius: 6px;
border: 1px solid rgba(255, 255, 255, 0.2);
background: rgba(255, 255, 255, 0.08);
color: inherit;
font-size: 12px;
cursor: pointer;
&:hover { background: rgba(255, 255, 255, 0.16); }
}
.ed-hidden { display: none; }
@media (max-width: 900px) {
.ed-main { flex-direction: column; overflow-y: auto; }
.ed-stage { flex: none; height: 48vh; }
.ed-panel { width: 100%; border-left: none; border-top: 1px solid rgba(255, 255, 255, 0.1); overflow: visible; }
.ed-hint { display: none; }
}
</style>
+23 -2
View File
@@ -1,6 +1,7 @@
<script setup lang="ts">
import { useUserAuth } from '@/composable/user-auth';
import { degrees, PDFDocument, rgb } from '@cantoo/pdf-lib';
import fontkit from '@cantoo/fontkit';
import { getDocument, GlobalWorkerOptions } from 'pdfjs-dist';
import pdfWorkerUrl from 'pdfjs-dist/build/pdf.worker.min.js?url';
import { zipSync } from 'fflate';
@@ -387,16 +388,36 @@ async function doDecrypt() {
statusMsg.value = '解密完成(输出为高清图片版,无密码),点击下载';
}
// 中文字体(Droid Sans Fallback,覆盖 CJK):仅含非西文水印时按需加载,模块级缓存字节
let cjkFontBytes: ArrayBuffer | null = null;
async function getCjkFontBytes(): Promise<ArrayBuffer> {
if (!cjkFontBytes) {
const res = await fetch(`${import.meta.env.BASE_URL}fonts/DroidSansFallback.ttf`);
if (!res.ok) throw new Error('中文字体加载失败');
cjkFontBytes = await res.arrayBuffer();
}
return cjkFontBytes;
}
async function doWatermark() {
if (!wmText.value.trim()) {
throw new Error('请输入水印文字');
}
const src = await loadDoc(files.value[0]);
const pages = src.getPages();
const font = await src.embedFont('Helvetica');
const text = wmText.value.slice(0, 30);
// Helvetica(WinAnsi) 无法编码中文,会被替换成 ?;含非西文字符时嵌入中文字体子集
const needCjk = [...text].some(ch => ch.charCodeAt(0) > 0xff);
let font;
if (needCjk) {
src.registerFontkit(fontkit);
font = await src.embedFont(await getCjkFontBytes(), { subset: true });
}
else {
font = await src.embedFont('Helvetica');
}
for (const page of pages) {
const { width, height } = page.getSize();
const text = wmText.value.slice(0, 30);
const tw = font.widthOfTextAtSize(text, wmSize.value);
page.drawText(text, {
x: (width - tw) / 2,