Files
it-tools-pro/src/tools/ai-image-lab/ai-image-lab.vue
T
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

571 lines
16 KiB
Vue
Raw Blame History

This file contains invisible Unicode characters
This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<script setup lang="ts">
import { onMounted, ref } from 'vue';
import { useHead } from '@vueuse/head';
import { licenseHeaders } from '@/tools/license/license';
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 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');
// ============ 公共 ============
const srcUrl = ref('');
const outUrl = ref('');
const busy = ref(false);
const error = ref('');
const fileInput = ref<HTMLInputElement>();
const curFile = ref<File | null>(null);
function pickFile() {
fileInput.value?.click();
}
function onInput(e: Event) {
const input = e.target as HTMLInputElement;
setFile(input.files?.[0] ?? null);
input.value = '';
}
function onDrop(e: DragEvent) {
setFile(e.dataTransfer?.files?.[0] ?? null);
}
function setFile(f: File | null) {
if (srcUrl.value) {
URL.revokeObjectURL(srcUrl.value);
}
if (outUrl.value) {
URL.revokeObjectURL(outUrl.value);
}
curFile.value = f;
srcUrl.value = f ? URL.createObjectURL(f) : '';
outUrl.value = '';
error.value = '';
}
async function fetchWithTimeout(url: string, opts: RequestInit, ms: number): Promise<Response> {
const ctrl = new AbortController();
const t = setTimeout(() => ctrl.abort(), ms);
try {
return await fetch(url, { ...opts, signal: ctrl.signal });
}
finally {
clearTimeout(t);
}
}
// ============ 抠图 ============
const bgMode = ref<'transparent' | 'white' | 'red' | 'blue' | 'green'>('transparent');
async function doMatting() {
if (!curFile.value) {
error.value = '请先上传图片';
return;
}
busy.value = true;
error.value = '';
try {
const res = await fetchWithTimeout('/relay/remove-bg', {
method: 'POST',
body: curFile.value,
headers: { ...licenseHeaders('ai-image-tools'), 'Content-Type': curFile.value.type || 'image/jpeg' },
}, 120000);
if (!res.ok) {
const j = await res.json().catch(() => ({}));
throw new Error(j.message || `HTTP ${res.status}`);
}
const blob = await res.blob();
if (outUrl.value) {
URL.revokeObjectURL(outUrl.value);
}
outUrl.value = URL.createObjectURL(blob);
outBlob.value = blob;
saveLab('AI抠图', curFile.value?.name || '', blob);
}
catch (e: any) {
error.value = String(e?.message || e);
}
finally {
busy.value = false;
}
}
const outBlob = ref<Blob | null>(null);
// 抠图结果叠加底色预览(证件照换底也用)
const compositeUrl = ref('');
async function applyBg(mode: string) {
bgMode.value = mode as any;
if (!outBlob.value) {
return;
}
const img = new Image();
const url = URL.createObjectURL(outBlob.value);
await new Promise<void>((r) => {
img.onload = () => r();
img.src = url;
});
const c = document.createElement('canvas');
c.width = img.naturalWidth;
c.height = img.naturalHeight;
const ctx = c.getContext('2d')!;
if (mode !== 'transparent') {
const colors: Record<string, string> = { white: '#ffffff', red: '#e60012', blue: '#438edb', green: '#07a05c' };
ctx.fillStyle = colors[mode] || '#ffffff';
ctx.fillRect(0, 0, c.width, c.height);
}
ctx.drawImage(img, 0, 0);
URL.revokeObjectURL(url);
if (compositeUrl.value) {
URL.revokeObjectURL(compositeUrl.value);
}
compositeUrl.value = c.toDataURL('image/png');
}
// ============ 无损放大 ============
const upScale = ref(2);
const upNoise = ref(1);
async function doUpscale() {
if (!curFile.value) {
error.value = '请先上传图片';
return;
}
busy.value = true;
error.value = '';
try {
const res = await fetchWithTimeout(`/relay/upscale?scale=${upScale.value}&noise=${upNoise.value}`, {
method: 'POST',
body: curFile.value,
headers: { ...licenseHeaders('ai-image-tools'), 'Content-Type': curFile.value.type || 'image/jpeg' },
}, 200000);
if (!res.ok) {
const j = await res.json().catch(() => ({}));
throw new Error(j.message || `HTTP ${res.status}`);
}
const blob = await res.blob();
if (outUrl.value) {
URL.revokeObjectURL(outUrl.value);
}
outUrl.value = URL.createObjectURL(blob);
const img = new Image();
img.src = outUrl.value;
await new Promise<void>((r) => {
img.onload = () => r();
});
saveLab(`AI放大${upScale.value}x`, curFile.value?.name || '', blob);
}
catch (e: any) {
error.value = String(e?.message || e);
}
finally {
busy.value = false;
}
}
// ============ 证件照 ============
const idSizes = [
{ key: 'one', name: '一寸', w: 295, h: 413 },
{ key: 'two', name: '二寸', w: 413, h: 579 },
{ key: 'passport', name: '护照', w: 390, h: 567 },
{ key: 'sq', name: '方形头像', w: 400, h: 400 },
];
const idSize = ref('one');
const idBg = ref<'white' | 'red' | 'blue'>('white');
const headScale = ref(100);
const headY = ref(0);
const idResult = ref('');
async function makeIdPhoto() {
if (!outBlob.value) {
error.value = '请先完成抠图(切换到「抠图」生成透明底图)';
return;
}
error.value = '';
const spec = idSizes.find(s => s.key === idSize.value)!;
const img = new Image();
const url = URL.createObjectURL(outBlob.value);
await new Promise<void>((r) => {
img.onload = () => r();
img.src = url;
});
const c = document.createElement('canvas');
c.width = spec.w;
c.height = spec.h;
const ctx = c.getContext('2d')!;
const colors: Record<string, string> = { white: '#ffffff', red: '#e60012', blue: '#438edb' };
ctx.fillStyle = colors[idBg.value];
ctx.fillRect(0, 0, c.width, c.height);
// 人物居中:按证件照标准(头部占约 60-70% 高)
const base = (c.height * 0.92) / img.naturalHeight;
const s = base * (headScale.value / 100);
const dw = img.naturalWidth * s;
const dh = img.naturalHeight * s;
const dx = (c.width - dw) / 2;
const dy = (c.height - dh) / 2 + (headY.value / 100) * c.height * 0.25;
ctx.drawImage(img, dx, dy, dw, dh);
if (idResult.value) {
URL.revokeObjectURL(idResult.value);
}
idResult.value = c.toDataURL('image/png');
saveLab('证件照', `${spec.name} ${idBg.value === 'white' ? '白底' : idBg.value === 'red' ? '红底' : '蓝底'}`, idResult.value || '');
}
function downloadUrl(url: string, name: string) {
const a = document.createElement('a');
a.href = url;
a.download = name;
a.click();
}
function switchTab(k: TabKey) {
tab.value = k;
error.value = '';
}
onMounted(() => {});
</script>
<template>
<div class="al-root">
<div class="al-tabs">
<button class="al-tab" :class="{ on: tab === 'matting' }" @click="switchTab('matting')">
✂️ 智能抠图
</button>
<button class="al-tab" :class="{ on: tab === 'upscale' }" @click="switchTab('upscale')">
🔍 无损放大
</button>
<button class="al-tab" :class="{ on: tab === 'idphoto' }" @click="switchTab('idphoto')">
🪪 证件照制作
</button>
<span class="al-note">本地 AI 处理,图片不离开服务器</span>
</div>
<div class="al-cols">
<!-- 左:参数 -->
<div class="al-left">
<input ref="fileInput" type="file" hidden accept="image/*" @change="onInput">
<div class="al-drop" @click="pickFile" @dragover.prevent @drop.prevent="onDrop">
<template v-if="!curFile">
<div class="al-drop-hint">📁 点击或拖入图片<br><span>JPG / PNG / WebP · ≤30MB</span></div>
</template>
<div v-else class="al-file">
🖼️ {{ curFile.name }}
<span class="al-file-size">({{ (curFile.size / 1024 / 1024).toFixed(1) }} MB)</span>
<a href="javascript:;" class="al-clear" @click.stop="setFile(null)">✕</a>
</div>
</div>
<!-- 抠图参数 -->
<template v-if="tab === 'matting'">
<div class="al-sec">抠图后背景</div>
<div class="al-chips">
<button class="al-chip" :class="{ on: bgMode === 'transparent' }" @click="applyBg('transparent')">透明</button>
<button class="al-chip" :class="{ on: bgMode === 'white' }" @click="applyBg('white')">白色</button>
<button class="al-chip" :class="{ on: bgMode === 'red' }" @click="applyBg('red')">红色</button>
<button class="al-chip" :class="{ on: bgMode === 'blue' }" @click="applyBg('blue')">蓝色</button>
<button class="al-chip" :class="{ on: bgMode === 'green' }" @click="applyBg('green')">绿色</button>
</div>
<div class="al-hint">一键去除背景,保留主体;可直接切换证件照底色。</div>
</template>
<!-- 放大参数 -->
<template v-if="tab === 'upscale'">
<div class="al-sec">放大倍数</div>
<div class="al-chips">
<button class="al-chip" :class="{ on: upScale === 2 }" @click="upScale = 2">2 倍</button>
<button class="al-chip" :class="{ on: upScale === 4 }" @click="upScale = 4">4 倍</button>
</div>
<div class="al-sec">降噪强度</div>
<div class="al-chips">
<button v-for="n in [-1, 0, 1, 2, 3]" :key="n" class="al-chip" :class="{ on: upNoise === n }" @click="upNoise = n">
{{ n === -1 ? '无' : `LV${n}` }}
</button>
</div>
<div class="al-hint">waifu2x 深度学习超分:模糊/低清图片放大后补细节,截图和照片都适用。</div>
</template>
<!-- 证件照参数 -->
<template v-if="tab === 'idphoto'">
<div class="al-sec">证件照规格</div>
<div class="al-chips">
<button v-for="s in idSizes" :key="s.key" class="al-chip" :class="{ on: idSize === s.key }" @click="idSize = s.key; makeIdPhoto()">
{{ s.name }}
</button>
</div>
<div class="al-sec">背景颜色</div>
<div class="al-chips">
<button class="al-chip" :class="{ on: idBg === 'white' }" @click="idBg = 'white'; makeIdPhoto()">白底</button>
<button class="al-chip" :class="{ on: idBg === 'red' }" @click="idBg = 'red'; makeIdPhoto()">红底</button>
<button class="al-chip" :class="{ on: idBg === 'blue' }" @click="idBg = 'blue'; makeIdPhoto()">蓝底</button>
</div>
<div class="al-sec">人物大小 {{ headScale }}%</div>
<input v-model.number="headScale" type="range" min="70" max="140" step="1" class="al-range" @change="makeIdPhoto()">
<div class="al-sec">上下位置 {{ headY > 0 ? '+' : '' }}{{ headY }}</div>
<input v-model.number="headY" type="range" min="-30" max="30" step="1" class="al-range" @change="makeIdPhoto()">
<div class="al-hint">流程:先在「抠图」去掉背景 → 回到本页选规格底色 → 微调人物大小位置。</div>
</template>
<button class="al-go" :disabled="busy || !curFile" @click="tab === 'matting' ? doMatting() : tab === 'upscale' ? doUpscale() : makeIdPhoto()">
{{ busy ? '⏳ AI 处理中…' : tab === 'matting' ? '✂️ 开始抠图' : tab === 'upscale' ? `🔍 放大 ${upScale}x` : '🪪 生成证件照' }}
</button>
<div v-if="error" class="al-error">{{ error }}</div>
</div>
<!-- 右:预览 -->
<div class="al-right">
<div class="al-sec">
{{ tab === 'idphoto' ? '证件照预览' : outUrl ? '处理结果' : '原图预览' }}
<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">
<img v-if="tab === 'idphoto' && idResult" :src="idResult" class="al-img al-img-id" alt="id photo">
<img v-else-if="outUrl" :src="bgMode !== 'transparent' && compositeUrl && tab === 'matting' ? compositeUrl : outUrl" class="al-img al-img-checker" alt="result">
<img v-else-if="srcUrl" :src="srcUrl" class="al-img" alt="source">
<div v-else class="al-empty">上传图片后在这里预览</div>
</div>
</div>
<ImgHist ref="histRef" kind="ai-image-lab" />
</div>
</div>
</template>
<style lang="less" scoped>
.al-root {
padding-bottom: 16px;
}
.al-tabs {
display: flex;
gap: 8px;
align-items: center;
margin-bottom: 14px;
flex-wrap: wrap;
}
.al-tab {
border: 1px solid rgba(128, 128, 128, 0.3);
background: #fff;
border-radius: 999px;
padding: 8px 18px;
font-size: 15px;
cursor: pointer;
transition: all 0.15s;
&.on {
background: #2563eb;
border-color: #2563eb;
color: #fff;
font-weight: 700;
}
}
.al-note {
margin-left: auto;
font-size: 13px;
opacity: 0.5;
}
.al-cols {
display: flex;
gap: 14px;
align-items: flex-start;
}
.al-left {
width: 340px;
flex-shrink: 0;
border: 1px solid rgba(128, 128, 128, 0.2);
border-radius: 12px;
padding: 14px;
}
.al-right {
flex: 1;
min-width: 0;
border: 1px solid rgba(128, 128, 128, 0.2);
border-radius: 12px;
padding: 14px;
}
.al-drop {
border: 1.5px dashed rgba(128, 128, 128, 0.4);
border-radius: 10px;
padding: 18px 12px;
text-align: center;
cursor: pointer;
margin-bottom: 12px;
transition: border-color 0.15s;
&:hover {
border-color: #2563eb;
}
.al-drop-hint {
font-size: 15px;
font-weight: 600;
line-height: 1.7;
span {
font-size: 13px;
font-weight: 400;
opacity: 0.5;
}
}
.al-file {
font-size: 14px;
font-weight: 600;
word-break: break-all;
.al-file-size {
font-weight: 400;
opacity: 0.55;
}
.al-clear {
color: #d03050;
margin-left: 8px;
text-decoration: none;
}
}
}
.al-sec {
font-size: 14px;
font-weight: 700;
opacity: 0.75;
margin: 10px 0 7px;
display: flex;
justify-content: space-between;
align-items: center;
}
.al-chips {
display: flex;
gap: 7px;
flex-wrap: wrap;
}
.al-chip {
border: 1px solid rgba(128, 128, 128, 0.3);
background: #fff;
border-radius: 999px;
padding: 5px 13px;
font-size: 14px;
cursor: pointer;
transition: all 0.13s;
&:hover {
border-color: #2563eb;
}
&.on {
background: rgba(37, 99, 235, 0.1);
border-color: #2563eb;
color: #2563eb;
font-weight: 700;
}
}
.al-range {
width: 100%;
}
.al-hint {
font-size: 13px;
opacity: 0.5;
line-height: 1.7;
margin-top: 10px;
}
.al-go {
width: 100%;
margin-top: 14px;
border: none;
background: #2563eb;
color: #fff;
border-radius: 9px;
padding: 11px;
font-size: 16px;
font-weight: 700;
cursor: pointer;
&:disabled {
opacity: 0.5;
cursor: not-allowed;
}
&:hover:not(:disabled) {
background: #1d4ed8;
}
}
.al-error {
color: #d03050;
font-size: 14px;
margin-top: 9px;
line-height: 1.6;
}
.al-dl {
border: 1px solid rgba(128, 128, 128, 0.3);
background: #fff;
border-radius: 7px;
padding: 4px 12px;
font-size: 13.5px;
cursor: pointer;
&:hover {
border-color: #18a058;
color: #18a058;
}
}
.al-preview {
min-height: 380px;
display: flex;
align-items: center;
justify-content: center;
background: rgba(128, 128, 128, 0.05);
border-radius: 10px;
padding: 16px;
.al-img {
max-width: 100%;
max-height: 520px;
border-radius: 8px;
}
.al-img-checker {
background:
repeating-conic-gradient(rgba(128, 128, 128, 0.12) 0% 25%, transparent 0% 50%) 0 0 / 20px 20px;
}
.al-img-id {
max-height: 460px;
box-shadow: 0 4px 20px rgba(0, 0, 0, 0.18);
}
.al-empty {
font-size: 14.5px;
opacity: 0.45;
}
}
</style>