Compare commits

...
Author SHA1 Message Date
jinghui 3c126277eb feat: 历史记录100条上限 + 后台文件管理升级收口
- 所有功能历史最多显示100条:relay img-history vis[:150]→[:100]、mcp-usage 流水 LIMIT 300→100
- 前端三处兜底:loadImgHist/ai-gen/poster slice(0,100)
- 上轮遗留收口:后台文件管理全量视图/50条分页/100x100缩略图/下载/三类删除、图片历史铁规则 ImgHist 共享层接入7工具
- Home NEW_FEATURES 与 README 同步
2026-11-14 18:58:48 +08:00
jinghui 225aa5ed68 feat(home): 海报NEW_FEATURES条目更新为42套模板/图层旋转/整页自适应 2026-11-13 22:54:38 +08:00
jinghui 846b161aa3 docs(readme): AI海报章节更新为42套模板10分类(含校园10款)、图层旋转与整页自适应无滚动条说明 2026-11-13 22:53:11 +08:00
jinghui 931c0b5673 feat(poster): 整页无滚动条自适应+单区域滚动+文字可旋转+模板25→42(新增校园10款)
- 布局: pmRoot按最内层n-layout-scroll-container实测高度定根(fit联动measure, resize/focus/visibilitychange复测, 余量18px), 根overflow:hidden; 桌面三列各自overflow-y内部滚动, 窄屏堆叠后仅.pm-main单区域滚动; fit()改宽高双向取min, 画布完整落入舞台不出滚动条
- 旋转: 图层接口新增rot(文字/图片/形状), 预览CSS transform绕图层中心, 导出canvas rotAround同中心旋转(预览/导出同轴不跑位), 编辑面板加旋转滑杆(-180~180)+复位; 实测模板内置-4°与滑杆-90°/-25°矩阵值精确, PNG导出98KB正常
- 模板: 25→42, 新增'校园'分类10款(教师节/开学第一课/家长会/秋季运动会/毕业季/社团招新/优秀学生表彰/快乐六一/考试加油/读书月)+促销2/节日1/活动1/美食3
- 验证: 780x437/1100x800/1600x900三档实测page_scrollable=false, 滚动只发生在指定区域; 桌面三列对齐, 校园10模板缩略图渲染正常
2026-11-13 22:49:33 +08:00
jinghui 6463aa81d8 fix(poster): /poster-maker 加入 WIDE_TOOLS——三栏布局(模板库292+画布+面板316)在600px限宽下必堆叠, 宽屏1600实测三列无溢出无页面滚动 2026-11-13 19:49:46 +08:00
jinghui 67c320a2de feat: 新增AI换脸与AI海报生成两个授权应用——换脸(insightface buffalo_l+inswapper_128本机CPU推理, POST /ai/face-swap, consent必填, 多脸取最大); 海报(25套模板9分类, 改文字/换图片/AI生成配图与背景/图层增删排序/背景预设, 按宽高比匹配上游尺寸档位, 导出1080x1440 PNG); license.ts与relay PROTECTED_TOOLS双端注册使pricing/buy自动+2; relay副本同步(Dockerfile装insightface+COPY face-models不入库) 2026-11-13 19:35:03 +08:00
jinghui afe73922cc pricing/buy 授权功能清单改为从 PROTECTED_TOOLS 自动派生: pricing 页原硬编码9条(实际授权13个,缺文字生成图片/AI图片实验室/文案工具箱/AI生图), 改为 MARKETING文案表+PROTECTED_TOOLS动态渲染, 新授权应用加入即自动上架, 无文案时用工具名称/描述兜底; 文案与套餐数量(9个/13个)全部改 {{paidFeatures.length}} 动态; Buy 页4处13个高级功能写死改 paidCount=Object.keys(PROTECTED_TOOLS).length
Release new versions / github-release (push) Canceled after 0s
Release new versions / docker-release (push) Canceled after 0s
2026-11-13 17:02:38 +08:00
jinghui d4ecefe313 fix: 侧栏收起全部/展开全部同步作用于我的收藏与授权应用 2026-11-13 16:44:38 +08:00
27 changed files with 2833 additions and 160 deletions

No files matched your search

+3
View File
@@ -28,6 +28,9 @@ coverage
*.sw?
.env
# 本地 AI 换脸模型(宿主预置, 不入库: buffalo_l ~289MB + inswapper_128 ~554MB)
docker/it-tools-relay/face-models/
/test-results/
/playwright-report/
/playwright/.cache/
+33
View File
@@ -75,6 +75,39 @@
- **界面文案**(按所选模型联动):未授权 `免费10次·剩N · CF池剩X/173张` / `… · Pollinations按Key余额`;已授权 `已授权 · CF池剩X/173张`;CF 池尽红色 `CF免费池已用完 · 08:00重置`。
- 额度查询端点 `POST /relay/ai/quota`(带 `model` 返回 `authorized/limit/used/remaining` + `upstream/upstream_daily/upstream_used/upstream_remaining/upstream_note/cf_daily`;`remaining=-1` 表示机器维度不限,仍受共享池约束)。次数用完点「或使用自己的提供商 / API KEY」用自己的 KEY 继续生成,403 提示文案同步引导。
### AI 换脸(2026.11 新增)
- 上传源人脸照片 + 目标照片,本机 CPU 一键换脸(insightface buffalo_l 人脸检测,多脸自动取最大 + inswapper_128 换脸模型,模型 855MB 预置于镜像内)。
- 接口 `POST /relay/ai/face-swap`(multipart:`source`/`target`/`consent`),需勾选授权承诺,结果走站内 `/relay/ai/img` 图链路,支持下载。
- 授权应用:未授权用户每天可免费试用 3 次,卡密激活后不限次。
### AI 海报生成(2026.11 新增)
- 42 套热门海报模板、10 大分类(促销/节日/活动/美食/教育/校园/健身/招聘/生日/封面),模板画布 1080×1440;「校园」分类含教师节/开学第一课/家长会/秋季运动会/毕业季/社团招新/优秀学生表彰/快乐六一/考试加油/读书月等 10 款学校师生主题模板。
- 选中模板后可:**修改文字**(内容/字号/颜色/粗细/对齐/行高/斜体,预览与导出换行一致)、**旋转任意图层**(文字/图片/形状均支持,-180°~180° 滑杆 + 一键复位,预览与导出同一旋转中心)、**替换图片**(本地上传 或 AI 生成,圆角可调)、拖动移动图层、图层排序/删除、添加文字与图片框、一键切换背景渐变、AI 生成整屏背景。
- 编辑页整页自适应浏览器高度、不出现整体滚动条:内容超出时只在模板列表 / 画布 / 编辑面板各自区域内滚动(窄屏堆叠后统一为一个区域),画布始终完整可见。
- AI 配图复用 `/relay/ai/gen-image` 与每日免费生图额度,按图框宽高比自动匹配上游尺寸档位。
- 完成后一键导出 1080×1440 PNG(旋转图层同步导出)。授权应用,支持每日免费试用。
### 历史记录 100 条上限(2026.11 新增)
所有功能里的历史记录最多显示 100 条(按时间倒序取最新 100 条):
- 服务端 `GET /relay/ai/img-history` 与 `GET /admin/mcp-usage` 调用流水统一截断前 100 条(只影响展示条数,后台总记录数/总调用量统计不受影响);
- 前端图片历史共享层(`loadImgHist`)、AI 生图与海报生成的自建历史均带 100 条本地兜底;
- 已有上限低于 100 的(生成记录 50 条、网速测速 20 条等)保持原值。
### 后台文件管理(2026.11 新增)
管理后台「文件管理」页全面升级:
- **默认全量视图**:进入即显示**所有用户**上传的文件 + AI 生成图片(换脸/生图/海报/编辑)+ MCP 产出文件的聚合列表,无需先选用户;下拉仍可按「仅 AI 生成 / 仅某用户」过滤。
- **50 条/页自动分页**:超过 50 条自动分页,页头页尾都有翻页控件,**显示总记录数与总大小**(如「共 81 条记录 · 合计 31.5 MB」)。
- **图片 100×100 缩略图**:图片类型文件在「预览」列显示 100×100 缩略图,点击看原图;**其他文件显示文件类型徽标**(PDF/PNG/MP4…)。
- **单独下载**:每一行都有「下载」链接(`Content-Disposition: attachment` 带原文件名),与「删除」并列;删除按来源分流(用户文件走 files 表、AI 生成图同步删 index、MCP 文件防路径穿越)。
- **安全**:缩略图与下载走统一 `/relay/admin/file?path=…&token=…` 路由(`<img>`/`<a>` 无法携带 header,鉴权走 query token,与 header 双通道校验);路径白名单限定 `users/`、`gen_images/`、`mcp_files/` 三棵子树 + realpath 校验,防目录穿越;无 token 请求 403。
- 服务端按 mtime 全局排序后切片分页,每项附带 `source`(user/gen/mcp)、`file_type`、`is_image`、相对 `path` 字段。
## 优势
- **一次激活,全站通用**:输入一次卡密,全部授权功能解锁,无需逐个购买
+3
View File
@@ -91,6 +91,7 @@ declare module '@vue/runtime-core' {
EmojiPicker: typeof import('./src/tools/emoji-picker/emoji-picker.vue')['default']
Encryption: typeof import('./src/tools/encryption/encryption.vue')['default']
EtaCalculator: typeof import('./src/tools/eta-calculator/eta-calculator.vue')['default']
FaceSwap: typeof import('./src/tools/face-swap/face-swap.vue')['default']
FavoriteButton: typeof import('./src/components/FavoriteButton.vue')['default']
FeedbackModal: typeof import('./src/components/FeedbackModal.vue')['default']
FormatTransformer: typeof import('./src/components/FormatTransformer.vue')['default']
@@ -129,6 +130,7 @@ declare module '@vue/runtime-core' {
IconMdiVideo: typeof import('~icons/mdi/video')['default']
ImageOcr: typeof import('./src/tools/image-ocr/image-ocr.vue')['default']
ImageTools: typeof import('./src/tools/image-tools/image-tools.vue')['default']
ImgHist: typeof import('./src/tools/img-hist/ImgHist.vue')['default']
InputCopyable: typeof import('./src/components/InputCopyable.vue')['default']
IntegerBaseConverter: typeof import('./src/tools/integer-base-converter/integer-base-converter.vue')['default']
Ipv4AddressConverter: typeof import('./src/tools/ipv4-address-converter/ipv4-address-converter.vue')['default']
@@ -217,6 +219,7 @@ declare module '@vue/runtime-core' {
PercentageCalculator: typeof import('./src/tools/percentage-calculator/percentage-calculator.vue')['default']
PhoneParserAndFormatter: typeof import('./src/tools/phone-parser-and-formatter/phone-parser-and-formatter.vue')['default']
PinyinConverter: typeof import('./src/tools/pinyin-converter/pinyin-converter.vue')['default']
Poster: typeof import('./src/tools/poster/poster.vue')['default']
'Pricing.page': typeof import('./src/pages/Pricing.page.vue')['default']
PsEditor: typeof import('./src/tools/image-tools/PsEditor.vue')['default']
QrCodeGenerator: typeof import('./src/tools/qr-code-generator/qr-code-generator.vue')['default']
+11
View File
@@ -0,0 +1,11 @@
.env
data/
__pycache__/
*.pyc
hf-cache/
piper-models/
ai-models/
waifu2x/
face-models/
*.log
.venv-hf/
+3
View File
@@ -7,7 +7,10 @@ RUN apt-get update \
# models are pre-downloaded on the host (build env has no internet)
RUN pip install --no-cache-dir piper-tts faster-whisper
RUN pip install --no-cache-dir -i https://pypi.tuna.tsinghua.edu.cn/simple "rembg[cpu]"
# AI 换脸: insightface(纯Python wheel 免编译) + buffalo_l人脸检测 + inswapper_128换脸模型(宿主已预置)
RUN pip install --no-cache-dir -i https://pypi.tuna.tsinghua.edu.cn/simple insightface
COPY hf-cache /root/.cache/huggingface
COPY face-models /app/face-models
COPY piper-models /app/piper-models
# AI 图片: u2net 抠图模型(预下载) + waifu2x-ncnn-vulkan 无损放大(CPU)
COPY ai-models/u2net.onnx /root/.u2net/u2net.onnx
+2 -1
View File
@@ -76,7 +76,8 @@ def mcp_usage_query(days: int = 7) -> dict:
conn = sqlite3.connect(_CTX["usage_db"])
rows = conn.execute(
"SELECT token_tail, machine, tool, ok, err, dur_ms, at FROM mcp_usage "
"WHERE at>? ORDER BY at DESC LIMIT 300", (since,)).fetchall()
# 铁规则:所有功能历史最多显示 100 条
"WHERE at>? ORDER BY at DESC LIMIT 100", (since,)).fetchall()
by_tool = conn.execute(
"SELECT tool, COUNT(*), SUM(ok) FROM mcp_usage WHERE at>? GROUP BY tool ORDER BY COUNT(*) DESC",
(since,)).fetchall()
+587 -31
View File
@@ -21,6 +21,7 @@ Trial state persisted to /app/data/trials.json (mounted volume).
import cgi
import io
import json
import mimetypes
import os
import re
import shutil
@@ -68,7 +69,7 @@ CF_DAILY_LIMIT = int(os.environ.get("CF_DAILY_LIMIT", "173"))
CF_DAILY_FILE = os.environ.get("CF_DAILY_FILE", "/app/data/daily_gen_cf.json")
DAY_MS = 24 * 60 * 60 * 1000
TZ_OFFSET_MS = 8 * 60 * 60 * 1000 # 北京时间 UTC+8 —— 重置对齐自然日 0 点
PROTECTED_TOOLS = {"translator", "image-ocr", "pdf-ocr", "ai-retouch", "doc-convert", "image-tools", "pdf-tools", "video-tools", "audio-tools", "text-to-image", "ai-image-tools", "copywriting", "screenshot-qa", "video-subtitle", "ai-gen", "ai-text-edit"}
PROTECTED_TOOLS = {"translator", "image-ocr", "pdf-ocr", "ai-retouch", "doc-convert", "image-tools", "pdf-tools", "video-tools", "audio-tools", "text-to-image", "ai-image-tools", "copywriting", "screenshot-qa", "video-subtitle", "ai-gen", "ai-text-edit", "face-swap", "poster-maker"}
MACHINE_RE = re.compile(r"^\d{10,16}$")
# verify() messages that unconditionally block activation
@@ -711,6 +712,116 @@ def check(machine: str, tool: str) -> int:
return 200 if trial_allowed(machine, tool) else 403
# ---- AI 换脸引擎:insightface buffalo_l 人脸检测 + inswapper_128 换脸(本机 CPU 推理) ----
_FACE_LOCK = threading.Lock()
_FACE_APP = None
_FACE_SWAP = None
_FACE_MODELS_DIR = os.environ.get("FACE_MODELS_DIR", "/app/face-models")
_GFPGAN_SESS = None
def _face_engine():
"""懒加载换脸引擎(线程安全;首次调用约 1~2s,之后常驻内存复用)。"""
global _FACE_APP, _FACE_SWAP
if _FACE_APP is None:
from insightface.app import FaceAnalysis
from insightface import model_zoo
app = FaceAnalysis(name="buffalo_l", root=_FACE_MODELS_DIR, providers=["CPUExecutionProvider"])
app.prepare(ctx_id=0, det_size=(640, 640))
swap = model_zoo.get_model(os.path.join(_FACE_MODELS_DIR, "inswapper_128.onnx"),
providers=["CPUExecutionProvider"])
_FACE_APP, _FACE_SWAP = app, swap
return _FACE_APP, _FACE_SWAP
def _largest_face(faces):
"""多张脸时取面积最大的一张(换脸默认作用于最显眼的人脸)。"""
return max(faces, key=lambda f: float((f.bbox[2] - f.bbox[0]) * (f.bbox[3] - f.bbox[1])))
def _gfpgan_session():
global _GFPGAN_SESS
if _GFPGAN_SESS is None:
import onnxruntime as _ort
path = os.path.join(_FACE_MODELS_DIR, "gfpgan_1.4.onnx")
if not os.path.exists(path):
return None
_GFPGAN_SESS = _ort.InferenceSession(path, providers=["CPUExecutionProvider"])
return _GFPGAN_SESS
def _gfpgan_enhance(img):
"""用 GFPGAN 对图中最大人脸做修复增强,返回增强后的整图(失败则原样返回)。"""
try:
import cv2 as _cv2
import numpy as _np
sess = _gfpgan_session()
if sess is None:
return img
app, _ = _face_engine()
faces = app.get(img)
if not faces:
return img
f = _largest_face(faces)
x1, y1, x2, y2 = [int(v) for v in f.bbox]
h, w = img.shape[:2]
# 扩展 bbox
pad = int(0.25 * max(x2 - x1, y2 - y1))
x1 = max(0, x1 - pad); y1 = max(0, y1 - pad)
x2 = min(w, x2 + pad); y2 = min(h, y2 + pad)
crop = img[y1:y2, x1:x2]
if crop.size == 0:
return img
inp = _cv2.resize(crop, (512, 512))
inp = _cv2.cvtColor(inp, _cv2.COLOR_BGR2RGB).astype("float32") / 255.0
inp = (inp - 0.5) / 0.5
inp = _np.transpose(inp, (2, 0, 1))[None, ...].astype("float32")
out = sess.run(None, {sess.get_inputs()[0].name: inp})[0]
out = out[0].transpose(1, 2, 0)
out = (out * 0.5 + 0.5) * 255.0
out = _np.clip(out, 0, 255).astype("uint8")
out = _cv2.cvtColor(out, _cv2.COLOR_RGB2BGR)
out = _cv2.resize(out, (x2 - x1, y2 - y1))
# 羽化混合
mask = _np.zeros((y2 - y1, x2 - x1), dtype="float32")
cx, cy = (x2 - x1) // 2, (y2 - y1) // 2
# 简单中心渐变蒙版
Y, X = _np.ogrid[:y2-y1, :x2-x1]
dist = _np.sqrt((X - cx) ** 2 + (Y - cy) ** 2)
r = min(cx, cy)
mask = _np.clip(1 - dist / max(r, 1), 0, 1)
mask = mask[..., None]
blended = (out.astype("float32") * mask + crop.astype("float32") * (1 - mask)).astype("uint8")
res = img.copy()
res[y1:y2, x1:x2] = blended
return res
except Exception as e:
print(f"[gfpgan] enhance failed: {e}", flush=True)
return img
def _face_swap_run(src_img, dst_img):
"""源人脸 -> 目标照片。返回 (jpg字节|None, 错误信息, 耗时ms)。加锁串行避免并发吃满 CPU。"""
import cv2 as _cv2
t0 = time.time()
with _FACE_LOCK:
app, swap = _face_engine()
src_faces = app.get(src_img)
dst_faces = app.get(dst_img)
if not src_faces:
return None, "源图中未检测到人脸,请换一张清晰的正脸照片", 0
if not dst_faces:
return None, "目标图中未检测到人脸,请换一张含人物的照片", 0
out = swap.get(dst_img, _largest_face(dst_faces), _largest_face(src_faces), paste_back=True)
# GFPGAN 修复增强(可选)
if os.environ.get("FACE_SWAP_GFPGAN", "1") != "0":
out = _gfpgan_enhance(out)
ok, buf = _cv2.imencode(".jpg", out, [int(_cv2.IMWRITE_JPEG_QUALITY), 92])
if not ok:
return None, "结果编码失败", 0
return buf.tobytes(), None, int((time.time() - t0) * 1000)
def _account_license_ok(machine: str) -> bool:
"""True when this device logged into an authorized account.
@@ -1166,6 +1277,21 @@ def _admin_auth(handler) -> bool:
tok = handler.headers.get("X-Admin-Token", "")
if ADMIN_TOKEN and tok and tok == ADMIN_TOKEN:
return True
# query token fallback: <img src> / <a download> 无法携带 header,缩略图与下载走 ?token=
if not tok:
try:
tok = (parse.parse_qs(parse.urlparse(handler.path).query).get("token") or [""])[0]
except Exception:
tok = ""
if ADMIN_TOKEN and tok and tok == ADMIN_TOKEN:
return True
if tok:
acc = _parse_token(tok)
if acc:
role, disabled = _user_attr(acc)
if role == "admin" and not disabled:
return True
tok = ""
# channel 2: logged-in admin account
auth = handler.headers.get("Authorization", "")
if auth.lower().startswith("bearer "):
@@ -1233,26 +1359,157 @@ def admin_api(method: str, sub: str, payload: dict, handler):
"totals": {"users": len(out_users), "files": total_files, "size": total_size},
}}
# ---- 统一文件下载/缩略图:path 相对 DATA_DIR(users/、gen_images/、mcp_files/ 白名单)----
# 鉴权走 _admin_auth(支持 header 或 ?token=,因 <img src>/<a download> 无法带 header)
if method == "GET" and sub == "/file":
qs = parse.parse_qs(parse.urlparse(handler.path).query)
rel = (qs.get("path") or [""])[0]
as_dl = (qs.get("dl") or [""])[0] == "1"
disp_q = (qs.get("name") or [""])[0]
if not rel or rel.startswith("/") or ".." in rel.split("/"):
return 400, {"code": 400, "message": "参数错误"}
if rel.split("/")[0] not in ("users", "gen_images", "mcp_files"):
return 404, {"code": 404, "message": "文件不存在"}
root = os.path.realpath(DATA_DIR)
fp = os.path.realpath(os.path.join(root, rel))
if not fp.startswith(root + os.sep) or not os.path.isfile(fp):
return 404, {"code": 404, "message": "文件不存在"}
try:
with open(fp, "rb") as fh:
data = fh.read()
except OSError:
return 404, {"code": 404, "message": "文件不存在"}
disp = os.path.basename(disp_q.replace(chr(92), "/")) if disp_q else os.path.basename(fp)
disp = re.sub(r'[\r\n"]+', '', disp)[:180] or os.path.basename(fp)
ctype = mimetypes.guess_type(fp)[0] or "application/octet-stream"
handler.send_response(200)
handler.send_header("Content-Type", ctype)
handler.send_header("Content-Length", str(len(data)))
if as_dl:
handler.send_header("Content-Disposition", "attachment; filename*=UTF-8''" + parse.quote(disp))
handler.end_headers()
handler.wfile.write(data)
return None, None
# ---- 文件管理:默认全量聚合(所有用户文件 + AI 生成图片 + MCP 产出),50/页分页 ----
if method == "GET" and sub.startswith("/files"):
qs = parse.parse_qs(parse.urlparse(handler.path).query)
username = (qs.get("username") or [""])[0]
if not username or "/" in username or ".." in username:
scope = (qs.get("scope") or [""])[0]
try:
page = max(1, int((qs.get("page") or ["1"])[0]))
except Exception:
page = 1
try:
page_size = min(200, max(1, int((qs.get("page_size") or ["50"])[0])))
except Exception:
page_size = 50
if username and ("/" in username or ".." in username):
return 400, {"code": 400, "message": "参数错误"}
fdir = os.path.join(_user_dir(username), "files")
files = []
total = 0
for root, _d, fs in os.walk(fdir):
kind = os.path.basename(root) if root != fdir else ""
for f in fs:
fp = os.path.join(root, f)
IMG_EXT = {"png", "jpg", "jpeg", "gif", "webp", "bmp", "svg", "avif", "ico"}
items = []
want_user = scope not in ("gen", "mcp")
want_gen = scope in ("", "gen")
want_mcp = scope in ("", "mcp")
if username: # 指定用户时只看该用户文件(兼容旧下拉语义)
want_user, want_gen, want_mcp = True, False, False
# 1) 用户上传文件(磁盘是 uuid 名 -> DB 取真实文件名/mime)
if want_user:
db_meta = {}
try:
conn = _db()
for fid, un, nm, mi in conn.execute("SELECT id, username, name, mime FROM files").fetchall():
db_meta[(un, fid)] = (nm or fid, mi or "")
conn.close()
except Exception:
db_meta = {}
uroots = [username] if username else (
sorted(os.listdir(USERS_ROOT)) if os.path.isdir(USERS_ROOT) else [])
for u in uroots:
fdir = os.path.join(USERS_ROOT, u, "files")
if not os.path.isdir(fdir):
continue
for root, _d, fs in os.walk(fdir):
kind = os.path.basename(root) if root != fdir else ""
for f in fs:
fp = os.path.join(root, f)
try:
st = os.stat(fp)
except OSError:
continue
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,
"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(),
"path": os.path.relpath(fp, DATA_DIR),
})
# 2) AI 生成图片(换脸/生图/海报/编辑,跨所有机器聚合 gen_images/*/)
if want_gen:
groot = os.path.join(DATA_DIR, "gen_images")
for m in (sorted(os.listdir(groot)) if os.path.isdir(groot) else []):
gdir = os.path.join(groot, m)
if not os.path.isdir(gdir):
continue
idx = {}
try:
idxp = os.path.join(gdir, "index.json")
for it in (json.load(open(idxp, encoding="utf-8")) if os.path.exists(idxp) else []):
if isinstance(it, dict):
idx[str(it.get("id"))] = it
except Exception:
idx = {}
for f in os.listdir(gdir):
if f == "index.json":
continue
fp = os.path.join(gdir, f)
try:
st = os.stat(fp)
except OSError:
continue
iid = os.path.splitext(f)[0]
meta = idx.get(iid, {})
ext = os.path.splitext(f)[1].lower().lstrip(".")
items.append({
"id": iid, "name": f, "kind": str(meta.get("kind") or "gen"),
"size": st.st_size, "mtime": int(st.st_mtime), "machine": m,
"prompt": str(meta.get("prompt") or ""), "url": f"/relay/ai/img/{m}/{iid}",
"source": "gen", "username": "", "mime": f"image/{ext}",
"is_image": ext in IMG_EXT, "file_type": (ext or "img").upper(),
"path": os.path.relpath(fp, DATA_DIR),
})
# 3) MCP 产出文件(data/mcp_files/)
if want_mcp:
mroot = os.path.join(DATA_DIR, "mcp_files")
for f in (sorted(os.listdir(mroot)) if os.path.isdir(mroot) else []):
fp = os.path.join(mroot, f)
if not os.path.isfile(fp):
continue
try:
st = os.stat(fp)
except OSError:
continue
total += st.st_size
files.append({"id": f, "name": f, "kind": kind, "size": st.st_size, "mtime": int(st.st_mtime)})
files.sort(key=lambda x: -x["mtime"])
return 200, {"code": 200, "message": "ok", "data": {"files": files, "total_size": total, "count": len(files)}}
ext = os.path.splitext(f)[1].lower().lstrip(".")
items.append({
"id": f, "name": f, "kind": "mcp", "size": st.st_size,
"mtime": int(st.st_mtime), "source": "mcp", "username": "",
"mime": "", "is_image": ext in IMG_EXT,
"file_type": (ext or "file").upper(),
"path": os.path.relpath(fp, DATA_DIR),
})
items.sort(key=lambda x: -x["mtime"])
total = len(items)
total_size = sum(x["size"] for x in items)
pages = max(1, (total + page_size - 1) // page_size)
page = min(page, pages)
start = (page - 1) * page_size
page_items = items[start:start + page_size]
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),
}}
if method == "POST" and sub == "/cleanup":
before = int(payload.get("before") or 0)
@@ -1295,8 +1552,45 @@ def admin_api(method: str, sub: str, payload: dict, handler):
if method == "POST" and sub == "/delete-file":
file_id = str(payload.get("id") or "")
username = str(payload.get("username") or "")
# MCP 文件删除:username 特殊标记 __mcp__,id=文件名(可含扩展名)
if username == "__mcp__":
if not file_id or file_id != os.path.basename(file_id) or file_id in (".", ".."):
return 400, {"code": 400, "message": "参数错误"}
mroot = os.path.realpath(os.path.join(DATA_DIR, "mcp_files"))
fp2 = os.path.realpath(os.path.join(mroot, file_id))
if not fp2.startswith(mroot + os.sep) or not os.path.isfile(fp2):
return 404, {"code": 404, "message": "文件不存在"}
size2 = os.path.getsize(fp2)
os.remove(fp2)
return 200, {"code": 200, "message": "ok", "data": {"freed": size2}}
if not re.match(r"^[A-Za-z0-9_-]{8,64}$", file_id) or not username:
return 400, {"code": 400, "message": "参数错误"}
# AI 生成图片删除:username 为特殊标记 __gen__,带 machine 定位 gen_images/<machine>/
if username == "__gen__":
machine = str(payload.get("machine") or "")
if not re.fullmatch(r"\d{10,16}", machine):
return 400, {"code": 400, "message": "参数错误"}
gdir = os.path.join(DATA_DIR, "gen_images", machine)
target = None
if os.path.isdir(gdir):
for fn in os.listdir(gdir):
if fn.startswith(file_id + ".") and os.path.isfile(os.path.join(gdir, fn)):
target = os.path.join(gdir, fn)
break
if not target:
return 404, {"code": 404, "message": "文件不存在"}
size = os.path.getsize(target)
os.remove(target)
idxp = os.path.join(gdir, "index.json")
with GEN_IMG_LOCK:
try:
idx = json.load(open(idxp, encoding="utf-8")) if os.path.exists(idxp) else []
idx = [it for it in idx if str((it or {}).get("id")) != file_id]
with open(idxp, "w", encoding="utf-8") as f:
json.dump(idx, f, ensure_ascii=False)
except Exception:
pass
return 200, {"code": 200, "message": "ok", "data": {"freed": size}}
base = os.path.join(_user_dir(username), "files")
target = os.path.join(base, file_id)
if not os.path.exists(target):
@@ -1445,6 +1739,8 @@ def admin_api(method: str, sub: str, payload: dict, handler):
if method == "GET" and sub == "/storage":
total = _dir_size(USERS_ROOT) if os.path.isdir(USERS_ROOT) else 0
if os.path.isdir(os.path.join(DATA_DIR, "gen_images")):
total += _dir_size(os.path.join(DATA_DIR, "gen_images"))
for extra in ("users.db", "usage.db", "trials.json"):
fp = os.path.join(DATA_DIR, extra)
if os.path.exists(fp):
@@ -1486,10 +1782,10 @@ def admin_api(method: str, sub: str, payload: dict, handler):
os.remove(probe)
except Exception as e:
return 400, {"code": 400, "message": f"目标路径不可写: {e}"}
# migrate existing data (users dir + db files)
# migrate existing data (users dir + AI 生成图片 + db files)
moved = []
old_root = DATA_DIR
for item in ("users",):
for item in ("users", "gen_images"):
src = os.path.join(old_root, item)
dst = os.path.join(new_root, item)
if os.path.isdir(src) and not os.path.isdir(dst):
@@ -2044,6 +2340,8 @@ class Handler(BaseHTTPRequestHandler):
self._reply(400, json.dumps({"code": 400, "message": "无效请求体"}, ensure_ascii=False).encode(), "application/json")
return
status, body = admin_api(method, sub, payload, self)
if status is None:
return # 二进制下载分支已自行写出响应
self._reply(status, json.dumps(body, ensure_ascii=False).encode("utf-8"), "application/json")
# ---------- 网速测试(用户浏览器 <-> 本站服务器) ----------
@@ -3121,9 +3419,15 @@ class Handler(BaseHTTPRequestHandler):
if parsed.path == "/ai/gen-image":
self._handle_gen_image()
return
if parsed.path == "/ai/img-save":
self._handle_img_save()
return
if parsed.path == "/ai/edit-image":
self._handle_edit_image()
return
if parsed.path == "/ai/face-swap":
self._handle_face_swap()
return
if parsed.path == "/ai/seamless-edit":
self._handle_seamless_edit()
return
@@ -3204,6 +3508,51 @@ class Handler(BaseHTTPRequestHandler):
self._reply(404, b"not found")
# ---------- 中文提示词自动转英文(Flux/SDXL 系对英文理解最好) ----------
_ZH_RE = re.compile(r"[\u4e00-\u9fff]")
_trans_cache: dict = {}
def _translate_prompt(self, prompt: str):
"""含中文才翻;成功 (英文, True);失败/未配置回退 (原文, False),绝不阻断生图。"""
if not prompt or not self._ZH_RE.search(prompt):
return prompt, False
cached = self._trans_cache.get(prompt)
if cached:
return cached, True
key = os.environ.get("NEWAPI_KEY", "")
if not key:
return prompt, False
try:
body = json.dumps({
"model": os.environ.get("IMG_PROMPT_MODEL", "mimo-v2.6-flash"),
"messages": [
{"role": "system", "content": (
"You are an expert prompt engineer for text-to-image models (Flux / SDXL / DALL-E). "
"Translate the user's Chinese image prompt into ONE high-quality English image-generation prompt. "
"Preserve every style, composition, aspect-ratio, lighting and detail keyword; you may expand "
"slightly for natural flow. Output ONLY the English prompt itself - no quotes, no explanations, "
"no Chinese characters, no markdown.")},
{"role": "user", "content": prompt},
],
"temperature": 0.3, "max_tokens": 500,
}).encode()
req = request.Request(
os.environ.get("NEWAPI_URL", "http://192.168.68.19:3099/v1/chat/completions"),
data=body, headers={"Content-Type": "application/json", "Authorization": "Bearer " + key})
data = json.loads(request.urlopen(req, timeout=30).read())
en = str(data.get("choices", [{}])[0].get("message", {}).get("content") or "").strip()
en = en.strip("`\"'\u201c\u201d ").strip()
if not en or self._ZH_RE.search(en[:120]):
return prompt, False
if len(self._trans_cache) >= 300:
self._trans_cache.clear()
self._trans_cache[prompt] = en
print(f"[img] prompt translated: {prompt[:40]} -> {en[:70]}", flush=True)
return en, True
except Exception as e: # noqa: BLE001
print(f"[img] translate failed, use original: {e}", flush=True)
return prompt, False
# ---------- AI 生图 (NEWAPI) ----------
def _nm_base(self):
return os.environ.get("NEWAPI_URL", "http://192.168.68.19:3099/v1/chat/completions").replace("/chat/completions", "")
@@ -3256,7 +3605,7 @@ class Handler(BaseHTTPRequestHandler):
b64 = item.get("b64_json") or ""
if not url and not b64:
raise RuntimeError("上游未返回图片")
self._reply(200, json.dumps({"code": 200, "message": "ok", "data": {"url": url, "b64": b64, "img_url": (d.get("img_url") or "") if isinstance(d, dict) else ""}}, ensure_ascii=False).encode("utf-8"), "application/json")
self._reply(200, json.dumps({"code": 200, "message": "ok", "data": {"url": url, "b64": b64, "img_url": (d.get("img_url") or "") if isinstance(d, dict) else "", "prompt_en": (d.get("prompt_en") or "") if isinstance(d, dict) else ""}}, ensure_ascii=False).encode("utf-8"), "application/json")
def _handle_image_models(self):
try:
@@ -3302,11 +3651,18 @@ class Handler(BaseHTTPRequestHandler):
msg = str(err or d.get("message") or "")
raise RuntimeError(msg[:300] or "上游未返回图片")
def _persist_gen_image(self, machine, d, model, prompt, w, h):
def _hist_owner(self, machine):
"""历史归属:登录账号优先,未登录回落机器码(铁规则:只看本人历史)。"""
u = _auth_user(self)
return u if u else machine
def _persist_gen_image(self, machine, d, model, prompt, w, h, kind="gen", owner=None):
"""把生成结果落盘并写入该机器的历史索引;返回站内图片 URL(任何失败返回空串)。"""
try:
if not self._gen_machine_ok(machine):
return ""
if owner is None:
owner = self._hist_owner(machine)
items = (d or {}).get("data") or []
if not items:
return ""
@@ -3321,6 +3677,14 @@ class Handler(BaseHTTPRequestHandler):
raw = rr.read()
if not raw or len(raw) < 200:
return ""
if not (w and h):
try:
from PIL import Image as _PIL
import io as _io
_im = _PIL.open(_io.BytesIO(raw))
w, h = _im.size
except Exception:
w, h = 0, 0
if raw[:8] == b"\x89PNG\r\n\x1a\n":
ext = ".png"
elif raw[:2] == b"\xff\xd8":
@@ -3349,6 +3713,8 @@ class Handler(BaseHTTPRequestHandler):
idx = []
idx.insert(0, {"id": iid, "file": fname, "at": int(time.time()),
"model": str(model)[:60], "prompt": str(prompt)[:500],
"kind": str(kind or "gen")[:20],
"owner": str(owner)[:64],
"w": w, "h": h})
while len(idx) > 100:
old = idx.pop() or {}
@@ -3439,26 +3805,103 @@ class Handler(BaseHTTPRequestHandler):
return
self._reply(200, json.dumps({"code": 200, "message": "ok", "data": ids[:200]}, ensure_ascii=False).encode("utf-8"), "application/json")
def _handle_img_save(self):
"""导出海报/成片落盘:客户端把 PNG base64 POST 上来,写入该机器的图片历史。"""
payload = self._read_payload()
machine = str(payload.get("machine") or "")
tool = str(payload.get("tool") or "poster-maker")[:40]
if tool in PROTECTED_TOOLS:
if check(machine, tool) != 200:
self._reply(403, json.dumps({"code": 403, "message": "需要授权或今日免费试用已用完"}, ensure_ascii=False).encode("utf-8"), "application/json")
return
elif not MACHINE_RE.match(machine or ""):
# 免费工具历史落盘:仅要求合法机器码,不走授权门禁
self._reply(400, json.dumps({"code": 400, "message": "bad machine"}, ensure_ascii=False).encode("utf-8"), "application/json")
return
b64 = str(payload.get("b64") or "")
if "," in b64[:100]:
b64 = b64.split(",", 1)[1]
if not b64:
self._reply(400, json.dumps({"code": 400, "message": "缺少图片数据"}, ensure_ascii=False).encode("utf-8"), "application/json")
return
if len(b64) > 40 * 1024 * 1024:
self._reply(413, json.dumps({"code": 413, "message": "图片超过 30MB 限制"}, ensure_ascii=False).encode("utf-8"), "application/json")
return
prompt = str(payload.get("prompt") or "海报导出")[:500]
model = str(payload.get("model") or "AI海报")[:60]
d = {"data": [{"b64_json": b64}]}
img_url = self._persist_gen_image(machine, d, model, prompt, 0, 0, kind=str(payload.get("kind") or "poster")[:20])
if not img_url:
self._reply(500, json.dumps({"code": 500, "message": "保存失败"}, ensure_ascii=False).encode("utf-8"), "application/json")
return
log_usage(machine, tool)
self._reply(200, json.dumps({"code": 200, "message": "ok", "data": {"img_url": img_url}}, ensure_ascii=False).encode("utf-8"), "application/json")
def _handle_img_history(self):
parsed = parse.urlparse(self.path)
qs = parse.parse_qs(parsed.query)
machine = str((qs.get("machine") or [""])[0] or "")
fkind = str((qs.get("kind") or [""])[0] or "")
if not self._gen_machine_ok(machine):
self._reply(400, json.dumps({"code": 400, "message": "bad machine"}, ensure_ascii=False).encode("utf-8"), "application/json")
return
idx_path = os.path.join(DATA_DIR, "gen_images", machine, "index.json")
items = []
if os.path.exists(idx_path):
# 铁规则:只看本人历史。登录=账号本人条目(跨设备)+ 本机匿名条目;
# 未登录=仅本机匿名条目(owner 为空或等于机器码,含迁移前旧记录)。
me = _auth_user(self)
root = os.path.join(DATA_DIR, "gen_images")
pairs = []
if me:
try:
items = json.load(open(idx_path, encoding="utf-8"))
if not isinstance(items, list):
items = []
for name in sorted(os.listdir(root)):
ip = os.path.join(root, name, "index.json")
if not os.path.isfile(ip):
continue
try:
its = json.load(open(ip, encoding="utf-8"))
except Exception:
continue
if isinstance(its, list):
pairs.append((name, its))
except Exception:
items = []
pairs = []
else:
its = []
ip = os.path.join(root, machine, "index.json")
if os.path.exists(ip):
try:
its = json.load(open(ip, encoding="utf-8"))
except Exception:
its = []
if not isinstance(its, list):
its = []
pairs.append((machine, its))
items = []
for name, its in pairs:
for it in its:
if isinstance(it, dict):
it["_dir"] = name
items.append(it)
if fkind:
# kind 过滤:逗号分隔多值;旧记录无 kind 字段视为 "gen"
want = {k for k in fkind.split(",") if k}
items = [it for it in items if str(it.get("kind") or "gen") in want]
vis = []
for it in items:
if isinstance(it, dict):
it["img_url"] = f"/relay/ai/img/{machine}/{it.get('id', '')}"
self._reply(200, json.dumps({"code": 200, "message": "ok", "data": items}, ensure_ascii=False).encode("utf-8"), "application/json")
o = str(it.get("owner") or "")
d = str(it.get("_dir") or machine)
if me:
ok = (o == me) or (d == machine and (not o or o == machine))
else:
ok = (d == machine) and (not o or o == machine)
if ok:
it["img_url"] = f"/relay/ai/img/{d}/{it.get('id', '')}"
vis.append(it)
vis.sort(key=lambda x: int(x.get("at") or 0), reverse=True)
# 铁规则:所有功能历史最多显示 100 条(按时间倒序取前 100)
vis = vis[:100]
for it in vis:
it.pop("_dir", None)
self._reply(200, json.dumps({"code": 200, "message": "ok", "data": vis}, ensure_ascii=False).encode("utf-8"), "application/json")
def _handle_img_file(self, parsed):
# 兼容两条链路:直连 relay(/relay/ai/img/m/id)与经 nginx(/ai/img/m/id)
@@ -3525,20 +3968,28 @@ class Handler(BaseHTTPRequestHandler):
w, h = 1024, 1024
w = max(16, min(2048, w))
h = max(16, min(2048, h))
# 中文提示词自动转英文再发上游(Flux/SDXL 英文效果最好;翻译失败回退原文)
gen_prompt, translated = self._translate_prompt(prompt)
try:
if own_provider:
d = self._provider_images_gen(provider, model, prompt, f"{w}x{h}")
d = self._provider_images_gen(provider, model, gen_prompt, f"{w}x{h}")
else:
d = self._nm_images_gen(model, prompt, f"{w}x{h}")
d = self._nm_images_gen(model, gen_prompt, f"{w}x{h}")
daily_consume(machine, model) # 内置渠道成功才扣次(机器计数 + CF 共享池)
except Exception as e: # noqa: BLE001
print(f"[img] gen failed: {e}", flush=True)
self._reply(502, json.dumps({"code": 502, "message": f"生图失败:{e}"}, ensure_ascii=False).encode("utf-8"), "application/json")
return
# 落盘保存到该机器的历史(失败不阻断响应)
img_url = self._persist_gen_image(machine, d, model, prompt, w, h)
try:
kind = str(payload.get("kind") or "gen")[:20]
except Exception:
kind = "gen"
img_url = self._persist_gen_image(machine, d, model, prompt, w, h, kind=kind) # 历史存用户原文
if isinstance(d, dict) and img_url:
d["img_url"] = img_url
if translated and isinstance(d, dict):
d["prompt_en"] = gen_prompt # 实际发给上游的英文提示词(供前端提示)
self._img_reply_ok(d)
def _handle_edit_image(self):
@@ -3565,8 +4016,15 @@ class Handler(BaseHTTPRequestHandler):
return
try:
img = up.file.read()
d = self._nm_images_edit(model, prompt, img, up.filename)
gen_prompt, translated = self._translate_prompt(prompt)
d = self._nm_images_edit(model, gen_prompt, img, up.filename)
daily_consume(machine, model) # 内置渠道成功才扣次(机器计数 + CF 共享池)
if translated and isinstance(d, dict):
d["prompt_en"] = gen_prompt
# 铁规则:生成即保存到后台存储目录(失败静默,不阻断响应)
img_url = self._persist_gen_image(machine, d, model, prompt, 0, 0, kind="edit")
if img_url and isinstance(d, dict):
d["img_url"] = img_url
self._img_reply_ok(d)
except Exception as e: # noqa: BLE001
print(f"[img] edit failed: {e}", flush=True)
@@ -3820,6 +4278,96 @@ class Handler(BaseHTTPRequestHandler):
canvas.paste(im2, ((tw - im2.width) // 2, (th - im2.height) // 2))
return canvas
def _handle_face_swap(self):
"""AI换脸(授权功能):源人脸照片 -> 目标照片,本机 CPU 推理,结果走 /ai/img 站内图链路。"""
machine = self.headers.get("X-Machine-Id", "")
code = check(machine, "face-swap")
if code != 200:
self._reply(403, json.dumps({"code": 403, "message": "AI换脸是授权功能:试用期内可免费体验,正式使用请先激活卡密"},
ensure_ascii=False).encode("utf-8"), "application/json")
return
log_usage(machine, "face-swap")
ctype = self.headers.get("Content-Type") or ""
if "multipart/form-data" not in ctype:
self._reply(400, json.dumps({"code": 400, "message": "需要 multipart/form-data"}, ensure_ascii=False).encode("utf-8"), "application/json")
return
try:
form = cgi.FieldStorage(fp=self.rfile, headers=self.headers,
environ={"REQUEST_METHOD": "POST", "CONTENT_TYPE": ctype})
except Exception as e: # noqa: BLE001
self._reply(400, json.dumps({"code": 400, "message": f"表单解析失败: {e}"}, ensure_ascii=False).encode("utf-8"), "application/json")
return
if str(form.getvalue("consent") or "") != "1":
self._reply(400, json.dumps({"code": 400, "message": "请先勾选「我承诺仅使用已获本人授权的照片进行换脸」"},
ensure_ascii=False).encode("utf-8"), "application/json")
return
try:
src_raw = form["source"].file.read() if "source" in form else b""
dst_raw = form["target"].file.read() if "target" in form else b""
except Exception:
src_raw, dst_raw = b"", b""
if not src_raw or not dst_raw:
self._reply(400, json.dumps({"code": 400, "message": "请同时上传源人脸照片与目标照片"}, ensure_ascii=False).encode("utf-8"), "application/json")
return
if len(src_raw) > 15 * 1024 * 1024 or len(dst_raw) > 15 * 1024 * 1024:
self._reply(400, json.dumps({"code": 400, "message": "单张图片不能超过 15MB"}, ensure_ascii=False).encode("utf-8"), "application/json")
return
import cv2 as _cv2
import numpy as _np
src_img = _cv2.imdecode(_np.frombuffer(src_raw, _np.uint8), _cv2.IMREAD_COLOR)
dst_img = _cv2.imdecode(_np.frombuffer(dst_raw, _np.uint8), _cv2.IMREAD_COLOR)
if src_img is None or dst_img is None:
self._reply(400, json.dumps({"code": 400, "message": "图片解码失败,请上传 JPG/PNG 等常见格式"}, ensure_ascii=False).encode("utf-8"), "application/json")
return
try:
out_jpg, msg, ms = _face_swap_run(src_img, dst_img)
except Exception as e: # noqa: BLE001
print(f"[face-swap] failed: {e}", flush=True)
self._reply(500, json.dumps({"code": 500, "message": f"换脸失败: {e}"}, ensure_ascii=False).encode("utf-8"), "application/json")
return
if out_jpg is None:
self._reply(400, json.dumps({"code": 400, "message": msg}, ensure_ascii=False).encode("utf-8"), "application/json")
return
try:
gen_dir = os.path.join(DATA_DIR, "gen_images", machine)
os.makedirs(gen_dir, exist_ok=True)
iid = f"{int(time.time())}_{uuid.uuid4().hex[:8]}"
with open(os.path.join(gen_dir, iid + ".jpg"), "wb") as f:
f.write(out_jpg)
idx_path = os.path.join(gen_dir, "index.json")
with GEN_IMG_LOCK:
idx = []
if os.path.exists(idx_path):
try:
idx = json.load(open(idx_path, encoding="utf-8"))
if not isinstance(idx, list):
idx = []
except Exception:
idx = []
idx.insert(0, {"id": iid, "file": iid + ".jpg", "at": int(time.time()),
"model": "AI换脸", "prompt": "face-swap",
"kind": "face-swap",
"owner": str(self._hist_owner(machine))[:64],
"w": int(dst_img.shape[1]), "h": int(dst_img.shape[0])})
while len(idx) > 100:
old = idx.pop() or {}
fn = str(old.get("file") or "")
if fn and "/" not in fn and "\\" not in fn:
try:
os.remove(os.path.join(gen_dir, fn))
except Exception:
pass
with open(idx_path, "w", encoding="utf-8") as f:
json.dump(idx, f, ensure_ascii=False)
except Exception as e: # noqa: BLE001
print(f"[face-swap] persist failed: {e}", flush=True)
self._reply(500, json.dumps({"code": 500, "message": "结果保存失败"}, ensure_ascii=False).encode("utf-8"), "application/json")
return
body = json.dumps({"code": 200, "message": "ok",
"data": {"url": f"/relay/ai/img/{machine}/{iid}", "elapsed_ms": ms}},
ensure_ascii=False).encode("utf-8")
self._reply(200, body, "application/json")
def _handle_seamless_edit(self):
machine = self.headers.get("X-Machine-Id", "")
if check(machine, "ai-text-edit") != 200:
@@ -3915,6 +4463,14 @@ class Handler(BaseHTTPRequestHandler):
self._reply(502, json.dumps({"code": 502, "message": f"重绘失败:{e}"}, ensure_ascii=False).encode("utf-8"), "application/json")
return
# 落盘到该机器图片历史(铁规则:生成即保存,失败不阻断响应)
try:
for im in images:
self._persist_gen_image(machine, {"data": [{"b64_json": im["b64"]}]},
"无痕改字", prompt, base_im.size[0], base_im.size[1],
kind="seamless")
except Exception as _pe: # noqa: BLE001
print(f"[se] persist failed: {_pe}", flush=True)
pub = [{"old": r["old"], "new": r["new"] or "(仅删除)", "style": r["style"]} for r in results]
self._reply(200, json.dumps({"code": 200, "message": "ok", "data": {"images": images, "edits": pub, "note": note}}, ensure_ascii=False).encode("utf-8"), "application/json")
+10
View File
@@ -44,6 +44,11 @@ function expandAll() {
for (const { name } of toolsByCategory.value) {
m[name] = false;
}
// 我的收藏 / 授权应用 也在渲染菜单里,必须一起收放(2026-11-13 用户要求)
if (props.favoriteCategory?.name) {
m[props.favoriteCategory.name] = false;
}
m[PAID_GROUP_NAME] = false;
collapsedCategories.value = m;
}
@@ -52,6 +57,11 @@ function collapseAll() {
for (const { name } of toolsByCategory.value) {
m[name] = true;
}
// 我的收藏 / 授权应用 也在渲染菜单里,必须一起收放(2026-11-13 用户要求)
if (props.favoriteCategory?.name) {
m[props.favoriteCategory.name] = true;
}
m[PAID_GROUP_NAME] = true;
collapsedCategories.value = m;
}
+1 -1
View File
@@ -40,7 +40,7 @@ useHead(head);
const { t } = useI18n();
// 宽屏工具:不受 600px 限宽,占满可用宽度(画布/多栏类工具)
const WIDE_TOOLS = new Set(['/label-designer', '/json-prettify', '/pdf-tools', '/image-tools', '/doc-convert', '/video-tools', '/seal-maker', '/signature-pad', '/ai-image-lab', '/ai-chat', '/copywriting', '/ai-gen', '/code-reader', '/my-ip', '/mcp-connect']);
const WIDE_TOOLS = new Set(['/label-designer', '/json-prettify', '/pdf-tools', '/image-tools', '/doc-convert', '/video-tools', '/seal-maker', '/signature-pad', '/ai-image-lab', '/ai-chat', '/copywriting', '/ai-gen', '/code-reader', '/my-ip', '/mcp-connect', '/poster-maker', '/ai-text-edit', '/ai-retouch']);
const isWide = computed(() => WIDE_TOOLS.has(route.path));
const i18nKey = computed<string>(() => route.path.trim().replace('/', ''));
+178 -31
View File
@@ -107,25 +107,66 @@ async function loadOverview() {
overview.value = b.data;
}
// ============ 文件管理 ============
const fileUser = ref('');
// ============ 文件管理(默认全量聚合,50 条/页自动分页)============
const fileUser = ref(''); // ''=全部, '__gen__'=AI生成, 其他=指定用户
const fileList = ref<any[]>([]);
const fileTotal = ref(0);
const fileTotal = ref(0); // 合计字节数
const fileCount = ref(0); // 总记录数
const filePage = ref(1);
const filePages = ref(1);
const FILE_PAGE_SIZE = 50;
const cleanupDays = ref(7);
const cleanupUser = ref('');
const cleanupResult = ref('');
async function loadFiles() {
if (!fileUser.value) {
return;
}
const b = await api(`/admin/files?username=${encodeURIComponent(fileUser.value)}`);
const q = new URLSearchParams();
if (fileUser.value === '__gen__') q.set('scope', 'gen');
else if (fileUser.value) q.set('username', fileUser.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 ?? [];
fileTotal.value = b.data?.total_size ?? 0;
fileCount.value = b.data?.total ?? 0;
filePages.value = b.data?.pages ?? 1;
filePage.value = b.data?.page ?? 1;
}
async function delFile(id: string) {
const b = await api('/admin/delete-file', { method: 'POST', body: JSON.stringify({ id, username: fileUser.value }) });
function gotoFilePage(p: number) {
filePage.value = Math.min(Math.max(1, p), filePages.value);
loadFiles();
}
// 文件直链:缩略图 <img> 与下载 <a> 无法携带 header,鉴权走 ?token=
function fileUrl(f: any, dl = false) {
const q = new URLSearchParams();
q.set('path', f.path || '');
if (f.name) q.set('name', f.name);
if (dl) q.set('dl', '1');
if (token.value) q.set('token', token.value);
return `/relay/admin/file?${q}`;
}
function windowOpen(url: string) {
window.open(url, '_blank', 'noopener');
}
function fileOwner(f: any) {
if (f.source === 'gen') return f.machine || 'AI';
if (f.source === 'mcp') return 'MCP';
return f.username || f.source || '-';
}
async function delFile(f: any) {
const body: any = { id: f.id };
if (f.source === 'gen') {
body.username = '__gen__';
body.machine = f.machine;
} else if (f.source === 'mcp') {
body.username = '__mcp__';
} else {
body.username = f.username || fileUser.value;
}
const b = await api('/admin/delete-file', { method: 'POST', body: JSON.stringify(body) });
if (b.code === 200) {
await loadFiles();
loadOverview();
@@ -144,9 +185,8 @@ async function cleanup() {
if (b.code === 200) {
cleanupResult.value = `已删除 ${b.data.removed} 个文件,释放 ${fmtSize(b.data.freed)}`;
loadOverview();
if (fileUser.value) {
loadFiles();
}
filePage.value = 1;
loadFiles();
}
}
@@ -154,6 +194,7 @@ function pickUser(u: string) {
fileUser.value = u;
cleanupUser.value = u;
tab.value = 'files';
filePage.value = 1;
loadFiles();
}
@@ -495,6 +536,9 @@ function switchTab(id: 'overview' | 'files' | 'usage' | 'mcp' | 'storage' | 'rec
if (id === 'feedback') {
loadFeedback();
}
if (id === 'files') {
loadFiles();
}
}
</script>
@@ -592,11 +636,17 @@ function switchTab(id: 'overview' | 'files' | 'usage' | 'mcp' | 'storage' | 'rec
<!-- files -->
<template v-if="tab === 'files'">
<div class="adm-toolbar">
<select v-model="fileUser" class="adm-select" @change="loadFiles">
<option value="">选择用户…</option>
<option v-for="u in users" :key="u.username" :value="u.username">{{ u.username }}</option>
<select v-model="fileUser" class="adm-select" @change="filePage = 1; loadFiles()">
<option value="">全部(所有用户 + AI 生成 + MCP)</option>
<option value="__gen__">仅 AI 生成图片(换脸/生图/海报)</option>
<option v-for="u in users" :key="u.username" :value="u.username">仅 {{ u.username }}</option>
</select>
<span v-if="fileList.length" class="adm-sub">{{ fileList.length }} 个文件 · 合计 {{ fmtSize(fileTotal) }}</span>
<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>
<span class="adm-pageinfo">第 {{ filePage }} / {{ filePages }} 页</span>
<button class="adm-btn adm-btn-sm" :disabled="filePage >= filePages" @click="gotoFilePage(filePage + 1)">下一页 ›</button>
</span>
</div>
<div class="adm-cleanup">
@@ -617,21 +667,36 @@ function switchTab(id: 'overview' | 'files' | 'usage' | 'mcp' | 'storage' | 'rec
<span v-if="cleanupResult" class="adm-ok">{{ cleanupResult }}</span>
</div>
<table class="adm-table">
<thead>
<tr><th>文件</th><th>类型</th><th>大小</th><th>时间</th><th></th></tr>
</thead>
<tbody>
<tr v-for="f in fileList" :key="f.id">
<td class="adm-fname">{{ f.name }}</td>
<td>{{ f.kind || '-' }}</td>
<td>{{ fmtSize(f.size) }}</td>
<td>{{ fmtTime(f.mtime) }}</td>
<td><a href="javascript:;" class="adm-del" @click="delFile(f.id)">删除</a></td>
</tr>
<tr v-if="!fileList.length"><td colspan="5" class="adm-none">{{ fileUser ? '该用户暂无文件' : '请先选择用户' }}</td></tr>
</tbody>
</table>
<div class="adm-fscroll">
<table class="adm-table">
<thead>
<tr><th class="adm-thumbcol">预览</th><th>文件</th><th>来源</th><th>类型</th><th>大小</th><th>时间</th><th></th></tr>
</thead>
<tbody>
<tr v-for="f in fileList" :key="(f.source || '') + ':' + (f.machine || '') + ':' + f.id">
<td class="adm-thumbcell">
<img v-if="f.is_image" class="adm-thumb" :src="fileUrl(f)" alt="" @click="windowOpen(fileUrl(f))">
<span v-else class="adm-ftype">{{ f.file_type || '文件' }}</span>
</td>
<td class="adm-fname" :title="f.prompt || f.name">{{ f.name }}</td>
<td>{{ fileOwner(f) }}</td>
<td>{{ f.kind || '-' }}</td>
<td>{{ fmtSize(f.size) }}</td>
<td>{{ fmtTime(f.mtime) }}</td>
<td class="adm-ops">
<a :href="fileUrl(f, true)" class="adm-dl" download>下载</a>
<a href="javascript:;" class="adm-del" @click="delFile(f)">删除</a>
</td>
</tr>
<tr v-if="!fileList.length"><td colspan="7" class="adm-none">暂无文件</td></tr>
</tbody>
</table>
</div>
<div v-if="filePages > 1" class="adm-pager adm-pager-b">
<button class="adm-btn adm-btn-sm" :disabled="filePage <= 1" @click="gotoFilePage(filePage - 1)">‹ 上一页</button>
<span class="adm-pageinfo">第 {{ filePage }} / {{ filePages }} 页 · 共 {{ fileCount }} 条</span>
<button class="adm-btn adm-btn-sm" :disabled="filePage >= filePages" @click="gotoFilePage(filePage + 1)">下一页 ›</button>
</div>
</template>
<!-- storage -->
@@ -1248,6 +1313,88 @@ function switchTab(id: 'overview' | 'files' | 'usage' | 'mcp' | 'storage' | 'rec
}
}
/* ===== 文件管理:缩略图/类型徽标/分页 ===== */
.adm-fscroll {
overflow-x: auto;
-webkit-overflow-scrolling: touch;
.adm-table {
min-width: 860px;
th {
white-space: nowrap;
}
}
}
.adm-thumbcol,
.adm-thumbcell {
width: 116px;
padding-top: 8px !important;
padding-bottom: 8px !important;
}
.adm-thumb {
width: 100px;
height: 100px;
object-fit: cover;
border-radius: 8px;
border: 1px solid rgba(128, 128, 128, 0.22);
background: rgba(128, 128, 128, 0.06);
display: block;
cursor: zoom-in;
}
.adm-ftype {
display: flex;
align-items: center;
justify-content: center;
width: 100px;
height: 64px;
border-radius: 8px;
background: rgba(128, 128, 128, 0.1);
font-weight: 700;
font-size: 13px;
letter-spacing: 0.5px;
color: rgba(128, 128, 128, 0.95);
text-transform: uppercase;
}
.adm-ops {
white-space: nowrap;
a + a {
margin-left: 10px;
}
}
.adm-dl {
color: #18a058;
text-decoration: none;
&:hover {
text-decoration: underline;
}
}
.adm-pager {
display: inline-flex;
align-items: center;
gap: 8px;
}
.adm-pager-b {
display: flex;
justify-content: center;
margin-top: 14px;
}
.adm-pageinfo {
font-size: 12.5px;
opacity: 0.75;
white-space: nowrap;
}
.adm-userbar {
display: flex;
align-items: center;
+8 -5
View File
@@ -1,6 +1,9 @@
<script setup lang="ts">
import { useHead } from '@vueuse/head';
import { AUTH_BASE, getMachineId, licenseState, checkAuth } from '@/tools/license/license';
import { AUTH_BASE, getMachineId, licenseState, checkAuth, PROTECTED_TOOLS } from '@/tools/license/license';
/** 授权功能数量:与 pricing/侧栏同源(license.ts PROTECTED_TOOLS),新授权应用上线自动 +1 */
const paidCount = Object.keys(PROTECTED_TOOLS).length;
useHead({ title: '购买卡密 - IT-TOOLS-PRO' });
@@ -121,7 +124,7 @@ async function refreshAuth(): Promise<void> {
authMsg.value = '正在核验授权…';
try {
const ok = await checkAuth();
authMsg.value = ok ? '授权已生效,13 个高级功能已解锁' : '卡密已发放,授权暂未刷新,请点击下方重新核验';
authMsg.value = ok ? `授权已生效,${paidCount} 个高级功能已解锁` : '卡密已发放,授权暂未刷新,请点击下方重新核验';
} catch {
authMsg.value = '授权核验失败,请稍后重试';
}
@@ -208,7 +211,7 @@ onUnmounted(stopPoll);
<div class="hero">
<div class="hero-title">🔐 购买卡密</div>
<div class="hero-sub">
支付成功后本页直接显示卡密,同时本机立即解锁 13 个高级功能
支付成功后本页直接显示卡密,同时本机立即解锁 {{ paidCount }} 个高级功能
</div>
</div>
@@ -248,7 +251,7 @@ onUnmounted(stopPoll);
<span class="cur">¥</span>{{ p.price }}
<span v-if="Number(p.original_price) > 0" class="origin">¥{{ p.original_price }}</span>
</div>
<div class="plan-meta">{{ fmtDays(p.duration_days) }} · 13 个高级功能</div>
<div class="plan-meta">{{ fmtDays(p.duration_days) }} · {{ paidCount }} 个高级功能</div>
<div v-if="p.description" class="plan-desc">{{ p.description }}</div>
</div>
<div v-if="!plans.length" class="tip">暂无可售套餐</div>
@@ -346,7 +349,7 @@ onUnmounted(stopPoll);
<div class="notes">
<div class="note-item">🔒 买断制:不按次、不按月,一次付费永久使用。</div>
<div class="note-item">🧭 授权跟随机器码绑定,换电脑用卡密重新激活即可恢复。</div>
<div class="note-item">🎁 支付成功即解锁 13 个高级功能,无需等待人工发货。</div>
<div class="note-item">🎁 支付成功即解锁 {{ paidCount }} 个高级功能,无需等待人工发货。</div>
<div class="note-item">❓ 卡密丢失可凭订单号联系管理员找回。</div>
</div>
</div>
+4
View File
@@ -11,6 +11,10 @@ import { useRecentTools } from '@/composable/recent-tools';
// 近期新功能亮点(手动维护,新工具上线时加一条)
// ★铁规则:每完成一批新功能/新工具,必须在这里最前面加条目(新→旧),否则首页看不到
const NEW_FEATURES = [
{ path: '/admin', icon: '📁', name: '后台文件管理', desc: '默认聚合所有用户文件与AI生成图片,每页50条自动分页显示总记录数,图片100×100缩略图、其他文件显示类型,全部支持单独下载' },
{ path: '/ai-gen', icon: '🗂️', name: '图片历史铁规则', desc: '所有生图功能右侧 50×50 缩略图历史竖排、点击看大图,按登录账号/机器码只看本人的,生成即保存到后台指定目录,全部功能历史最多显示100条' },
{ path: '/face-swap', icon: '🎭', name: 'AI 换脸', desc: '上传源人脸与目标照片,本地 AI 一键换脸(insightface 人脸检测+inswapper),授权功能支持免费试用' },
{ path: '/poster-maker', icon: '🖼️', name: 'AI 海报生成', desc: '42套模板10分类(含校园师生款)、文字图片可旋转、整页自适应不滚动,改文字换图片AI生成配图,一键导出 PNG' },
{ path: '/ai-gen', icon: '🎨', name: 'AI 生图', desc: '10款内置模型一键出图,四组86个现成提示词(通用/自媒体/电商/软件类),中文自动转英文发送' },
{ path: '/mcp-connect', icon: '🔌', name: 'AI 接入 (MCP)', desc: '把本站能力接到任意 AI 客户端,13个工具、卡密令牌管理、调用记录后台可查' },
{ path: '/admin', icon: '📊', name: '管理后台升级', desc: '使用统计含未登录访客、在线人数实时排行、留言反馈与公告推送、用户最后登录时间' },
+34 -60
View File
@@ -1,6 +1,7 @@
<script setup lang="ts">
import { useHead } from '@vueuse/head';
import { PROTECTED_TOOLS, getMachineId } from '@/tools/license/license';
import { useToolStore } from '@/tools/tools.store';
useHead({ title: '授权应用 - IT-TOOLS-PRO' });
@@ -18,65 +19,38 @@ interface Feature {
points: string[];
}
const FEATURES: Feature[] = [
{
path: '/translator',
name: '在线翻译',
icon: '🌐',
points: ['文本翻译 16 种语言,自动识别源语言', '中英互译走本地开源引擎不限流,其他语种自动切备用线路', '文档整篇翻译(中英),扫描件/图片自动 OCR,译文可下载'],
},
{
path: '/image-ocr',
name: '图片OCR文字识别',
icon: '📷',
points: ['本地 OCR 引擎,中文识别准确率 99%+', '截图、扫描件、照片文字一键提取', '逐行输出带置信度,支持粘贴图片'],
},
{
path: '/pdf-ocr',
name: 'PDF文字识别',
icon: '📄',
points: ['逐页 OCR 中英文 PDF(最多 50 页)', '每页预览、翻页查看识别结果', '一键复制全部或下载 TXT'],
},
{
path: '/ai-retouch',
name: 'AI修图',
icon: '🎨',
points: ['去水印/修复:涂抹区域智能填充', '抠图去背景、4x 超分辨率、人脸修复', '本地 AI 模型推理,单张 10 秒级出图'],
},
{
path: '/pdf-tools',
name: 'PDF工具',
icon: '📑',
points: ['合并/拆分/旋转/重排/压缩等 11 种常用处理', '加密/解密/加水印/提取文本/加页码/转图片', '全程浏览器本地处理,文件不上传服务器'],
},
{
path: '/image-tools',
name: '图片工具',
icon: '🖼️',
points: ['压缩/转换/尺寸/裁剪/旋转/滤镜等 12 种常用处理', '打码、加水印、拼接、EXIF 查看编辑', '全程浏览器本地处理,图片不上传服务器'],
},
{
path: '/video-tools',
name: '视频工具',
icon: '🎥',
points: ['格式转换/压缩/裁剪/旋转/变速/消音/提取音频/截图/GIF互转等 11 个工具', '服务端 ffmpeg 高速转码,最大支持 2GB 视频', '处理完在线预览,一键下载结果'],
},
{
path: '/audio-tools',
name: '音频工具',
icon: '🎙️',
points: ['文字转音频:本地神经 TTS,离线可用速度快', '音频转文字:Whisper 引擎,中英日粤自动检测带时间轴', '声音克隆:5 秒样本克隆音色(即将上线)'],
},
{
path: '/doc-convert',
name: '文档格式转换',
icon: '🔄',
points: ['Word/PDF/TXT/RTF/ODT/EPUB/MOBI/AZW3/HTML 九种格式互转', '自建转换引擎,批量转换打包下载', '单文件最快几秒完成'],
},
];
/** 授权功能营销卖点:key = 工具 path。
* ★ 新开发的授权应用只要加进 license.ts 的 PROTECTED_TOOLS,本页会自动出现,
* 没写文案的会用工具自身的名称/描述兜底(想更好看再往这张表里补 icon + points)。
* (2026-11-13 用户要求:授权应用开发完必须自动同步到本页,禁止再手工维护清单) */
const MARKETING: Record<string, { icon: string; points: string[] }> = {
'/translator': { icon: '🌐', points: ['文本翻译 16 种语言,自动识别源语言', '中英互译走本地开源引擎不限流,其他语种自动切备用线路', '文档整篇翻译(中英),扫描件/图片自动 OCR,译文可下载'] },
'/image-ocr': { icon: '📷', points: ['本地 OCR 引擎,中文识别准确率 99%+', '截图、扫描件、照片文字一键提取', '逐行输出带置信度,支持粘贴图片'] },
'/pdf-ocr': { icon: '📄', points: ['逐页 OCR 中英文 PDF(最多 50 页)', '每页预览、翻页查看识别结果', '一键复制全部或下载 TXT'] },
'/ai-retouch': { icon: '🎨', points: ['去水印/修复:涂抹区域智能填充', '抠图去背景、4x 超分辨率、人脸修复', '本地 AI 模型推理,单张 10 秒级出图'] },
'/pdf-tools': { icon: '📑', points: ['合并/拆分/旋转/重排/压缩等 11 种常用处理', '加密/解密/加水印/提取文本/加页码/转图片', '全程浏览器本地处理,文件不上传服务器'] },
'/image-tools': { icon: '🖼️', points: ['压缩/转换/尺寸/裁剪/旋转/滤镜等 12 种常用处理', '打码、加水印、拼接、EXIF 查看编辑', '全程浏览器本地处理,图片不上传服务器'] },
'/video-tools': { icon: '🎥', points: ['格式转换/压缩/裁剪/旋转/变速/消音/提取音频/截图/GIF互转等 11 个工具', '服务端 ffmpeg 高速转码,最大支持 2GB 视频', '处理完在线预览,一键下载结果'] },
'/audio-tools': { icon: '🎙️', points: ['文字转音频:本地神经 TTS,离线可用速度快', '音频转文字:Whisper 引擎,中英日粤自动检测带时间轴', '声音克隆:5 秒样本克隆音色(即将上线)'] },
'/doc-convert': { icon: '🔄', points: ['Word/PDF/TXT/RTF/ODT/EPUB/MOBI/AZW3/HTML 九种格式互转', '自建转换引擎,批量转换打包下载', '单文件最快几秒完成'] },
'/text-to-image': { icon: '🔤', points: ['输入文字一键排版成图,字体/颜色/尺寸/背景可调', '适合做封面、标语、社媒配图,出图即下载', '本地渲染不联网,批量出图不排队'] },
'/ai-image-lab': { icon: '🪄', points: ['智能抠图去背景,发丝级边缘', 'AI 无损放大、模糊变清晰', '证件照制作:换底色、按规格裁剪'] },
'/copywriting': { icon: '✍️', points: ['AI 一键改写、降低 AIGC 率', '爆款标题、小红书/朋友圈文案', '多风格模板,改完即可用'] },
'/ai-gen': { icon: '🖌️', points: ['多模型文生图,宽高比可选', '内置示例提示词,新手一键出图', '生成记录可管理、可下载'] },
};
// only show tools that are actually in the protected list
const paidFeatures = FEATURES.filter(f => f.path in PROTECTED_TOOLS);
/** 授权功能清单 = license.ts 的 PROTECTED_TOOLS(唯一权威源),本页零手工维护 */
const toolStore = useToolStore();
const paidFeatures = computed<Feature[]>(() => Object.keys(PROTECTED_TOOLS).map((path) => {
const tool = toolStore.tools.find(t => t.path === path);
const m = MARKETING[path];
return {
path,
name: PROTECTED_TOOLS[path] || tool?.name || path,
icon: m?.icon || '🧩',
points: m?.points || [tool?.description || '授权高级功能,一次激活全部通用'],
};
}));
const machineId = getMachineId();
const copied = ref(false);
@@ -108,7 +82,7 @@ async function copyMachine() {
<div class="hero">
<div class="hero-title">🚀 授权解锁全部高级功能</div>
<div class="hero-sub">
IT-TOOLS-PRO 的 20+ 基础工具永久免费(含面单设计),下面 9 个算力型高级功能需要授权。一次激活,全部通用。
IT-TOOLS-PRO 的 20+ 基础工具永久免费(含面单设计),下面 {{ paidFeatures.length }} 个算力型高级功能需要授权。一次激活,全部通用。
</div>
</div>
@@ -144,7 +118,7 @@ async function copyMachine() {
<div class="adv-card">
<div class="adv-icon">🔑</div>
<div class="adv-title">一次激活,全站通用</div>
<div class="adv-desc">输入一次卡密,13 个高级功能全部解锁,无需逐个购买</div>
<div class="adv-desc">输入一次卡密,{{ paidFeatures.length }} 个高级功能全部解锁,无需逐个购买</div>
</div>
<div class="adv-card">
<div class="adv-icon">♾️</div>
+5 -3
View File
@@ -1,5 +1,6 @@
<script setup lang="ts">
import { getMachineId, licenseHeaders } from '@/tools/license/license';
import { authHdr } from '@/tools/img-hist/img-hist';
const models = ref<{ id: string; i2i: boolean; custom?: boolean }[]>([]);
const model = ref(''); // 打开页面默认选中列表第一个模型
@@ -101,9 +102,10 @@ function mergeModels() {
const history = ref<{ id: string; at: number; model: string; prompt: string; img_url: string }[]>([]);
async function loadHistory() {
try {
const res = await fetch(`/relay/ai/img-history?machine=${encodeURIComponent(getMachineId())}`);
const res = await fetch(`/relay/ai/img-history?machine=${encodeURIComponent(getMachineId())}&kind=gen`, { headers: authHdr() });
const j = await res.json();
if (j.code === 200 && Array.isArray(j.data)) history.value = j.data;
// 铁规则:所有功能历史最多显示 100 条
if (j.code === 200 && Array.isArray(j.data)) history.value = j.data.slice(0, 100);
} catch { /* ignore */ }
}
function openHist(it: any) {
@@ -337,7 +339,7 @@ async function generate() {
}
const res = await fetch('/relay/ai/gen-image', {
method: 'POST',
headers: { 'Content-Type': 'application/json', ...licenseHeaders('ai-gen') },
headers: { 'Content-Type': 'application/json', ...licenseHeaders('ai-gen'), ...authHdr() },
body: JSON.stringify(body),
});
const j = await res.json().catch(() => ({}));
+19 -8
View File
@@ -2,11 +2,22 @@
import { onMounted, ref } from 'vue';
import { useHead } from '@vueuse/head';
import { licenseHeaders } from '@/tools/license/license';
import GenHistory from '@/tools/gen-history/GenHistory.vue';
import { useGenHistory } from '@/tools/gen-history/gen-history';
import ImgHist from '@/tools/img-hist/ImgHist.vue';
import { blobToB64, dataUrlToB64, saveImgHist } from '@/tools/img-hist/img-hist';
useHead({ title: 'AI 图片实验室 - IT-TOOLS-PRO' });
const genHist = useGenHistory('ai-image-lab');
const histRef = ref<InstanceType<typeof ImgHist> | null>(null);
/** 处理结果保存到服务器历史(失败静默,不影响下载) */
async function saveLab(model: string, prompt: string, src: Blob | string) {
try {
const b64 = typeof src === 'string' ? dataUrlToB64(src) : await blobToB64(src);
if (!b64) return;
const ok = await saveImgHist({ kind: 'ai-image-lab', tool: 'ai-image-tools', b64, model, prompt });
if (ok) histRef.value?.reload();
}
catch { /* 静默 */ }
}
type TabKey = 'matting' | 'upscale' | 'idphoto';
const tab = ref<TabKey>('matting');
@@ -83,7 +94,7 @@ async function doMatting() {
}
outUrl.value = URL.createObjectURL(blob);
outBlob.value = blob;
genHist.add({ title: `AI 抠图: ${curFile.value.name}`, detail: `${(blob.size / 1024).toFixed(0)}KB` });
saveLab('AI抠图', curFile.value?.name || '', blob);
}
catch (e: any) {
error.value = String(e?.message || e);
@@ -156,7 +167,7 @@ async function doUpscale() {
await new Promise<void>((r) => {
img.onload = () => r();
});
genHist.add({ title: `AI 放大 ${upScale.value}x: ${curFile.value.name}`, detail: `${img.naturalWidth}×${img.naturalHeight} · ${(blob.size / 1024).toFixed(0)}KB` });
saveLab(`AI放大${upScale.value}x`, curFile.value?.name || '', blob);
}
catch (e: any) {
error.value = String(e?.message || e);
@@ -211,7 +222,7 @@ async function makeIdPhoto() {
URL.revokeObjectURL(idResult.value);
}
idResult.value = c.toDataURL('image/png');
genHist.add({ title: `证件照: ${spec.name} ${idBg.value === 'white' ? '白底' : idBg.value === 'red' ? '红底' : '蓝底'}`, detail: `${spec.w}×${spec.h}` });
saveLab('证件照', `${spec.name} ${idBg.value === 'white' ? '白底' : idBg.value === 'red' ? '红底' : '蓝底'}`, idResult.value || '');
}
function downloadUrl(url: string, name: string) {
@@ -319,7 +330,7 @@ onMounted(() => {});
<div class="al-right">
<div class="al-sec">
{{ tab === 'idphoto' ? '证件照预览' : outUrl ? '处理结果' : '原图预览' }}
<button v-if="tab === 'idphoto' && idResult" class="al-dl" @click="downloadUrl(idResult, '证件照.png')">⬇ 下载证件照</button>
<button v-if="tab === 'idphoto' && idResult" class="al-dl" @click="saveLab('证件照', '证件照下载', idResult); downloadUrl(idResult, '证件照.png')">⬇ 下载证件照</button>
<button v-else-if="outUrl && tab !== 'idphoto'" class="al-dl" @click="downloadUrl(outUrl, tab === 'matting' ? '抠图.png' : `放大${upScale}x.${(curFile?.name || '').split('.').pop() || 'jpg'}`)">⬇ 下载结果</button>
</div>
<div class="al-preview">
@@ -328,8 +339,8 @@ onMounted(() => {});
<img v-else-if="srcUrl" :src="srcUrl" class="al-img" alt="source">
<div v-else class="al-empty">上传图片后在这里预览</div>
</div>
<GenHistory tool="ai-image-lab" label="AI 图片记录" class="mt-10px" />
</div>
<ImgHist ref="histRef" kind="ai-image-lab" />
</div>
</div>
</template>
+17 -10
View File
@@ -1,10 +1,21 @@
<script setup lang="ts">
import { useUserAuth } from '@/composable/user-auth';
import { licenseHeaders } from '../license/license';
import GenHistory from '@/tools/gen-history/GenHistory.vue';
import { useGenHistory } from '@/tools/gen-history/gen-history';
import ImgHist from '@/tools/img-hist/ImgHist.vue';
import { blobToB64, saveImgHist } from '@/tools/img-hist/img-hist';
const genHist = useGenHistory('ai-retouch');
const histRef = ref<InstanceType<typeof ImgHist> | null>(null);
/** 修图结果保存到服务器历史(失败静默,不影响下载) */
async function saveRetouch(blob: Blob) {
try {
const b64 = await blobToB64(blob);
if (!b64) return;
const ok = await saveImgHist({ kind: 'ai-retouch', tool: 'ai-retouch', b64, model: tab.value.label, prompt: fileName.value || '' });
if (ok) histRef.value?.reload();
}
catch { /* 静默 */ }
}
interface TabDef {
key: string;
@@ -211,6 +222,7 @@ async function submit() {
}
const blob = await res.blob();
resultUrl.value = URL.createObjectURL(blob);
saveRetouch(blob);
if (tab.value.key === 'inpaint') clearMask();
}
catch (e: any) {
@@ -219,12 +231,7 @@ async function submit() {
finally {
elapsed.value = Math.round(performance.now() - start);
processing.value = false;
if (resultUrl.value) {
genHist.add({
title: tab.value.label,
detail: `原图 ${imgNatural.value.w}×${imgNatural.value.h} · 耗时 ${elapsed.value}ms`,
});
}
}
}
@@ -411,6 +418,7 @@ onUnmounted(() => {
</div>
</n-spin>
</div>
<ImgHist ref="histRef" kind="ai-retouch" />
</div>
<!-- bottom bar -->
@@ -432,7 +440,6 @@ onUnmounted(() => {
</c-button>
</div>
<GenHistory tool="ai-retouch" position="right" label="修图记录" />
</div>
</template>
+7 -2
View File
@@ -1,5 +1,7 @@
<script setup lang="ts">
import { getMachineId, licenseHeaders } from '@/tools/license/license';
import ImgHist from '@/tools/img-hist/ImgHist.vue';
import { authHdr } from '@/tools/img-hist/img-hist';
// ---------- 状态 ----------
const file = ref<File | null>(null);
@@ -51,6 +53,7 @@ onMounted(async () => {
// ---------- 最近任务(localStorage 缩略图) ----------
interface SETask { id: string; time: number; prompt: string; before: string; after: string; count: number }
const tasks = ref<SETask[]>([]);
const histRef = ref<InstanceType<typeof ImgHist> | null>(null);
const LS_KEY = 'it-ai-text-edit:tasks';
function loadTasks() {
@@ -145,7 +148,7 @@ async function submit() {
}
const res = await fetch('/relay/ai/seamless-edit', {
method: 'POST',
headers: licenseHeaders('ai-text-edit'),
headers: { ...licenseHeaders('ai-text-edit'), ...authHdr() },
body: fd,
});
const j = await res.json().catch(() => ({}));
@@ -167,6 +170,7 @@ async function submit() {
tasks.value = tasks.value.slice(0, 12);
saveTasks();
}
histRef.value?.reload();
else if (!note.value) {
note.value = '未产生结果,请调整描述后重试';
}
@@ -339,6 +343,7 @@ function clearAll() {
</div>
</div>
</div>
<ImgHist ref="histRef" kind="seamless" />
</div>
</div>
</template>
@@ -349,7 +354,7 @@ function clearAll() {
.se-title { font-size: 30px; font-weight: 800; letter-spacing: 2px; }
.se-sub { margin-top: 6px; font-size: 13px; opacity: 0.6; }
.se-grid { display: grid; grid-template-columns: 380px 1fr; gap: 16px; align-items: start; }
.se-grid { display: grid; grid-template-columns: 380px 1fr 76px; gap: 16px; align-items: start; }
@media (max-width: 900px) { .se-grid { grid-template-columns: 1fr; } }
.se-ctrl { background: #fff; border: 1px solid rgba(128,128,128,0.18); border-radius: 12px; padding: 16px; display: flex; flex-direction: column; gap: 14px; box-shadow: 0 1px 4px rgba(0,0,0,0.04); }
+366
View File
@@ -0,0 +1,366 @@
<script setup lang="ts">
import { onUnmounted, ref } from 'vue';
import { useHead } from '@vueuse/head';
import { licenseHeaders } from '@/tools/license/license';
import ImgHist from '@/tools/img-hist/ImgHist.vue';
import { authHdr } from '@/tools/img-hist/img-hist';
useHead({ title: 'AI 换脸 - IT-TOOLS-PRO' });
const srcUrl = ref('');
const dstUrl = ref('');
const srcFile = ref<File | null>(null);
const dstFile = ref<File | null>(null);
const consent = ref(false);
const histRef = ref<InstanceType<typeof ImgHist> | null>(null);
const busy = ref(false);
const error = ref('');
const resultUrl = ref('');
const elapsed = ref(0);
const srcInput = ref<HTMLInputElement>();
const dstInput = ref<HTMLInputElement>();
function pick(which: 'source' | 'target') {
(which === 'source' ? srcInput : dstInput).value?.click();
}
function setFile(which: 'source' | 'target', f: File | null) {
const urlRef = which === 'source' ? srcUrl : dstUrl;
const fileRef = which === 'source' ? srcFile : dstFile;
if (urlRef.value) {
URL.revokeObjectURL(urlRef.value);
}
if (f && !f.type.startsWith('image/')) {
error.value = '请上传图片文件(JPG/PNG/WebP 等)';
return;
}
if (f && f.size > 15 * 1024 * 1024) {
error.value = '单张图片不能超过 15MB';
return;
}
fileRef.value = f;
urlRef.value = f ? URL.createObjectURL(f) : '';
}
function onInput(which: 'source' | 'target', e: Event) {
const input = e.target as HTMLInputElement;
setFile(which, input.files?.[0] ?? null);
input.value = '';
}
function onDrop(which: 'source' | 'target', e: DragEvent) {
e.preventDefault();
setFile(which, e.dataTransfer?.files?.[0] ?? null);
}
async function doSwap() {
if (!srcFile.value || !dstFile.value) {
error.value = '请先上传源人脸照片与目标照片';
return;
}
if (!consent.value) {
error.value = '请先勾选「我承诺仅使用已获本人授权的照片进行换脸」';
return;
}
busy.value = true;
error.value = '';
resultUrl.value = '';
const fd = new FormData();
fd.append('source', srcFile.value);
fd.append('target', dstFile.value);
fd.append('consent', '1');
const ctrl = new AbortController();
const timer = setTimeout(() => ctrl.abort(), 300000);
try {
const res = await fetch('/relay/ai/face-swap', {
method: 'POST',
headers: { ...licenseHeaders('face-swap'), ...authHdr() },
body: fd,
signal: ctrl.signal,
});
const j = await res.json().catch(() => ({} as any));
if (!res.ok || j.code !== 200) {
throw new Error(j.message || `HTTP ${res.status}`);
}
resultUrl.value = j.data?.url || '';
elapsed.value = Number(j.data?.elapsed_ms || 0);
if (!resultUrl.value) {
throw new Error('服务端未返回结果图片');
}
histRef.value?.reload();
}
catch (e: any) {
error.value = e?.name === 'AbortError' ? '处理超时,请稍后重试' : String(e?.message || e);
}
finally {
clearTimeout(timer);
busy.value = false;
}
}
function downloadResult() {
if (!resultUrl.value) {
return;
}
const a = document.createElement('a');
const url = new URL(resultUrl.value, location.origin);
url.searchParams.set('dl', '1');
a.href = url.toString();
a.download = 'face-swap.jpg';
a.click();
}
onUnmounted(() => {
if (srcUrl.value) {
URL.revokeObjectURL(srcUrl.value);
}
if (dstUrl.value) {
URL.revokeObjectURL(dstUrl.value);
}
});
</script>
<template>
<div class="fs-root">
<div class="fs-main">
<div class="fs-head">
<h1>🎭 AI 换脸</h1>
<span class="fs-note">insightface 人脸检测 + inswapper 本地 CPU 推理 · 照片不离开服务器</span>
</div>
<div class="fs-uploads">
<!-- 源人脸 -->
<div
class="fs-card" :class="{ has: !!srcUrl }" @click="pick('source')"
@dragover.prevent @drop="onDrop('source', $event)"
>
<input ref="srcInput" type="file" accept="image/*" hidden @change="onInput('source', $event)">
<template v-if="srcUrl">
<img :src="srcUrl" alt="源人脸">
<div class="fs-cap">① 源人脸(提供脸的人)· 点击更换</div>
</template>
<template v-else>
<div class="fs-plus">👤</div>
<div class="fs-cap">① 上传源人脸照片<br><small>清晰正脸,脸将被取用</small></div>
</template>
</div>
<div class="fs-arrow">➜</div>
<!-- 目标照片 -->
<div
class="fs-card" :class="{ has: !!dstUrl }" @click="pick('target')"
@dragover.prevent @drop="onDrop('target', $event)"
>
<input ref="dstInput" type="file" accept="image/*" hidden @change="onInput('target', $event)">
<template v-if="dstUrl">
<img :src="dstUrl" alt="目标照片">
<div class="fs-cap">② 目标照片(被换脸的人)· 点击更换</div>
</template>
<template v-else>
<div class="fs-plus">🖼️</div>
<div class="fs-cap">② 上传目标照片<br><small>人脸会被替换成源人脸</small></div>
</template>
</div>
</div>
<label class="fs-consent">
<input v-model="consent" type="checkbox">
<span>我承诺仅使用<b>已获本人授权</b>的照片进行换脸,不用于任何侵权、欺诈或违法用途</span>
</label>
<div class="fs-actions">
<button class="fs-go" :disabled="busy || !srcFile || !dstFile || !consent" @click="doSwap">
{{ busy ? '换脸中…(首次约需几秒)' : '开始换脸' }}
</button>
<span v-if="elapsed && resultUrl" class="fs-elapsed">耗时 {{ (elapsed / 1000).toFixed(1) }}s</span>
</div>
<div v-if="error" class="fs-error">⚠️ {{ error }}</div>
<div v-if="resultUrl" class="fs-result">
<img :src="resultUrl" alt="换脸结果">
<div class="fs-result-bar">
<span>换脸结果(多张人脸时自动选取最大的一张)</span>
<button class="fs-dl" @click="downloadResult">⬇ 下载图片</button>
</div>
</div>
<p class="fs-tips">
提示:两张图都需包含清晰人脸;源脸与目标脸角度、光线越接近效果越好。图片仅在服务器本地处理,不对外分享。
</p>
</div>
<ImgHist ref="histRef" kind="face-swap" />
</div>
</template>
<style scoped>
.fs-root {
display: flex;
flex-direction: row;
gap: 12px;
padding: 8px 4px;
align-items: flex-start;
}
.fs-main {
flex: 1;
min-width: 0;
display: flex;
flex-direction: column;
gap: 16px;
}
@media (max-width: 760px) {
.fs-root { flex-direction: column; }
}
.fs-head {
display: flex;
align-items: baseline;
gap: 12px;
flex-wrap: wrap;
}
.fs-head h1 {
font-size: 22px;
margin: 0;
}
.fs-note {
font-size: 12px;
opacity: 0.6;
}
.fs-uploads {
display: flex;
align-items: stretch;
gap: 14px;
flex-wrap: wrap;
}
.fs-card {
flex: 1 1 260px;
min-height: 240px;
border: 2px dashed rgba(128, 128, 128, 0.45);
border-radius: 12px;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
gap: 8px;
cursor: pointer;
padding: 12px;
transition: border-color 0.15s, background 0.15s;
background: rgba(128, 128, 128, 0.05);
}
.fs-card:hover {
border-color: rgba(128, 128, 128, 0.8);
background: rgba(128, 128, 128, 0.1);
}
.fs-card img {
max-width: 100%;
max-height: 240px;
border-radius: 8px;
object-fit: contain;
}
.fs-plus {
font-size: 42px;
opacity: 0.75;
}
.fs-cap {
font-size: 13px;
text-align: center;
line-height: 1.5;
}
.fs-cap small {
opacity: 0.55;
}
.fs-arrow {
align-self: center;
font-size: 26px;
opacity: 0.55;
}
.fs-consent {
display: flex;
align-items: flex-start;
gap: 8px;
font-size: 13px;
line-height: 1.6;
cursor: pointer;
padding: 10px 12px;
border-radius: 8px;
background: rgba(255, 170, 0, 0.08);
border: 1px solid rgba(255, 170, 0, 0.35);
}
.fs-consent input {
margin-top: 3px;
}
.fs-actions {
display: flex;
align-items: center;
gap: 14px;
}
.fs-go {
padding: 10px 28px;
font-size: 15px;
font-weight: 600;
color: #fff;
background: #3b82f6;
border: none;
border-radius: 10px;
cursor: pointer;
transition: opacity 0.15s;
}
.fs-go:hover:not(:disabled) {
opacity: 0.88;
}
.fs-go:disabled {
opacity: 0.45;
cursor: not-allowed;
}
.fs-elapsed {
font-size: 13px;
opacity: 0.65;
}
.fs-error {
font-size: 13px;
color: #e5484d;
background: rgba(229, 72, 77, 0.08);
border: 1px solid rgba(229, 72, 77, 0.35);
border-radius: 8px;
padding: 8px 12px;
}
.fs-result {
display: flex;
flex-direction: column;
gap: 8px;
}
.fs-result img {
width: 100%;
max-height: 560px;
object-fit: contain;
border-radius: 12px;
border: 1px solid rgba(128, 128, 128, 0.3);
}
.fs-result-bar {
display: flex;
justify-content: space-between;
align-items: center;
font-size: 13px;
opacity: 0.8;
flex-wrap: wrap;
gap: 8px;
}
.fs-dl {
padding: 7px 16px;
font-size: 13px;
color: #fff;
background: #10b981;
border: none;
border-radius: 8px;
cursor: pointer;
}
.fs-dl:hover {
opacity: 0.88;
}
.fs-tips {
font-size: 12px;
opacity: 0.55;
line-height: 1.7;
margin: 0;
}
</style>
+11
View File
@@ -0,0 +1,11 @@
import { FaceId } from '@vicons/tabler';
import { defineTool } from '../tool';
export const tool = defineTool({
name: 'AI 换脸',
path: '/face-swap',
description: 'AI 换脸:上传源人脸与目标照片,本地 AI 一键换脸',
keywords: ['ai', '换脸', 'face', 'swap', '人脸', '人脸替换', 'ai换脸', '头像', '表情'],
component: () => import('./face-swap.vue'),
icon: FaceId,
});
+171
View File
@@ -0,0 +1,171 @@
<script setup lang="ts">
import { onMounted, ref } from 'vue';
import { loadImgHist, type HistItem } from './img-hist';
/**
* 图片历史右栏(铁规则统一实现):
* 50×50 缩略图右侧竖排、点击查看大图、按本人隔离(登录=账号/未登录=机器码)。
* 父级把本组件放在布局最右侧即可;生成成功后调用父组件暴露的 reload()。
*/
const props = withDefaults(defineProps<{ kind: string; label?: string }>(), {
label: '历史',
});
const items = ref<HistItem[]>([]);
const viewUrl = ref('');
async function reload() {
items.value = await loadImgHist(props.kind);
}
defineExpose({ reload });
onMounted(reload);
</script>
<template>
<aside class="ih">
<div class="ih-t">
{{ label }}<em v-if="items.length">{{ items.length }}</em>
</div>
<div v-if="items.length" class="ih-list">
<img
v-for="it in items"
:key="it.id"
:src="it.img_url"
:title="it.prompt || '点击查看大图'"
class="ih-thumb"
@click="viewUrl = it.img_url"
>
</div>
<div v-else class="ih-empty">
还没有<br>生成记录
</div>
</aside>
<div v-if="viewUrl" class="ih-view" @click="viewUrl = ''">
<img :src="viewUrl" alt="历史图片">
<span class="ih-view-tip">点击任意处关闭</span>
</div>
</template>
<style scoped lang="less">
.ih {
flex: 0 0 76px;
width: 76px;
border: 1px solid rgba(128, 128, 128, 0.25);
border-radius: 12px;
background: rgba(128, 128, 128, 0.04);
display: flex;
flex-direction: column;
overflow: hidden;
align-self: flex-start;
max-height: calc(100vh - 230px);
.ih-t {
font-size: 11.5px;
font-weight: 700;
text-align: center;
padding: 9px 4px 7px;
border-bottom: 1px solid rgba(128, 128, 128, 0.18);
opacity: 0.75;
flex-shrink: 0;
em {
font-style: normal;
color: #0ea5a0;
margin-left: 4px;
}
}
.ih-list {
flex: 1;
overflow-y: auto;
overflow-x: hidden;
padding: 9px 13px 12px;
display: flex;
flex-direction: column;
align-items: center;
gap: 8px;
}
.ih-thumb {
width: 50px;
height: 50px;
object-fit: cover;
border-radius: 7px;
border: 2px solid transparent;
cursor: zoom-in;
background: #fff;
box-shadow: 0 1px 5px rgba(0, 0, 0, 0.1);
transition: all 0.15s;
display: block;
flex-shrink: 0;
&:hover {
border-color: #0ea5a0;
transform: translateY(-1px);
}
}
.ih-empty {
font-size: 11px;
text-align: center;
opacity: 0.45;
padding: 16px 4px;
line-height: 1.6;
}
}
.ih-view {
position: fixed;
inset: 0;
z-index: 9999;
background: rgba(0, 0, 0, 0.86);
display: flex;
align-items: center;
justify-content: center;
cursor: zoom-out;
img {
max-width: 92vw;
max-height: 88vh;
object-fit: contain;
border-radius: 8px;
box-shadow: 0 8px 40px rgba(0, 0, 0, 0.5);
}
.ih-view-tip {
position: absolute;
bottom: 26px;
left: 0;
right: 0;
text-align: center;
color: rgba(255, 255, 255, 0.65);
font-size: 12px;
}
}
@media (max-width: 900px) {
.ih {
flex: none;
width: 100%;
flex-direction: row;
align-items: center;
max-height: none;
.ih-t {
border-bottom: none;
border-right: 1px solid rgba(128, 128, 128, 0.18);
padding: 8px 10px;
flex-shrink: 0;
}
.ih-list {
flex-direction: row;
overflow-x: auto;
overflow-y: hidden;
padding: 8px;
}
}
}
</style>
+102
View File
@@ -0,0 +1,102 @@
import { getMachineId } from '@/tools/license/license';
/**
* 图片历史共享层(铁规则):
* - 历史右栏 50×50 缩略图竖排 + 点击查看大图(ImgHist.vue)
* - 按本人隔离:登录带 Authorization(服务端按账号归属过滤),未登录按机器码
* - 生成结果保存到服务器后台「存储设置」目录(/relay/ai/img-save → DATA_DIR/gen_images)
* 历史拉取/保存失败一律静默,不阻断生成与下载。
*/
/** 登录态 Authorization(无登录返回空对象) */
export function authHdr(): Record<string, string> {
try {
const a = JSON.parse(localStorage.getItem('it-tools-auth') ?? 'null');
if (a && typeof a.token === 'string' && a.token) {
const h: Record<string, string> = {};
h['Authorization'] = 'Bearer ' + a.token;
return h;
}
}
catch { /* ignore */ }
return {};
}
export interface HistItem {
id: string;
at: number;
model?: string;
prompt?: string;
kind?: string;
img_url: string;
w?: number;
h?: number;
}
/** 拉取本人某 kind 的图片历史(静默失败返回 []) */
export async function loadImgHist(kind: string): Promise<HistItem[]> {
try {
const url = `/relay/ai/img-history?machine=${encodeURIComponent(getMachineId())}&kind=${encodeURIComponent(kind)}`;
const res = await fetch(url, { headers: authHdr() });
const j = await res.json();
// 铁规则:所有功能历史最多显示 100 条(服务端已截断,此处兜底)
if (j.code === 200 && Array.isArray(j.data)) return j.data.slice(0, 100);
}
catch { /* 静默 */ }
return [];
}
export interface SaveImgOpts {
kind: string;
tool: string;
b64: string;
model?: string;
prompt?: string;
}
/** 保存生成结果到服务器(后台 storage_root/gen_images),静默失败返回 false */
export async function saveImgHist(o: SaveImgOpts): Promise<boolean> {
try {
const h = authHdr();
h['Content-Type'] = 'application/json';
const res = await fetch('/relay/ai/img-save', {
method: 'POST',
headers: h,
body: JSON.stringify({
machine: getMachineId(),
b64: o.b64,
kind: o.kind,
tool: o.tool,
model: o.model || '',
prompt: o.prompt || '',
}),
});
const j = await res.json().catch(() => ({}));
return j.code === 200;
}
catch { /* 静默,不阻断下载 */ }
return false;
}
/** Blob → 纯 base64(不含 data: 前缀) */
export function blobToB64(blob: Blob): Promise<string> {
return new Promise((resolve) => {
try {
const fr = new FileReader();
fr.onload = () => {
const s = String(fr.result || '');
resolve(s.includes(',') ? s.split(',', 2)[1] : s);
};
fr.onerror = () => resolve('');
fr.readAsDataURL(blob);
}
catch {
resolve('');
}
});
}
/** dataURL → 纯 base64 */
export function dataUrlToB64(u: string): string {
return u.includes(',') ? u.split(',', 2)[1] : u;
}
+3 -1
View File
@@ -96,6 +96,8 @@ import { tool as copywriting } from './copywriting';
import { tool as mcpConnect } from './mcp-connect';
import { tool as docConvert } from './doc-convert';
import { tool as aiRetouch } from './ai-retouch';
import { tool as faceSwap } from './face-swap';
import { tool as posterMaker } from './poster';
import { tool as wifiQrCodeGenerator } from './wifi-qr-code-generator';
import { tool as randomPortGenerator } from './random-port-generator';
import { tool as romanNumeralConverter } from './roman-numeral-converter';
@@ -166,7 +168,7 @@ export const toolsByCategory: ToolCategory[] = [
},
{
name: 'Images and videos',
components: [qrCodeGenerator, wifiQrCodeGenerator, batchBarcodeGenerator, codeReader, imageOcr, pdfOcr, pdfTools, imageTools, base64ImageConverter, videoTools, audioTools, sealMaker, signaturePad, textToImage, aiGen, docConvert, aiRetouch, labelDesigner, siteBookmarks, svgPlaceholderGenerator, cameraRecorder],
components: [qrCodeGenerator, wifiQrCodeGenerator, batchBarcodeGenerator, codeReader, imageOcr, pdfOcr, pdfTools, imageTools, base64ImageConverter, videoTools, audioTools, sealMaker, signaturePad, textToImage, aiGen, docConvert, aiRetouch, faceSwap, posterMaker, labelDesigner, siteBookmarks, svgPlaceholderGenerator, cameraRecorder],
},
{
name: 'Development',
+2
View File
@@ -19,6 +19,8 @@ export const PROTECTED_TOOLS: Record<string, string> = {
'/ai-image-lab': 'AI图片实验室',
'/copywriting': '文案工具箱',
'/ai-gen': 'AI 生图',
'/face-swap': 'AI换脸',
'/poster-maker': 'AI海报生成',
};
export const TRIAL_MS = 30 * 60 * 1000; // 每个功能每天免费 30 分钟
+11
View File
@@ -0,0 +1,11 @@
import { Template } from '@vicons/tabler';
import { defineTool } from '../tool';
export const tool = defineTool({
name: 'AI 海报',
path: '/poster-maker',
description: 'AI 海报生成:热门海报模板任选,改文字、换图片、AI 配图,一键导出 PNG',
keywords: ['poster', '海报', '模板', '宣传图', '朋友圈', '小红书', '电商', '海报生成', 'ai海报'],
component: () => import('./poster.vue'),
icon: Template,
});
+754
View File
@@ -0,0 +1,754 @@
<script setup lang="ts">
import { ref, computed, onMounted, onBeforeUnmount } from 'vue';
import { getMachineId, licenseHeaders } from '@/tools/license/license';
import { authHdr } from '@/tools/img-hist/img-hist';
import {
POSTER_TEMPLATES, POSTER_CATS, BG_PRESETS, POSTER_W, POSTER_H,
type PosterTemplate, type PosterBg, type PosterImageLayer,
} from './templates';
type L = any; // 图层运行时对象(text / image / shape 联合,编辑期动态增删)
const FONT_STACK = '"PingFang SC","Hiragino Sans GB","Microsoft YaHei","Noto Sans CJK SC",sans-serif';
const MINI_W = 116;
const cat = ref('hot');
const cur = ref<PosterTemplate | null>(null);
const tplId = ref('');
const layers = ref<L[]>([]);
const bg = ref<PosterBg>({});
const selId = ref('');
const scale = ref(0.5);
const stageEl = ref<HTMLElement | null>(null);
const pmRoot = ref<HTMLElement | null>(null);
const pmH = ref(0); // 视口自适应高度:根不滚动,滚动只发生在内部区域
const fileEl = ref<HTMLInputElement | null>(null);
const pmError = ref('');
const models = ref<{ id: string; name?: string }[]>([]);
const model = ref('');
const genBusy = ref(false);
const bgPrompt = ref('');
const exporting = ref(false);
// ---------- 生成历史(服务端落盘,右侧 50×50 缩略图竖排) ----------
const hist = ref<{ id: string; img_url: string; prompt?: string; kind?: string; at?: number }[]>([]);
const histBusy = ref(false);
const histView = ref(''); // 大图查看(点击缩略图打开,点空白关闭)
async function loadHist() {
histBusy.value = true;
try {
const res = await fetch(`/relay/ai/img-history?machine=${encodeURIComponent(getMachineId())}&kind=poster`, {
headers: { ...licenseHeaders('poster-maker'), ...authHdr() },
});
const j = await res.json().catch(() => ({}) as any);
// 铁规则:所有功能历史最多显示 100 条
if (res.ok && j.code === 200 && Array.isArray(j.data)) hist.value = j.data.slice(0, 100);
} catch { /* 历史拉取失败静默,不影响编辑 */ } finally { histBusy.value = false; }
}
let uid = 0;
let ro: ResizeObserver | null = null;
let scRO: ResizeObserver | null = null;
const filtered = computed(() =>
cat.value === 'hot' ? POSTER_TEMPLATES : POSTER_TEMPLATES.filter((t) => t.category === cat.value));
const sel = computed(() => layers.value.find((l) => l.id === selId.value) || null);
const selName = computed(() => {
const l = sel.value; if (!l) return '';
if (l.type === 'text') return (l.text || '文字').slice(0, 10);
if (l.type === 'image') return '图片';
return l.shape === 'ellipse' ? '圆形色块' : '矩形色块';
});
// ---------- 换模板 ----------
function selectTemplate(t: PosterTemplate) {
tplId.value = t.id;
cur.value = t;
bg.value = JSON.parse(JSON.stringify(t.bg));
layers.value = JSON.parse(JSON.stringify(t.layers)).map((l: L) => ({ ...l, id: 'l' + ++uid }));
selId.value = '';
pmError.value = '';
}
function resetTpl() {
const t = POSTER_TEMPLATES.find((x) => x.id === tplId.value);
if (t) selectTemplate(t);
}
// ---------- 文字排版(预览与导出共用,保证换行一致) ----------
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.italic ? 'italic ' : ''}${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;
}
// ---------- 样式 ----------
function bgCss(b: PosterBg): string {
if (b.color) return b.color;
if (b.stops?.length) {
const stops = b.stops.map((s) => `${s.c} ${Math.round(s.p * 100)}%`).join(', ');
return `linear-gradient(${b.angle ?? 135}deg, ${stops})`;
}
return '#ffffff';
}
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: l.align ?? 'center',
lineHeight: l.size * (l.lineHeight ?? 1.25) + 'px',
fontStyle: l.italic ? 'italic' : 'normal',
textShadow: l.shadow ? `0 ${l.shadow.y}px ${l.shadow.blur}px ${l.shadow.color}` : 'none',
};
}
function shapeStyle(l: L) {
return {
background: l.fill,
borderRadius: l.shape === 'ellipse' ? '50%' : (l.radius ?? 0) + 'px',
opacity: l.opacity ?? 1,
};
}
function miniBoxStyle(l: L) { return boxStyle(l); }
const tplLayers = (t: PosterTemplate): L[] => t.layers as any;
function onFill(e: Event) { const l = sel.value; if (l) l.fill = (e.target as HTMLInputElement).value; }
function onRot(e: Event) { const l = sel.value; if (l) l.rot = Number((e.target as HTMLInputElement).value); }
// ---------- 选中 / 拖动 ----------
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();
}
let drag: { l: L; sx: number; sy: number; lx: number; ly: number } | null = null;
function onMove(e: PointerEvent) {
if (!drag) return;
const s = scale.value || 1;
const l = drag.l;
let nx = drag.lx + (e.clientX - drag.sx) / s;
let ny = drag.ly + (e.clientY - drag.sy) / s;
const maxX = POSTER_W - l.w;
const maxY = POSTER_H - (l.type === 'text' ? l.size : l.h);
l.x = Math.min(Math.max(nx, 0), Math.max(maxX, 0));
l.y = Math.min(Math.max(ny, 0), Math.max(maxY, 0));
}
function onUp() {
drag = null;
window.removeEventListener('pointermove', onMove);
window.removeEventListener('pointerup', onUp);
}
// ---------- 图层增删 ----------
function addText() {
const l = { id: 'l' + ++uid, type: 'text', text: '点击右侧修改文字', x: 140, y: 660, w: 800, size: 80, color: '#111111', weight: 700, align: 'center', lineHeight: 1.25 };
layers.value.push(l); selId.value = l.id;
}
function addImage() {
const l = { id: 'l' + ++uid, type: 'image', x: 190, y: 500, w: 700, h: 520, radius: 24, src: '', prompt: '' };
layers.value.push(l); selId.value = l.id;
}
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);
}
function pickFile() { fileEl.value?.click(); }
function onFile(e: Event) {
const f = (e.target as HTMLInputElement).files?.[0];
const l = sel.value;
if (f && l && l.type === 'image') l.src = URL.createObjectURL(f);
(e.target as HTMLInputElement).value = '';
}
function clearImg() { const l = sel.value; if (l && l.type === 'image') l.src = ''; }
// ---------- AI 生图(复用 relay /ai/gen-image + 每日免费额度) ----------
function b64DataUrl(b64: string) {
let mime = 'image/png';
if (b64.startsWith('/9j/')) mime = 'image/jpeg';
else if (b64.startsWith('UklGR')) mime = 'image/webp';
return `data:${mime};base64,${b64}`;
}
async function genFor(l: PosterImageLayer) {
const prompt = String(l.prompt ?? '').trim();
if (!prompt) { pmError.value = '请先填写图片描述'; return; }
genBusy.value = true; pmError.value = '';
try {
// 上游生图模型只接受固定尺寸档位(如 dall-e-3 仅 1024²/1792×1024/1024×1792),
// 按图框宽高比映射到三档,出图后由 CSS object-fit:cover 裁切填充
const ar = l.w / Math.max(1, l.h);
let width = 1024, height = 1024;
if (ar > 1.25) { width = 1792; height = 1024; }
else if (ar < 0.8) { width = 1024; height = 1792; }
const res = await fetch('/relay/ai/gen-image', {
method: 'POST',
headers: { 'Content-Type': 'application/json', ...licenseHeaders('poster-maker'), ...authHdr() },
body: JSON.stringify({ machine: getMachineId(), prompt, model: model.value, width, height, kind: 'poster' }),
});
const j = await res.json().catch(() => ({}) as any);
if (!res.ok || j.code !== 200) throw new Error(j.message || `HTTP ${res.status}`);
const url = j.data?.img_url || (j.data?.b64 ? b64DataUrl(j.data.b64) : '') || j.data?.url || '';
if (!url) throw new Error('未返回图片');
l.src = url;
loadHist(); // 服务端已落盘,刷新右侧历史
} catch (err: any) {
pmError.value = 'AI 生成失败:' + (err?.message || String(err));
} finally {
genBusy.value = false;
}
}
async function genBg() {
const l = {
id: 'l' + ++uid, type: 'image', x: 0, y: 0, w: POSTER_W, h: POSTER_H, radius: 0,
src: '', prompt: bgPrompt.value.trim() || '高级感海报背景图,留白构图,杂志风',
};
layers.value.unshift(l);
selId.value = '';
await genFor(l);
if (!l.src) layers.value = layers.value.filter((x) => x !== l);
}
// ---------- 缩放 ----------
// 宽高双向适配:画布始终完整落在舞台内,舞台自身不出滚动条
function fit() {
measure(); // 舞台尺寸一变就顺带复测根高度(仅值变化才写,稳定后自收敛)
const el = stageEl.value;
const w = Math.max((el?.clientWidth || 600) - 20, 120);
const h = Math.max((el?.clientHeight || 760) - 20, 160);
scale.value = Math.min(Math.max(Math.min(w / POSTER_W, h / POSTER_H), 0.1), 0.85);
}
// 测量所在滚动容器:根高度 = 容器可视高 - 上方占用,页面级永不出现滚动条
function measure() {
const el = pmRoot.value;
if (!el) return;
// 必须取最内层滚动容器:外层是套壳,高度口径不同,用外层算出来的值会错
const sc = el.closest('.n-layout-scroll-container') as HTMLElement | null;
if (!sc) return;
const above = el.getBoundingClientRect().top - sc.getBoundingClientRect().top + sc.scrollTop;
const h = Math.floor(sc.clientHeight - above - 18);
if (h >= 160 && h !== pmH.value) pmH.value = h;
}
// ---------- 导出 PNG ----------
function rrPath(ctx: CanvasRenderingContext2D, x: number, y: number, w: number, h: number, r: number) {
r = Math.min(r, w / 2, h / 2);
ctx.beginPath();
ctx.moveTo(x + r, y);
ctx.lineTo(x + w - r, y);
ctx.quadraticCurveTo(x + w, y, x + w, y + r);
ctx.lineTo(x + w, y + h - r);
ctx.quadraticCurveTo(x + w, y + h, x + w - r, y + h);
ctx.lineTo(x + r, y + h);
ctx.quadraticCurveTo(x, y + h, x, y + h - r);
ctx.lineTo(x, y + r);
ctx.quadraticCurveTo(x, y, x + r, y);
ctx.closePath();
}
function drawBg(ctx: CanvasRenderingContext2D, b: PosterBg) {
if (b.color) { ctx.fillStyle = b.color; ctx.fillRect(0, 0, POSTER_W, POSTER_H); return; }
if (!b.stops?.length) { ctx.fillStyle = '#fff'; ctx.fillRect(0, 0, POSTER_W, POSTER_H); return; }
const a = (b.angle ?? 135) * Math.PI / 180;
const len = Math.abs(POSTER_W * Math.sin(a)) + Math.abs(POSTER_H * Math.cos(a));
const cx = POSTER_W / 2, cy = POSTER_H / 2;
const dx = Math.sin(a), dy = -Math.cos(a);
const g = ctx.createLinearGradient(cx - dx * len / 2, cy - dy * len / 2, cx + dx * len / 2, cy + dy * len / 2);
for (const s of b.stops) g.addColorStop(Math.min(Math.max(s.p, 0), 1), s.c);
ctx.fillStyle = g;
ctx.fillRect(0, 0, POSTER_W, POSTER_H);
}
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;
});
}
// 绕 (cx, cy) 旋转画布坐标系:预览走 CSS transform、导出走 canvas,中心一致才不跑位
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 === 'shape') {
ctx.save();
if (l.rot) rotAround(ctx, l.x + l.w / 2, l.y + l.h / 2, l.rot);
ctx.globalAlpha = l.opacity ?? 1;
ctx.fillStyle = l.fill;
if (l.shape === 'ellipse') {
ctx.beginPath();
ctx.ellipse(l.x + l.w / 2, l.y + l.h / 2, l.w / 2, l.h / 2, 0, 0, Math.PI * 2);
ctx.fill();
} else {
rrPath(ctx, l.x, l.y, l.w, l.h, l.radius ?? 0);
ctx.fill();
}
ctx.restore();
return;
}
if (l.type === 'image') {
ctx.save();
if (l.rot) rotAround(ctx, l.x + l.w / 2, l.y + l.h / 2, l.rot);
rrPath(ctx, l.x, l.y, l.w, l.h, l.radius ?? 0);
ctx.clip();
const img = l.src ? await loadImg(l.src) : null;
if (img && img.naturalWidth) {
const s = Math.max(l.w / img.naturalWidth, l.h / img.naturalHeight);
const dw = img.naturalWidth * s, dh = img.naturalHeight * s;
ctx.drawImage(img, l.x + (l.w - dw) / 2, l.y + (l.h - dh) / 2, dw, dh);
} else {
ctx.fillStyle = '#ececec';
ctx.fillRect(l.x, l.y, l.w, l.h);
ctx.fillStyle = '#999999';
ctx.font = `400 ${Math.max(24, Math.round(l.h * 0.06))}px ${FONT_STACK}`;
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.fillText('图片位', l.x + l.w / 2, l.y + l.h / 2);
ctx.textBaseline = 'alphabetic';
}
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 = l.align === 'center' ? 'center' : l.align === 'right' ? 'right' : 'left';
const tx = l.align === 'center' ? l.x + l.w / 2 : l.align === 'right' ? l.x + l.w : l.x;
for (let i = 0; i < lines.length; i++) {
const y = l.y + i * lh + (lh - (asc + desc)) / 2 + asc;
if (l.shadow) {
ctx.shadowColor = l.shadow.color; ctx.shadowBlur = l.shadow.blur; ctx.shadowOffsetY = l.shadow.y;
} else {
ctx.shadowColor = 'transparent'; ctx.shadowBlur = 0; ctx.shadowOffsetY = 0;
}
ctx.fillText(lines[i], tx, y);
}
ctx.restore();
}
async function exportPng() {
exporting.value = true; pmError.value = '';
try {
const c = document.createElement('canvas');
c.width = POSTER_W; c.height = POSTER_H;
const ctx = c.getContext('2d')!;
drawBg(ctx, bg.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 = `${cur.value?.name || '海报'}.png`;
a.click();
setTimeout(() => URL.revokeObjectURL(a.href), 8000);
// 同步保存到服务器后台存储目录(后台「存储设置」的 gen_images),失败不阻断下载
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);
});
await fetch('/relay/ai/img-save', {
method: 'POST',
headers: { 'Content-Type': 'application/json', ...licenseHeaders('poster-maker'), ...authHdr() },
body: JSON.stringify({ machine: getMachineId(), b64, kind: 'poster', model: 'AI海报', prompt: cur.value?.name || '海报导出' }),
});
loadHist();
} catch { /* 保存失败不影响本地下载 */ }
} catch (err: any) {
pmError.value = '导出失败:' + (err?.message || String(err));
} finally {
exporting.value = false;
}
}
onMounted(async () => {
selectTemplate(POSTER_TEMPLATES[0]);
loadHist();
measure();
fit();
ro = new ResizeObserver(fit);
if (stageEl.value) ro.observe(stageEl.value);
const sc = pmRoot.value?.closest('.n-layout-scroll-container');
if (sc) { scRO = new ResizeObserver(measure); scRO.observe(sc); }
window.addEventListener('resize', measure);
window.addEventListener('focus', measure);
document.addEventListener('visibilitychange', measure);
// 头部字体/公告条加载完高度会微变,延迟复测两次
setTimeout(measure, 400);
setTimeout(measure, 1500);
try {
const res = await fetch('/relay/ai/image-models', { headers: licenseHeaders('poster-maker') });
const j = await res.json().catch(() => ({}) as any);
if (res.ok && j.code === 200 && Array.isArray(j.data)) {
models.value = j.data;
model.value = j.data[0]?.id ?? '';
}
} catch { /* 模型列表拉取失败时用默认空值 */ }
});
onBeforeUnmount(() => {
ro?.disconnect();
scRO?.disconnect();
window.removeEventListener('resize', measure);
window.removeEventListener('focus', measure);
document.removeEventListener('visibilitychange', measure);
onUp();
});
</script>
<template>
<div ref="pmRoot" class="pm-root" :style="pmH ? { height: pmH + 'px' } : undefined">
<div class="pm-top">
<div class="pm-cats">
<button
v-for="c in POSTER_CATS" :key="c.id"
class="pm-cat" :class="{ on: cat === c.id }"
@click="cat = c.id"
>{{ c.name }}</button>
</div>
<div class="pm-actions">
<button class="pm-btn" @click="addText">+ 文字</button>
<button class="pm-btn" @click="addImage">+ 图片框</button>
<button class="pm-btn" @click="resetTpl">重置模板</button>
<button class="pm-btn primary" :disabled="exporting" @click="exportPng">
{{ exporting ? '导出中…' : '⬇ 下载 PNG' }}
</button>
</div>
</div>
<div v-if="pmError" class="pm-error">{{ pmError }}</div>
<div class="pm-main">
<!-- 左:模板库 -->
<aside class="pm-tpls">
<div class="pm-sec-title">海报模板({{ filtered.length }})</div>
<div class="pm-tpl-grid">
<div
v-for="t in filtered" :key="t.id"
class="pm-tpl-card" :class="{ on: tplId === t.id }"
@click="selectTemplate(t)"
>
<div class="pm-mini" :style="{ width: MINI_W + 'px', height: Math.round(MINI_W * POSTER_H / POSTER_W) + 'px' }">
<div
class="pm-mini-in"
:style="{ width: POSTER_W + 'px', height: POSTER_H + 'px', transform: `scale(${MINI_W / POSTER_W})`, background: bgCss(t.bg) }"
>
<template v-for="(l, i) in tplLayers(t)" :key="i">
<div v-if="l.type === 'shape'" class="pm-layer" :style="miniBoxStyle(l)">
<div class="pm-shape" :style="shapeStyle(l)"></div>
</div>
<div v-else-if="l.type === 'image'" class="pm-layer" :style="miniBoxStyle(l)">
<img v-if="l.src" :src="l.src" class="pm-img" draggable="false" />
<div v-else class="pm-img pm-ph">📷</div>
</div>
<div v-else class="pm-layer" :style="miniBoxStyle(l)">
<div :style="fontStyle(l)"><div v-for="(ln, li) in linesOf(l)" :key="li">{{ ln || '\u00a0' }}</div></div>
</div>
</template>
</div>
</div>
<div class="pm-tpl-name">{{ t.name }}</div>
</div>
</div>
</aside>
<!-- 中:画布 -->
<section class="pm-stage" ref="stageEl" @click.self="selId = ''">
<div
class="pm-frame"
:style="{ width: POSTER_W * scale + 'px', height: POSTER_H * scale + 'px' }"
>
<div
class="pm-canvas"
:style="{ width: POSTER_W + 'px', height: POSTER_H + 'px', transform: `scale(${scale})`, background: bgCss(bg) }"
@click.self="selId = ''"
>
<div
v-for="l in layers" :key="l.id"
class="pm-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>
<template v-else-if="l.type === 'image'">
<img v-if="l.src" :src="l.src" class="pm-img" draggable="false" />
<div v-else class="pm-img pm-ph">📷 点击右侧替换图片</div>
</template>
<div v-else class="pm-shape" :style="shapeStyle(l)"></div>
</div>
</div>
</div>
</section>
<!-- 右:编辑面板 -->
<aside class="pm-panel">
<div class="pm-sec">
<div class="pm-sec-title">背景</div>
<div class="pm-bgs">
<button
v-for="p in BG_PRESETS" :key="p.name"
class="pm-bg-sw" :style="{ background: bgCss(p.bg) }"
:title="p.name"
@click="bg = JSON.parse(JSON.stringify(p.bg))"
></button>
</div>
<div class="pm-row">
<input v-model="bgPrompt" class="pm-input" placeholder="AI 背景描述,如:蓝色科技感海报背景" />
</div>
<button class="pm-btn wide" :disabled="genBusy" @click="genBg">
{{ genBusy ? '生成中…' : '✨ AI 生成背景' }}
</button>
</div>
<div class="pm-sec">
<div class="pm-sec-title">图层(上层在前)</div>
<div class="pm-layers">
<div
v-for="l in [...layers].reverse()" :key="l.id"
class="pm-li" :class="{ on: selId === l.id }"
@click="selId = l.id"
>
<span class="pm-li-ico">{{ l.type === 'text' ? 'T' : l.type === 'image' ? '🖼' : '■' }}</span>
<span class="pm-li-name">{{ l.type === 'text' ? (l.text || '文字').slice(0, 10) : l.type === 'image' ? '图片' : (l.shape === 'ellipse' ? '圆形色块' : '矩形色块') }}</span>
<span class="pm-li-ops" @click.stop>
<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>
</div>
<div v-if="sel" class="pm-sec">
<div class="pm-sec-title">编辑「{{ selName }}」</div>
<div class="pm-row">
<label>旋转</label>
<input :value="sel.rot ?? 0" type="range" min="-180" max="180" step="1" @input="onRot" />
<span>{{ sel.rot ?? 0 }}°</span>
<button class="pm-mini-btn" @click="sel.rot = 0">复位</button>
</div>
<template v-if="sel.type === 'text'">
<textarea v-model="sel.text" class="pm-input ta" rows="3" placeholder="文字内容,支持换行"></textarea>
<div class="pm-row">
<label>字号</label>
<input v-model.number="sel.size" type="range" min="20" max="240" />
<span>{{ sel.size }}</span>
</div>
<div class="pm-row">
<label>颜色</label>
<input v-model="sel.color" type="color" class="pm-color" />
<label class="chk"><input v-model="sel.italic" type="checkbox" /> 斜体</label>
</div>
<div class="pm-row">
<label>粗细</label>
<select v-model.number="sel.weight" class="pm-sel">
<option :value="400">常规</option>
<option :value="700">加粗</option>
<option :value="900">特粗</option>
</select>
<label>行高</label>
<input v-model.number="sel.lineHeight" type="range" min="1" max="2" step="0.05" />
</div>
<div class="pm-row">
<label>对齐</label>
<button class="pm-mini-btn" :class="{ on: sel.align === 'left' }" @click="sel.align = 'left'">左</button>
<button class="pm-mini-btn" :class="{ on: sel.align === 'center' }" @click="sel.align = 'center'">中</button>
<button class="pm-mini-btn" :class="{ on: sel.align === 'right' }" @click="sel.align = 'right'">右</button>
</div>
</template>
<template v-else-if="sel.type === 'image'">
<textarea v-model="sel.prompt" class="pm-input ta" rows="3" placeholder="AI 生成的图片描述"></textarea>
<div class="pm-row" v-if="models.length">
<label>模型</label>
<select v-model="model" class="pm-sel">
<option v-for="m in models" :key="m.id" :value="m.id">{{ m.name || m.id }}</option>
</select>
</div>
<button class="pm-btn wide" :disabled="genBusy" @click="genFor(sel)">
{{ genBusy ? '生成中…(约 10-30 秒)' : '✨ AI 生成图片' }}
</button>
<div class="pm-row gap">
<button class="pm-btn" @click="pickFile">📁 上传图片</button>
<button class="pm-btn" :disabled="!sel.src" @click="clearImg">清除图片</button>
</div>
<div class="pm-row">
<label>圆角</label>
<input v-model.number="sel.radius" type="range" min="0" max="360" />
</div>
<input ref="fileEl" type="file" accept="image/*" class="pm-hidden" @change="onFile" />
</template>
<template v-else>
<div class="pm-row">
<label>颜色</label>
<input :value="sel.fill" type="color" class="pm-color" @input="onFill" />
<label class="chk"><input v-model.number="sel.opacity" type="range" min="0.1" max="1" step="0.05" /> 透明</label>
</div>
<div class="pm-row" v-if="sel.shape === 'rect'">
<label>圆角</label>
<input v-model.number="sel.radius" type="range" min="0" :max="Math.min(sel.w, sel.h) / 2" />
</div>
</template>
</div>
<div v-else class="pm-tip">点击画布中的元素进行编辑,拖动可移动位置;右侧图层可排序、删除。</div>
</aside>
<!-- 最右:生成历史(50×50 缩略图竖排,点击查看大图) -->
<aside class="pm-hist">
<div class="pm-hist-t">历史<em v-if="hist.length">{{ hist.length }}</em></div>
<div v-if="hist.length" class="pm-hist-list">
<img
v-for="it in hist" :key="it.id"
class="pm-hist-thumb"
:src="it.img_url"
:title="it.prompt || '点击查看大图'"
@click="histView = it.img_url"
/>
</div>
<div v-else class="pm-hist-empty">还没有<br />生成记录</div>
</aside>
</div>
<!-- 大图查看 -->
<div v-if="histView" class="pm-hist-view" @click="histView = ''">
<img :src="histView" alt="生成图片大图" />
</div>
</div>
</template>
<style scoped>
.pm-root { display: flex; flex-direction: column; gap: 10px; padding: 12px; box-sizing: border-box; height: 100%; overflow: hidden; }
.pm-top { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; justify-content: space-between; flex-shrink: 0; }
.pm-cats { display: flex; flex-wrap: wrap; gap: 6px; }
.pm-cat { padding: 5px 12px; border-radius: 14px; border: 1px solid var(--n-border-color, #d9d9d9); background: transparent; color: inherit; cursor: pointer; font-size: 13px; }
.pm-cat.on { background: #3b82f6; border-color: #3b82f6; color: #fff; }
.pm-actions { display: flex; gap: 6px; flex-wrap: wrap; }
.pm-btn { padding: 6px 12px; border-radius: 8px; border: 1px solid var(--n-border-color, #d9d9d9); background: var(--n-action-color, #fff); color: inherit; cursor: pointer; font-size: 13px; }
.pm-btn:hover { border-color: #3b82f6; color: #3b82f6; }
.pm-btn.primary { background: #3b82f6; border-color: #3b82f6; color: #fff; }
.pm-btn.primary:hover { background: #2563eb; color: #fff; }
.pm-btn.wide { width: 100%; margin-top: 6px; }
.pm-btn:disabled { opacity: .55; cursor: not-allowed; }
.pm-error { flex-shrink: 0; padding: 8px 12px; border-radius: 8px; background: #fef2f2; border: 1px solid #fecaca; color: #dc2626; font-size: 13px; }
.pm-main { display: flex; gap: 12px; align-items: stretch; flex: 1; min-height: 0; }
/* 模板库 */
.pm-tpls { width: 292px; flex-shrink: 0; min-height: 0; overflow-y: auto; overflow-x: hidden; }
.pm-sec-title { font-size: 13px; font-weight: 700; opacity: .75; margin-bottom: 8px; }
.pm-tpl-grid { display: grid; grid-template-columns: repeat(2, 1fr); gap: 10px; }
.pm-tpl-card { border: 2px solid transparent; border-radius: 10px; padding: 6px; cursor: pointer; background: rgba(127,127,127,.07); }
.pm-tpl-card:hover { border-color: rgba(59,130,246,.4); }
.pm-tpl-card.on { border-color: #3b82f6; background: rgba(59,130,246,.10); }
.pm-mini { position: relative; overflow: hidden; border-radius: 6px; margin: 0 auto; }
.pm-mini-in { position: relative; transform-origin: 0 0; }
.pm-tpl-name { font-size: 12px; text-align: center; margin-top: 4px; }
/* 画布 */
.pm-stage { flex: 1; min-width: 0; min-height: 0; display: flex; justify-content: center; overflow: auto; padding-bottom: 8px; }
.pm-frame { position: relative; flex-shrink: 0; box-shadow: 0 6px 24px rgba(0,0,0,.18); border-radius: 4px; overflow: hidden; }
.pm-canvas { position: absolute; left: 0; top: 0; transform-origin: 0 0; overflow: hidden; }
.pm-layer { position: absolute; box-sizing: border-box; user-select: none; -webkit-user-select: none; touch-action: none; }
.pm-layer.sel { outline: 3px dashed #3b82f6; outline-offset: 2px; }
.pm-img { width: 100%; height: 100%; object-fit: cover; display: block; pointer-events: none; }
.pm-ph { display: flex; align-items: center; justify-content: center; background: rgba(127,127,127,.14); border: 2px dashed rgba(127,127,127,.5); color: rgba(127,127,127,.9); font-size: 26px; text-align: center; box-sizing: border-box; }
.pm-shape { width: 100%; height: 100%; pointer-events: none; }
.pm-mini .pm-ph { font-size: 40px; }
/* 面板 */
.pm-panel { width: 316px; flex-shrink: 0; min-height: 0; overflow-y: auto; display: flex; flex-direction: column; gap: 14px; }
/* 生成历史(右栏 76px,50×50 缩略图竖排) */
.pm-hist { width: 76px; flex-shrink: 0; min-height: 0; display: flex; flex-direction: column; gap: 6px; }
.pm-hist-t { font-size: 12px; font-weight: 700; opacity: .75; text-align: center; }
.pm-hist-t em { font-style: normal; color: #3b82f6; margin-left: 3px; }
.pm-hist-list { flex: 1; min-height: 0; overflow-y: auto; display: flex; flex-direction: column; align-items: center; gap: 6px; padding-bottom: 8px; }
.pm-hist-thumb { width: 50px; height: 50px; object-fit: cover; border-radius: 8px; cursor: zoom-in; border: 2px solid transparent; background: rgba(127,127,127,.12); flex-shrink: 0; transition: border-color .15s; }
.pm-hist-thumb:hover { border-color: #3b82f6; }
.pm-hist-empty { font-size: 11px; opacity: .55; text-align: center; line-height: 1.6; padding-top: 10px; }
.pm-hist-view { position: fixed; inset: 0; z-index: 9999; background: rgba(0,0,0,.78); display: flex; align-items: center; justify-content: center; cursor: zoom-out; padding: 24px; }
.pm-hist-view img { max-width: 92vw; max-height: 92vh; object-fit: contain; border-radius: 8px; background: #fff; box-shadow: 0 10px 40px rgba(0,0,0,.4); }
.pm-sec { padding: 10px 12px; border: 1px solid var(--n-border-color, #e5e5e5); border-radius: 10px; background: rgba(127,127,127,.04); }
.pm-bgs { display: grid; grid-template-columns: repeat(8, 1fr); gap: 6px; }
.pm-bg-sw { height: 26px; border-radius: 6px; border: 1px solid rgba(127,127,127,.35); cursor: pointer; }
.pm-row { display: flex; align-items: center; gap: 8px; margin-top: 8px; font-size: 13px; flex-wrap: wrap; }
.pm-row.gap { gap: 10px; }
.pm-row label { opacity: .8; white-space: nowrap; }
.pm-input { width: 100%; box-sizing: border-box; margin-top: 8px; padding: 6px 8px; border-radius: 6px; border: 1px solid var(--n-border-color, #d9d9d9); background: var(--n-action-color, #fff); color: inherit; font-size: 13px; }
.pm-input.ta { resize: vertical; font-family: inherit; }
.pm-input:focus { outline: none; border-color: #3b82f6; }
.pm-color { width: 44px; height: 28px; padding: 0; border: 1px solid rgba(127,127,127,.35); border-radius: 6px; background: transparent; cursor: pointer; }
.pm-sel { padding: 4px 6px; border-radius: 6px; border: 1px solid var(--n-border-color, #d9d9d9); background: var(--n-action-color, #fff); color: inherit; font-size: 13px; }
.pm-mini-btn { padding: 3px 10px; border-radius: 6px; border: 1px solid var(--n-border-color, #d9d9d9); background: transparent; color: inherit; cursor: pointer; font-size: 13px; }
.pm-mini-btn.on { background: #3b82f6; border-color: #3b82f6; color: #fff; }
.chk { display: inline-flex; align-items: center; gap: 4px; }
.pm-layers { display: flex; flex-direction: column; gap: 4px; max-height: 190px; overflow: auto; }
.pm-li { display: flex; align-items: center; gap: 6px; padding: 5px 8px; border-radius: 6px; border: 1px solid transparent; cursor: pointer; font-size: 13px; background: rgba(127,127,127,.06); }
.pm-li.on { border-color: #3b82f6; background: rgba(59,130,246,.12); }
.pm-li-name { flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.pm-li-ops { display: inline-flex; gap: 2px; }
.pm-li-ops button { border: none; background: transparent; cursor: pointer; color: inherit; padding: 2px 4px; font-size: 12px; border-radius: 4px; }
.pm-li-ops button:hover { background: rgba(127,127,127,.2); }
.pm-tip { font-size: 13px; opacity: .65; line-height: 1.7; padding: 8px 4px; }
.pm-hidden { display: none; }
@media (max-width: 1180px) {
.pm-main { flex-direction: column; overflow-y: auto; }
.pm-tpls, .pm-panel { width: 100%; max-height: none; overflow: visible; }
.pm-stage { flex: none; height: 56vh; }
.pm-tpl-grid { grid-template-columns: repeat(4, 1fr); }
/* 窄屏:历史栏改为横排(缩略图仍 50×50) */
.pm-hist { width: 100%; flex-direction: row; align-items: center; gap: 8px; }
.pm-hist-t { flex-shrink: 0; }
.pm-hist-list { flex-direction: row; overflow-x: auto; overflow-y: hidden; padding-bottom: 0; }
}
</style>
+457
View File
@@ -0,0 +1,457 @@
// AI 海报模板库 —— 设计尺寸 1080×1440(3:4 通用朋友圈/小红书/电商比例)
// 模板 = 背景(纯色/线性渐变) + 图层列表(文字/图片/色块),加载后进入画布编辑:
// 支持改文字(内容/字号/颜色/粗细/对齐)、换图片(上传/AI生成)、拖动移动、增删图层、导出 PNG。
export interface PosterTextShadow { color: string; blur: number; y: number }
export interface PosterTextLayer {
type: 'text';
text: string;
x: number; y: number; w: number;
size: number;
color: string;
weight?: number;
align?: 'left' | 'center' | 'right';
lineHeight?: number; // 倍数,默认 1.25
italic?: boolean;
shadow?: PosterTextShadow;
rot?: number; // 旋转角度(度,绕图层中心,可为负)
}
export interface PosterImageLayer {
type: 'image';
x: number; y: number; w: number; h: number;
radius?: number;
rot?: number; // 旋转角度(度)
src?: string; // 当前图片(上传或 AI 生成后写入)
prompt?: string; // AI 生成默认提示词
}
export interface PosterShapeLayer {
type: 'shape';
shape: 'rect' | 'ellipse';
x: number; y: number; w: number; h: number;
fill: string;
radius?: number;
opacity?: number;
rot?: number; // 旋转角度(度)
}
export type PosterLayer = PosterTextLayer | PosterImageLayer | PosterShapeLayer;
export interface PosterBg {
color?: string;
angle?: number;
stops?: { c: string; p: number }[];
}
export interface PosterTemplate {
id: string;
name: string;
category: string;
w: number;
h: number;
bg: PosterBg;
layers: PosterLayer[];
}
export const POSTER_W = 1080;
export const POSTER_H = 1440;
export const POSTER_CATS = [
{ id: 'hot', name: '热门' },
{ id: 'promo', name: '促销' },
{ id: 'festival', name: '节日' },
{ id: 'event', name: '活动' },
{ id: 'food', name: '美食' },
{ id: 'edu', name: '教育' },
{ id: 'school', name: '校园' },
{ id: 'sport', name: '健身' },
{ id: 'recruit', name: '招聘' },
{ id: 'birthday', name: '生日' },
{ id: 'redbook', name: '封面' },
];
const tx = (text: string, x: number, y: number, w: number, size: number, color: string,
o: Partial<PosterTextLayer> = {}): PosterTextLayer =>
({ type: 'text', text, x, y, w, size, color, weight: 700, align: 'center', lineHeight: 1.25, ...o });
const im = (x: number, y: number, w: number, h: number, prompt = '', o: Partial<PosterImageLayer> = {}): PosterImageLayer =>
({ type: 'image', x, y, w, h, radius: 24, prompt, ...o });
const sh = (shape: 'rect' | 'ellipse', x: number, y: number, w: number, h: number, fill: string,
o: Partial<PosterShapeLayer> = {}): PosterShapeLayer =>
({ type: 'shape', shape, x, y, w, h, fill, ...o });
const solid = (color: string): PosterBg => ({ color });
const grad = (angle: number, c1: string, c2: string): PosterBg =>
({ angle, stops: [{ c: c1, p: 0 }, { c: c2, p: 1 }] });
const mk = (id: string, name: string, category: string, bg: PosterBg, layers: PosterLayer[]): PosterTemplate =>
({ id, name, category, w: POSTER_W, h: POSTER_H, bg, layers });
export const POSTER_TEMPLATES: PosterTemplate[] = [
// ---------------- 促销 ----------------
mk('shuang11', '双11狂购节', 'promo', grad(135, '#ff2d55', '#ff9500'), [
sh('ellipse', 640, 60, 420, 420, 'rgba(255,255,255,0.13)'),
sh('ellipse', -60, 240, 300, 300, 'rgba(255,255,255,0.10)'),
tx('双11狂购节', 50, 380, 980, 140, '#ffffff', { weight: 900 }),
tx('全场5折起 · 满300减50', 50, 570, 980, 56, '#ffe082'),
sh('rect', 340, 668, 400, 96, '#ffd60a', { radius: 48 }),
tx('限时抢购 手慢无', 340, 686, 400, 44, '#c62828'),
im(90, 830, 900, 430, '双11电商促销商品堆头,礼盒购物袋红色节日氛围,电商海报', { radius: 28 }),
tx('活动时间:11月1日 - 11月11日', 50, 1300, 980, 40, '#ffffff', { weight: 400 }),
]),
mk('d618', '618年中大促', 'promo', grad(120, '#0052ff', '#00c6ff'), [
tx('618年中大促', 50, 290, 980, 150, '#ffffff', { weight: 900 }),
tx('跨店每满300减50', 50, 490, 980, 60, '#ffd60a', { weight: 900 }),
im(140, 640, 800, 560, '618蓝色科技感电商商品展示,礼盒光效,促销banner', { radius: 32 }),
sh('rect', 340, 1258, 400, 92, '#ffd60a', { radius: 46 }),
tx('立即抢购', 340, 1274, 400, 44, '#0052ff'),
]),
mk('qingcang', '清仓大甩卖', 'promo', solid('#ffd60a'), [
tx('清仓大甩卖', 50, 230, 980, 170, '#d32f2f', { weight: 900 }),
tx('全场1折起', 50, 450, 980, 110, '#111111', { weight: 900 }),
tx('数量有限 售完即止', 50, 610, 980, 48, '#333333'),
im(120, 740, 840, 460, '工厂清仓甩卖商品堆头,衣服鞋帽纸箱,黄色促销海报', { radius: 24 }),
sh('ellipse', 380, 1250, 320, 170, '#d32f2f'),
tx('速抢', 380, 1298, 320, 56, '#ffffff', { weight: 900 }),
]),
mk('kaixin', '新店开业', 'promo', grad(135, '#e53935', '#ff7043'), [
sh('ellipse', -100, -80, 420, 420, 'rgba(255,255,255,0.12)'),
tx('新店开业', 50, 320, 980, 165, '#ffffff', { weight: 900 }),
tx('全场8折 · 进店有礼', 50, 540, 980, 60, '#ffe082'),
im(120, 700, 840, 480, '新店铺开业花篮与门头,喜庆红色氛围,开业典礼照片', { radius: 24 }),
tx('地址:XX路88号 · 电话:138-0000-0000', 50, 1270, 980, 42, '#ffffff', { weight: 400 }),
]),
// ---------------- 节日 ----------------
mk('chunjie', '新春快乐', 'festival', grad(135, '#c62828', '#ff8f00'), [
sh('ellipse', 390, 130, 300, 300, 'rgba(255,213,79,0.92)'),
tx('2026', 390, 226, 300, 72, '#c62828', { weight: 900 }),
tx('新春快乐', 50, 520, 980, 190, '#ffd54f', { weight: 900, shadow: { color: 'rgba(120,0,0,0.45)', blur: 24, y: 8 } }),
tx('万事如意 · 阖家幸福 · 财源广进', 50, 770, 980, 52, '#ffffff', { weight: 700 }),
im(140, 900, 800, 400, '中国春节红灯笼与梅花,喜庆新年氛围摄影', { radius: 24 }),
tx('恭祝全市人民 新年大吉', 50, 1350, 980, 46, '#ffe0b2', { weight: 400 }),
]),
mk('zhongqiu', '中秋团圆', 'festival', grad(160, '#1a237e', '#6a1b9a'), [
tx('中秋佳节', 50, 250, 980, 175, '#ffd54f', { weight: 900 }),
tx('月圆人团圆', 50, 455, 980, 70, '#ffffff'),
im(190, 620, 700, 700, '满月夜空,金色月亮特写,中秋节深蓝色氛围', { radius: 350 }),
tx('但愿人长久 千里共婵娟', 50, 1372, 980, 44, '#c5cae9', { weight: 400 }),
]),
mk('shengdan', '圣诞快乐', 'festival', solid('#2e7d32'), [
tx('圣诞快乐', 50, 230, 980, 175, '#ff5252', { weight: 900, shadow: { color: 'rgba(0,0,0,0.35)', blur: 18, y: 6 } }),
tx('Merry Christmas', 50, 440, 980, 54, '#ffffff', { weight: 400, italic: true }),
im(140, 570, 800, 550, '圣诞树彩灯装饰,温暖圣诞夜氛围', { radius: 24 }),
sh('rect', 330, 1185, 420, 100, '#ff5252', { radius: 50 }),
tx('圣诞好礼8折', 330, 1207, 420, 44, '#ffffff'),
tx('12月24日 - 12月26日', 50, 1340, 980, 40, '#c8e6c9', { weight: 400 }),
]),
mk('yuandan', '元旦快乐', 'festival', grad(135, '#0d47a1', '#00acc1'), [
tx('元旦快乐', 50, 300, 980, 165, '#ffffff', { weight: 900 }),
tx('2026 新年新气象', 50, 510, 980, 64, '#b3e5fc'),
im(120, 680, 840, 470, '跨年城市夜空烟花,蓝色新年氛围摄影', { radius: 24 }),
tx('愿所有美好如期而至', 50, 1240, 980, 54, '#ffffff', { weight: 700 }),
tx('Happy New Year', 50, 1345, 980, 40, '#b3e5fc', { weight: 400, italic: true }),
]),
// ---------------- 活动 ----------------
mk('choujiang', '幸运大抽奖', 'event', grad(135, '#6a1b9a', '#e91e63'), [
sh('ellipse', 340, 110, 400, 400, 'rgba(255,255,255,0.15)'),
tx('抽', 340, 205, 400, 200, '#ffd60a', { weight: 900 }),
tx('幸运大抽奖', 50, 580, 980, 150, '#ffffff', { weight: 900 }),
tx('100%中奖 · 最高赢免单', 50, 770, 980, 60, '#ffd60a'),
im(140, 900, 800, 380, '抽奖转盘与紫色礼盒,霓虹活动海报背景', { radius: 24 }),
sh('rect', 340, 1320, 400, 90, '#ffd60a', { radius: 45 }),
tx('立即参与', 340, 1338, 400, 44, '#6a1b9a'),
]),
mk('fenxiang', '行业分享会', 'event', solid('#263238'), [
sh('rect', 80, 110, 12, 130, '#00acc1'),
tx('行业干货分享会', 130, 118, 870, 72, '#80deea', { align: 'left', weight: 700 }),
tx('时间:11月20日 14:00\n地点:市图书馆 · 报告厅', 80, 320, 920, 44, '#b0bec5', { align: 'left', weight: 400, lineHeight: 1.6 }),
im(80, 560, 920, 540, '讲师舞台演讲分享会现场,PPT大屏,专业会议照片', { radius: 16 }),
sh('rect', 80, 1180, 920, 180, 'rgba(0,172,193,0.18)', { radius: 20 }),
tx('限额50名 · 报名免费', 120, 1244, 840, 46, '#80deea', { align: 'left', weight: 700 }),
]),
mk('huiyuan', '会员日', 'event', solid('#ff6f00'), [
tx('会员日', 50, 280, 980, 180, '#ffffff', { weight: 900 }),
tx('每月8日 双倍积分', 50, 510, 980, 66, '#ffe0b2'),
im(190, 660, 700, 560, '橙色暖调会员积分礼品展示,电商会员日配图', { radius: 28 }),
tx('更有会员专属价等你来抢', 50, 1280, 980, 48, '#ffffff', { weight: 700 }),
]),
// ---------------- 美食 ----------------
mk('huoguo', '招牌火锅', 'food', solid('#b71c1c'), [
tx('沸腾火锅', 50, 230, 980, 160, '#ffd54f', { weight: 900 }),
tx('麻辣鲜香 · 越煮越有味', 50, 430, 980, 56, '#ffffff'),
im(110, 580, 860, 560, '红油火锅翻滚特写,辣椒花椒热气腾腾,美食摄影', { radius: 24 }),
tx('进店消费满100送50', 50, 1220, 980, 52, '#ffd54f', { weight: 900 }),
tx('地址:美食街A12 · 11:00-次日02:00', 50, 1340, 980, 40, '#ffcdd2', { weight: 400 }),
]),
mk('naicha', '新品奶茶', 'food', grad(135, '#fce4ec', '#f8bbd0'), [
tx('新品上市', 50, 270, 980, 150, '#ad1457', { weight: 900 }),
tx('招牌奶茶 第二杯半价', 50, 470, 980, 64, '#880e4f'),
im(160, 640, 760, 560, '粉色系珍珠奶茶饮品摄影,清新甜品海报', { radius: 28 }),
sh('ellipse', 390, 1250, 300, 160, '#ad1457'),
tx('尝鲜去', 390, 1292, 300, 46, '#ffffff', { weight: 900 }),
]),
mk('shaokao', '深夜烧烤', 'food', solid('#171717'), [
tx('深夜烧烤', 50, 250, 980, 150, '#ff9100', { weight: 900 }),
tx('串串香 · 啤酒畅饮', 50, 450, 980, 58, '#ffffff'),
im(100, 600, 880, 540, '炭火烧烤羊肉串特写,火光油亮,夜市美食摄影', { radius: 20 }),
tx('营业至凌晨2点 · 到店送烤串5串', 50, 1220, 980, 46, '#ffab40', { weight: 700 }),
tx('XX路夜市3号摊', 50, 1330, 980, 38, '#9e9e9e', { weight: 400 }),
]),
// ---------------- 教育 ----------------
mk('shuxi', '暑期班招生', 'edu', grad(135, '#00695c', '#26a69a'), [
tx('暑期班招生', 50, 280, 980, 150, '#ffffff', { weight: 900 }),
tx('名额有限 · 报名立减500', 50, 480, 980, 60, '#b2dfdb'),
im(130, 640, 820, 470, '学生在明亮教室上课,教育培训宣传照', { radius: 24 }),
sh('rect', 290, 1200, 500, 100, '#ffd60a', { radius: 50 }),
tx('免费试听一节课', 290, 1222, 500, 44, '#00695c'),
tx('咨询电话:400-000-0000', 50, 1345, 980, 40, '#b2dfdb', { weight: 400 }),
]),
mk('kaixue', '开学季特惠', 'edu', solid('#1565c0'), [
tx('开学季', 50, 260, 980, 170, '#ffd60a', { weight: 900 }),
tx('学费立减500元', 50, 470, 980, 76, '#ffffff', { weight: 900 }),
tx('再送开学大礼包', 50, 610, 980, 50, '#bbdefb'),
im(150, 740, 780, 430, '书本文具开学用品摆拍,蓝色清爽背景', { radius: 24 }),
sh('rect', 340, 1260, 400, 96, '#ffd60a', { radius: 48 }),
tx('马上报名', 340, 1280, 400, 44, '#1565c0'),
]),
mk('chongci', '考试冲刺营', 'edu', solid('#283593'), [
tx('考试冲刺营', 50, 250, 980, 140, '#ffd54f', { weight: 900 }),
tx('30天高效提分计划', 50, 450, 980, 64, '#ffffff'),
im(120, 610, 840, 470, '学生夜晚书桌台灯下复习,学习氛围照片', { radius: 24 }),
tx('一对一辅导 · 名师划重点', 50, 1160, 980, 50, '#c5cae9'),
sh('rect', 300, 1270, 480, 96, '#ffd54f', { radius: 48 }),
tx('预约免费测评', 300, 1290, 480, 44, '#283593'),
]),
// ---------------- 健身 ----------------
mk('jianshen', '健身年卡', 'sport', solid('#1b1b1b'), [
tx('年卡特惠', 50, 250, 980, 160, '#c6ff00', { weight: 900 }),
tx('¥1999/年 限时开抢', 50, 460, 980, 72, '#ffffff', { weight: 900 }),
im(100, 620, 880, 500, '健身房力量训练场景,深色调硬核健身摄影', { radius: 24 }),
tx('私教体验课×3 免费送', 50, 1210, 980, 50, '#c6ff00', { weight: 700 }),
tx('24小时营业 · 全城连锁', 50, 1330, 980, 38, '#9e9e9e', { weight: 400 }),
]),
mk('yujia', '瑜伽体验课', 'sport', grad(160, '#80cbc4', '#e0f2f1'), [
tx('瑜伽体验课', 50, 280, 980, 140, '#00695c', { weight: 900 }),
tx('新客免费 · 零基础友好', 50, 470, 980, 58, '#004d40'),
im(140, 640, 800, 520, '瑜伽垫上的女性拉伸,明亮工作室清新氛围', { radius: 28 }),
tx('每周六上午 10:00', 50, 1240, 980, 48, '#00695c', { weight: 700 }),
tx('扫码预约 限前50名', 50, 1335, 980, 42, '#00897b', { weight: 400 }),
]),
// ---------------- 招聘 ----------------
mk('gaoxin', '高薪招聘', 'recruit', solid('#0d1b2a'), [
sh('rect', 0, 0, 1080, 12, '#00e5ff'),
tx('高薪招聘\n期待你加入', 80, 170, 920, 110, '#ffffff', { align: 'left', weight: 900, lineHeight: 1.35 }),
tx('前端工程师 / 产品经理 / 运营', 80, 510, 920, 48, '#4dd0e1', { align: 'left', weight: 700 }),
tx('13薪 · 五险一金 · 弹性工作 · 年度体检', 80, 630, 920, 44, '#90a4ae', { align: 'left', weight: 400 }),
im(80, 770, 920, 430, '现代互联网公司开放办公区,团队协作照片', { radius: 16 }),
sh('rect', 80, 1300, 460, 92, '#00e5ff', { radius: 46 }),
tx('投递简历', 80, 1319, 460, 40, '#0d1b2a'),
]),
mk('mendi', '门店招聘', 'recruit', solid('#ffd60a'), [
tx('门店招聘', 50, 270, 980, 160, '#111111', { weight: 900 }),
tx('店员 / 收银 / 导购', 50, 480, 980, 64, '#b71c1c', { weight: 900 }),
tx('月薪4500-8000 · 包吃住', 50, 610, 980, 52, '#111111'),
im(140, 740, 800, 420, '明亮便利店门店员工微笑服务照片', { radius: 24 }),
sh('rect', 300, 1250, 480, 100, '#b71c1c', { radius: 50 }),
tx('电话:138-0000-0000', 300, 1274, 480, 44, '#ffffff', { weight: 900 }),
]),
// ---------------- 生日 ----------------
mk('shengri', '生日快乐', 'birthday', grad(135, '#f8bbd0', '#f48fb1'), [
tx('生日快乐', 50, 260, 980, 170, '#ad1457', { weight: 900 }),
tx('愿你所求皆如愿', 50, 465, 980, 56, '#880e4f'),
im(170, 630, 740, 560, '粉色生日蛋糕蜡烛气球,生日派对摄影', { radius: 32 }),
sh('ellipse', 380, 1250, 320, 160, '#ad1457'),
tx('许愿时刻', 380, 1292, 320, 46, '#ffffff', { weight: 900 }),
]),
mk('zhousui', '宝宝周岁', 'birthday', grad(135, '#fff9c4', '#ffe0b2'), [
tx('周岁快乐', 50, 250, 980, 150, '#ef6c00', { weight: 900 }),
tx('宝宝成长纪念', 50, 450, 980, 56, '#e65100'),
im(160, 620, 760, 560, '抓周物品与宝宝生日布置,暖黄色温馨照片', { radius: 32 }),
tx('健康快乐 平安长大', 50, 1280, 980, 48, '#bf360c', { weight: 700 }),
]),
// ---------------- 封面/宣传 ----------------
mk('ganhuo', '干货分享封面', 'redbook', solid('#f7f7f7'), [
sh('rect', 70, 90, 340, 92, '#ff2442', { radius: 46 }),
tx('干货分享', 70, 111, 340, 42, '#ffffff', { weight: 900 }),
tx('5个让效率翻倍\n的办公神器', 70, 240, 940, 96, '#111111', { align: 'left', weight: 900, lineHeight: 1.4 }),
tx('收藏 = 用到', 70, 530, 940, 40, '#888888', { align: 'left', weight: 400 }),
im(70, 640, 940, 640, '干净留白的桌面办公好物平铺摄影,小红书封面风格', { radius: 24 }),
tx('关注我 持续分享实用工具', 70, 1350, 940, 36, '#999999', { align: 'left', weight: 400 }),
]),
mk('qiye', '企业宣传', 'redbook', grad(135, '#004d40', '#00897b'), [
tx('企业宣传', 50, 300, 980, 150, '#ffffff', { weight: 900 }),
tx('专业 · 高效 · 值得信赖', 50, 500, 980, 56, '#b2dfdb'),
im(110, 660, 860, 520, '现代企业办公大楼玻璃幕墙蓝天,商务摄影', { radius: 20 }),
tx('成立10年 · 服务客户10000+', 50, 1250, 980, 46, '#80cbc4', { weight: 700 }),
sh('rect', 340, 1345, 400, 76, 'rgba(255,255,255,0.92)', { radius: 38 }),
tx('了解更多', 340, 1363, 400, 36, '#004d40', { weight: 700 }),
]),
// ---------------- 校园(学校/老师/学生) ----------------
mk('jiaoshijie', '教师节快乐', 'school', grad(135, '#ff8f00', '#ffd54f'), [
sh('ellipse', 660, 70, 380, 380, 'rgba(255,255,255,0.16)'),
tx('教师节快乐', 50, 330, 980, 150, '#ffffff', { weight: 900, shadow: { color: 'rgba(180,80,0,0.4)', blur: 20, y: 6 } }),
tx('三尺讲台 · 一生耕耘', 50, 540, 980, 56, '#fff3e0', { weight: 700 }),
im(140, 670, 800, 470, '老师在黑板前讲课,明亮温暖教室,教师节主题摄影', { radius: 24 }),
sh('rect', 340, 1195, 400, 96, '#c62828', { radius: 48 }),
tx('感恩有您', 340, 1217, 400, 44, '#ffd54f'),
tx('9月10日 · 致敬每一位恩师', 50, 1345, 980, 40, '#fff8e1', { weight: 400 }),
]),
mk('kaixue1', '开学第一课', 'school', grad(120, '#1565c0', '#42a5f5'), [
tx('开学第一课', 50, 260, 980, 150, '#ffd60a', { weight: 900 }),
tx('新学期 · 新起点 · 新目标', 50, 470, 980, 54, '#ffffff', { weight: 700 }),
im(130, 620, 820, 480, '黑板与书本开学场景,粉笔字新学期,明亮教室', { radius: 24 }),
sh('rect', 300, 1180, 480, 100, '#ffd60a', { radius: 50 }),
tx('收心启航 立即返校', 300, 1206, 480, 44, '#1565c0'),
tx('XX学校 9月1日正式上课', 50, 1340, 980, 40, '#bbdefb', { weight: 400 }),
]),
mk('jiazhanghui', '家长会通知', 'school', solid('#1a237e'), [
sh('rect', 0, 0, 1080, 14, '#ffd60a'),
tx('家长会通知', 60, 130, 960, 130, '#ffffff', { align: 'left', weight: 900 }),
tx('时间:本周六 09:00\n地点:三年级(2)班教室\n主讲:班主任 王老师', 60, 350, 960, 46, '#c5cae9', { align: 'left', weight: 400, lineHeight: 1.7 }),
im(60, 660, 960, 430, '教室家长会现场,课桌整齐排列,明亮校园教室', { radius: 16 }),
sh('rect', 60, 1170, 480, 96, '#ffd60a', { radius: 48 }),
tx('敬请准时出席', 60, 1193, 480, 44, '#1a237e'),
tx('XX小学 三年级(2)班 家委会', 60, 1330, 960, 38, '#90a4ae', { align: 'left', weight: 400 }),
]),
mk('yundonghui', '秋季运动会', 'school', grad(135, '#d32f2f', '#ff7043'), [
sh('ellipse', -80, 180, 320, 320, 'rgba(255,255,255,0.12)'),
tx('秋季运动会', 50, 300, 980, 165, '#ffd54f', { weight: 900 }),
tx('激情飞扬 · 超越自我', 50, 520, 980, 56, '#ffffff', { weight: 700 }),
im(120, 660, 840, 470, '学校操场红色跑道与运动健儿,运动会场景', { radius: 24 }),
sh('rect', 340, 1200, 400, 96, '#ffffff', { radius: 48 }),
tx('报名参赛', 340, 1224, 400, 44, '#d32f2f'),
tx('10月16日 · 学校操场', 50, 1345, 980, 40, '#ffe0b2', { weight: 400 }),
]),
mk('biyeji', '毕业季', 'school', grad(160, '#0d47a1', '#26c6da'), [
tx('毕业快乐', 50, 250, 980, 175, '#ffffff', { weight: 900, shadow: { color: 'rgba(0,40,90,0.45)', blur: 22, y: 8 } }),
tx('愿你前程似锦 · 顶峰相见', 50, 470, 980, 54, '#b3e5fc', { weight: 700 }),
im(190, 620, 700, 640, '学士帽抛向蓝天,毕业季庆祝,青春校园', { radius: 32 }),
tx('2026届 · 青春不散场', 50, 1350, 980, 42, '#e1f5fe', { weight: 400 }),
]),
mk('shezhaoxin', '社团招新', 'school', grad(135, '#8e24aa', '#ff6d00'), [
tx('社团招新', 50, 270, 980, 170, '#ffffff', { weight: 900 }),
tx('百团大战 · 就等你来', 50, 490, 980, 58, '#ffe0b2', { weight: 700 }),
im(140, 640, 800, 470, '大学生社团活动,街舞音乐绘画丰富多彩,校园招新', { radius: 28 }),
sh('ellipse', 370, 1180, 340, 170, '#ffd60a'),
tx('加入我们', 370, 1228, 340, 48, '#6a1b9a', { weight: 900 }),
tx('本周五中午 · 食堂广场', 50, 1380, 980, 38, '#ffffff', { weight: 400 }),
]),
mk('biaozhang', '优秀学生表彰', 'school', solid('#fff8e1'), [
sh('rect', 36, 36, 1008, 1368, '#c62828'),
sh('rect', 60, 60, 960, 1320, '#fff8e1'),
tx('光荣榜', 50, 170, 980, 150, '#c62828', { weight: 900 }),
tx('优秀学生表彰', 50, 370, 980, 96, '#d32f2f', { weight: 900, rot: -4 }),
tx('张同学 · 李同学 · 王同学\n品学兼优 · 全面发展', 140, 570, 800, 52, '#5d4037', { weight: 700, lineHeight: 1.8 }),
im(240, 810, 600, 380, '金色奖杯与奖状证书特写,表彰大会氛围', { radius: 20 }),
tx('XX学校 教务处', 50, 1270, 980, 44, '#8d6e63', { weight: 400 }),
]),
mk('ertongjie', '快乐六一', 'school', grad(135, '#00bcd4', '#8bc34a'), [
tx('快乐六一', 50, 270, 980, 165, '#ffffff', { weight: 900, shadow: { color: 'rgba(0,90,110,0.35)', blur: 18, y: 6 } }),
tx('阳光自信 · 快乐成长', 50, 485, 980, 54, '#e0f7fa', { weight: 700 }),
im(160, 630, 760, 550, '小学校园儿童欢笑庆祝,彩色气球彩带,六一儿童节', { radius: 32 }),
sh('ellipse', 390, 1230, 300, 160, '#ff5722'),
tx('6·1', 390, 1272, 300, 62, '#ffffff', { weight: 900 }),
tx('XX小学 庆六一文艺汇演', 50, 1395, 980, 36, '#ffffff', { weight: 400 }),
]),
mk('kaoshi', '考试加油', 'school', solid('#b71c1c'), [
sh('ellipse', 340, 90, 400, 400, 'rgba(255,213,79,0.92)'),
tx('必胜', 340, 210, 400, 150, '#b71c1c', { weight: 900 }),
tx('考试加油', 50, 560, 980, 165, '#ffd54f', { weight: 900 }),
tx('以梦为马 · 不负韶华', 50, 780, 980, 54, '#ffffff', { weight: 700 }),
im(140, 900, 800, 350, '学生伏案复习试卷书本特写,台灯下奋斗场景', { radius: 20 }),
sh('rect', 300, 1300, 480, 96, '#ffd60a', { radius: 48 }),
tx('金榜题名', 300, 1324, 480, 44, '#b71c1c'),
]),
mk('dushuyue', '书香校园读书月', 'school', grad(160, '#4e342e', '#8d6e63'), [
tx('书香校园', 50, 260, 980, 160, '#ffe0b2', { weight: 900 }),
tx('读书月 · 阅读分享活动', 50, 470, 980, 52, '#ffffff', { weight: 700 }),
im(130, 620, 820, 480, '图书馆书架与学生阅读,温暖木质色调,书香氛围', { radius: 24 }),
sh('rect', 290, 1170, 500, 96, '#ffe0b2', { radius: 48 }),
tx('每天阅读30分钟', 290, 1194, 500, 44, '#4e342e'),
tx('主办:语文教研组 · 11月', 50, 1330, 980, 40, '#d7ccc8', { weight: 400 }),
]),
// ---------------- 更多促销/节日/活动/美食 ----------------
mk('miaosha', '限时秒杀', 'promo', solid('#111111'), [
tx('限时秒杀', 50, 260, 980, 170, '#ff1744', { weight: 900 }),
tx('前100名 · 1元抢', 50, 480, 980, 72, '#ffffff', { weight: 900 }),
im(80, 660, 580, 520, '爆款商品抢购堆头,红黑配色电商海报', { radius: 24 }),
sh('ellipse', 700, 660, 320, 320, 'rgba(255,23,68,0.88)'),
tx('1元', 700, 755, 320, 120, '#ffffff', { weight: 900, rot: -8 }),
tx('每晚8点准时开抢', 50, 1260, 980, 52, '#ff8a80', { weight: 700 }),
tx('活动截止:11月30日', 50, 1350, 980, 38, '#9e9e9e', { weight: 400 }),
]),
mk('shuang12', '双12年终盛典', 'promo', grad(135, '#4a148c', '#e91e63'), [
sh('ellipse', 620, 50, 440, 440, 'rgba(255,255,255,0.12)'),
tx('双12年终盛典', 40, 340, 1000, 130, '#ffffff', { weight: 900 }),
tx('年终好价 · 全场包邮', 50, 530, 980, 58, '#ffd60a', { weight: 900 }),
im(140, 670, 800, 470, '双12紫色电商促销礼盒堆头,霓虹光效', { radius: 28 }),
sh('rect', 340, 1210, 400, 96, '#ffd60a', { radius: 48 }),
tx('立即抢购', 340, 1234, 400, 44, '#4a148c'),
tx('12月12日 0点开抢', 50, 1350, 980, 40, '#f3e5f5', { weight: 400 }),
]),
mk('muri', '母亲节快乐', 'festival', grad(160, '#ec407a', '#f8bbd0'), [
tx('母亲节快乐', 50, 280, 980, 160, '#ffffff', { weight: 900, shadow: { color: 'rgba(150,20,60,0.35)', blur: 18, y: 6 } }),
tx('时光不老 · 母爱永恒', 50, 490, 980, 54, '#fce4ec', { weight: 700 }),
im(170, 640, 740, 540, '粉色康乃馨花束特写,母亲节温馨氛围', { radius: 32 }),
sh('ellipse', 380, 1225, 320, 150, '#ad1457'),
tx('感恩有你', 380, 1265, 320, 46, '#ffffff', { weight: 900 }),
tx('5月第二个星期日', 50, 1395, 980, 36, '#ffffff', { weight: 400 }),
]),
mk('zhounian', '门店周年庆', 'event', grad(135, '#bf360c', '#ff6d00'), [
tx('三周年庆', 50, 290, 980, 175, '#ffd54f', { weight: 900 }),
tx('感恩回馈 · 全场5折', 50, 520, 980, 60, '#ffffff', { weight: 900 }),
im(130, 670, 820, 460, '店铺周年庆气球拱门与礼盒,喜庆橙红色', { radius: 24 }),
sh('rect', 300, 1195, 480, 100, '#ffffff', { radius: 50 }),
tx('进店即送礼品', 300, 1222, 480, 44, '#bf360c'),
tx('活动3天 · 11月20-22日', 50, 1345, 980, 40, '#ffe0b2', { weight: 400 }),
]),
mk('waimai', '外卖满减', 'food', solid('#ff6f00'), [
tx('外卖满减', 50, 250, 980, 165, '#ffffff', { weight: 900 }),
tx('满25减12 · 满40减20', 50, 465, 980, 62, '#ffe0b2', { weight: 900 }),
im(140, 630, 800, 470, '外卖餐盒美食打包俯拍,橙色暖调餐饮摄影', { radius: 28 }),
sh('ellipse', 700, 1140, 300, 160, '#b71c1c'),
tx('立减', 700, 1184, 300, 50, '#ffd54f', { weight: 900 }),
tx('扫码下单 · 30分钟送达', 50, 1350, 980, 44, '#ffffff', { weight: 700 }),
]),
mk('kafei', '咖啡新品', 'food', solid('#3e2723'), [
tx('新品拿铁', 50, 250, 980, 160, '#ffab40', { weight: 900 }),
tx('第二杯半价', 50, 450, 980, 66, '#ffffff', { weight: 900 }),
im(150, 610, 780, 560, '咖啡拉花拿铁特写,木质桌面暖光,咖啡馆氛围', { radius: 32 }),
tx('每日现磨 · 门店限量', 50, 1250, 980, 48, '#ffe0b2', { weight: 700 }),
tx('活动时间:11:00 - 18:00', 50, 1350, 980, 38, '#bcaaa4', { weight: 400 }),
]),
mk('meishijie', '美食嘉年华', 'food', grad(135, '#e65100', '#ffb300'), [
sh('ellipse', -70, 240, 300, 300, 'rgba(255,255,255,0.14)'),
tx('美食嘉年华', 50, 300, 980, 155, '#ffffff', { weight: 900 }),
tx('全场5折 · 吃货狂欢', 50, 510, 980, 58, '#fff3e0', { weight: 900 }),
im(130, 660, 820, 470, '各类美食拼盘俯拍,烤串甜品饮品,热闹美食节', { radius: 24 }),
sh('rect', 340, 1200, 400, 96, '#b71c1c', { radius: 48 }),
tx('5折开吃', 340, 1224, 400, 44, '#ffd54f'),
tx('本周六日 · 中心广场', 50, 1345, 980, 40, '#ffffff', { weight: 400 }),
]),
];
// 背景快捷预设(画布"背景"区一键切换)
export const BG_PRESETS: { name: string; bg: PosterBg }[] = [
{ name: '中国红', bg: grad(135, '#c62828', '#ff8f00') },
{ name: '活力橙', bg: grad(135, '#ff6d00', '#ffb300') },
{ name: '科技蓝', bg: grad(120, '#0052ff', '#00c6ff') },
{ name: '魅紫', bg: grad(135, '#6a1b9a', '#e91e63') },
{ name: '森绿', bg: grad(135, '#00695c', '#26a69a') },
{ name: '樱花粉', bg: grad(135, '#f8bbd0', '#f48fb1') },
{ name: '暗夜黑', bg: solid('#171717') },
{ name: '奶油白', bg: solid('#f7f7f7') },
];
+31 -7
View File
@@ -1,12 +1,21 @@
<script setup lang="ts">
import { onMounted, ref } from 'vue';
import { useHead } from '@vueuse/head';
import GenHistory from '@/tools/gen-history/GenHistory.vue';
import { useGenHistory } from '@/tools/gen-history/gen-history';
import ImgHist from '@/tools/img-hist/ImgHist.vue';
import { blobToB64, saveImgHist } from '@/tools/img-hist/img-hist';
useHead({ title: '文字生成图片 - IT-TOOLS-PRO' });
const genHist = useGenHistory('text-to-image');
const histRef = ref<InstanceType<typeof ImgHist> | null>(null);
/** 生成结果保存到服务器历史(失败静默,不影响本地下载) */
async function persist(b64: string) {
try {
const ok = await saveImgHist({ kind: 'text-to-image', tool: 'text-to-image', b64, model: '文字生成图片', prompt: (text.value || '').slice(0, 100) });
if (ok) histRef.value?.reload();
}
catch { /* 静默 */ }
}
const text = ref('在线免费文字生成图片工具\nIT-TOOLS-PRO 让你更高效地工作\n如果你觉得这个工具好用,可以分享给你的小伙伴们');
const format = ref<'png' | 'jpg'>('png');
@@ -36,7 +45,7 @@ const generated = ref(false);
const resultUrl = ref('');
const resultSize = ref(0);
function render(toBlob = false) {
function render(toBlob = false, save = false) {
const c = canvas.value;
if (!c) {
return;
@@ -66,13 +75,15 @@ function render(toBlob = false) {
}
resultUrl.value = URL.createObjectURL(blob);
resultSize.value = blob.size;
if (save) {
blobToB64(blob).then((b64) => { if (b64) persist(b64); });
}
}, mime, 0.92);
}
}
function download() {
render(true);
genHist.add({ title: `文字生成图片: ${text.value.slice(0, 20)}`, detail: `${width.value}×${height.value} ${format.value.toUpperCase()} · ${fontSize.value}px` });
setTimeout(() => {
const a = document.createElement('a');
a.href = resultUrl.value;
@@ -105,6 +116,7 @@ onMounted(() => {
<template>
<div class="ti-root">
<div class="ti-main">
<div class="ti-panel">
<div class="ti-panel-title">📝 文本内容</div>
<textarea v-model="text" class="ti-textarea" rows="6" placeholder="输入要生成图片的文字,支持多行…" @input="render()" />
@@ -175,7 +187,7 @@ onMounted(() => {
</div>
<div class="ti-btns">
<button class="ti-btn" @click="render(true)">
<button class="ti-btn" @click="render(true, true)">
🚀 生成
</button>
<button class="ti-btn ti-btn-ghost" :disabled="!resultUrl" @click="download">
@@ -197,13 +209,25 @@ onMounted(() => {
</div>
</div>
<GenHistory tool="text-to-image" label="生成记录" class="mt-10px" />
</div>
<ImgHist ref="histRef" kind="text-to-image" />
</div>
</template>
<style lang="less" scoped>
.ti-root {
padding-bottom: 40px;
display: flex;
flex-direction: row;
gap: 12px;
align-items: flex-start;
}
.ti-main {
flex: 1;
min-width: 0;
}
@media (max-width: 760px) {
.ti-root { flex-direction: column; }
}
.ti-panel {