Files
it-tools-pro/src/tools/image-tools/image-tools.vue
T

1369 lines
39 KiB
Vue
Raw Blame History

This file contains ambiguous Unicode characters
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 { useUserAuth } from '@/composable/user-auth';
import exifr from 'exifr';
import QRCode from 'qrcode';
import { prepareZXingModule, readBarcodes } from 'zxing-wasm/reader';
import wasmUrl from 'zxing-wasm/reader/zxing_reader.wasm?url';
import { useStorage } from '@vueuse/core';
import GenHistory from '@/tools/gen-history/GenHistory.vue';
import { useGenHistory } from '@/tools/gen-history/gen-history';
prepareZXingModule({ overrideWasmUrl: wasmUrl });
const genHist = useGenHistory('image-tools');
interface TabDef { key: string; label: string; desc: string; multi?: boolean; noFile?: boolean }
const TABS: TabDef[] = [
{ key: 'compress', label: '图片压缩', desc: '压缩图片体积(JPEG/WebP 质量可调)' },
{ key: 'convert', label: '图片转换', desc: '转换图片格式:PNG / JPEG / WebP' },
{ key: 'resize', label: '调整尺寸', desc: '按像素调整图片宽高,可保持比例' },
{ key: 'crop', label: '裁剪', desc: '按坐标区域裁剪图片' },
{ key: 'rotate', label: '旋转', desc: '旋转或翻转图片' },
{ key: 'filter', label: '滤镜', desc: '为图片应用滤镜效果(灰度/复古/模糊等)' },
{ key: 'mosaic', label: '打码', desc: '在图片上拖拽框选区域,马赛克或涂黑打码' },
{ key: 'exif', label: 'EXIF 查看', desc: '查看拍摄设备、时间、参数等 EXIF 信息' },
{ key: 'qrgen', label: '二维码生成', desc: '把文字/链接生成为二维码图片', noFile: true },
{ key: 'qrread', label: '二维码识别', desc: '识别图片中的二维码/条码内容' },
{ key: 'watermark', label: '加水印', desc: '为图片添加文字水印(居中或平铺)' },
{ key: 'stitch', label: '多图拼接', desc: '把多张图片水平或垂直拼接为一张', multi: true },
];
const tabKey = useStorage('image-tools:tab', 'compress');
const tab = computed(() => TABS.find(t => t.key === tabKey.value) ?? TABS[0]);
// options
const quality = useStorage('image-tools:quality', 80);
const convFormat = useStorage<'image/png' | 'image/jpeg' | 'image/webp'>('image-tools:format', 'image/webp');
const rsW = useStorage('image-tools:rs-w', 800);
const rsH = useStorage('image-tools:rs-h', 600);
const rsKeep = useStorage('image-tools:rs-keep', true);
const cropX = useStorage('image-tools:crop-x', 0);
const cropY = useStorage('image-tools:crop-y', 0);
const cropW = useStorage('image-tools:crop-w', 200);
const cropH = useStorage('image-tools:crop-h', 200);
const rotAngle = useStorage('image-tools:rot', 90);
const rotFree = useStorage('image-tools:rot-free', 0);
const filterKind = useStorage('image-tools:filter', 'grayscale');
const mosaicKind = useStorage<'pixel' | 'black'>('image-tools:mosaic-kind', 'pixel');
const qrText = useStorage('image-tools:qr-text', 'https://it.88531.cn');
const qrSize = useStorage('image-tools:qr-size', 300);
const wmText = useStorage('image-tools:wm-text', '© IT-TOOLS-PRO');
const wmMode = useStorage<'center' | 'tile'>('image-tools:wm-mode', 'tile');
const wmOpacity = useStorage('image-tools:wm-opacity', 30);
const stitchDir = useStorage<'h' | 'v'>('image-tools:stitch-dir', 'h');
const stitchGap = useStorage('image-tools:stitch-gap', 0);
const FILTERS: Record<string, string> = {
none: '原图',
grayscale: '灰度',
bw: '黑白',
vintage: '复古',
bright: '明亮',
blur: '轻微模糊',
invert: '反色',
warm: '暖色调',
};
const MAX_MB = 50;
const files = ref<File[]>([]);
const fileInput = ref<HTMLInputElement>();
const dragActive = ref(false);
const busy = ref(false);
const statusMsg = ref('');
const errorMsg = ref('');
const outputUrl = ref('');
const outputName = ref('');
const outputSize = ref(0);
const exifInfo = ref<{ k: string; v: string }[]>([]);
const qrResult = ref('');
const qrCopied = ref(false);
const decodeText = ref('');
// main image preview + mosaic canvas
const mainImg = ref<HTMLImageElement | null>(null);
const mosaicCanvas = ref<HTMLCanvasElement>();
const mosaicBox = ref<{ x1: number; y1: number; x2: number; y2: number } | null>(null);
let mosaicDrawing = false;
const displayScale = ref(1);
function pickFiles() {
fileInput.value?.click();
}
function onInputChange(e: Event) {
const input = e.target as HTMLInputElement;
addFiles(Array.from(input.files ?? []));
input.value = '';
}
function onDrop(e: DragEvent) {
dragActive.value = false;
addFiles(Array.from(e.dataTransfer?.files ?? []));
}
const { cloudUpload } = useUserAuth();
function addFiles(list: File[]) {
for (const f of list) {
cloudUpload(f, 'image-tools').catch(() => {});
}
const imgs = list.filter(f => f.type.startsWith('image/'));
if (!imgs.length) {
errorMsg.value = '请选择图片文件';
return;
}
for (const f of imgs) {
if (f.size > MAX_MB * 1024 * 1024) {
errorMsg.value = `${f.name} 超过 ${MAX_MB}MB 上限`;
return;
}
}
errorMsg.value = '';
files.value = tab.value.multi ? [...files.value, ...imgs] : imgs.slice(0, 1);
loadMainImage();
}
function loadMainImage() {
resultUrl.value = '';
exifInfo.value = [];
qrResult.value = '';
decodeText.value = '';
mosaicBox.value = null;
mainImg.value = null;
const f = files.value[0];
if (!f || tab.value.noFile) {
return;
}
const url = URL.createObjectURL(f);
const img = new Image();
img.onload = () => {
mainImg.value = img;
nextTick(drawMosaicCanvas);
};
img.src = url;
}
function removeFile(i: number) {
files.value.splice(i, 1);
loadMainImage();
}
function onTabChange(t: TabDef) {
tabKey.value = t.key;
files.value = [];
errorMsg.value = '';
statusMsg.value = '';
clearOutput();
loadMainImage();
}
function clearOutput() {
if (outputUrl.value) {
URL.revokeObjectURL(outputUrl.value);
}
outputUrl.value = '';
outputName.value = '';
outputSize.value = 0;
exifInfo.value = [];
}
// result preview
const resultUrl = ref('');
const resultDim = ref('');
function setOutput(blob: Blob, name: string, record?: { title: string; detail?: string }) {
clearOutput();
outputUrl.value = URL.createObjectURL(blob);
resultUrl.value = outputUrl.value;
outputName.value = name;
outputSize.value = blob.size;
if (record) {
genHist.add(record);
}
}
function downloadOutput() {
if (!outputUrl.value) {
return;
}
const a = document.createElement('a');
a.href = outputUrl.value;
a.download = outputName.value;
a.click();
}
function fmtSize(n: number): string {
return n > 1024 * 1024 ? `${(n / 1024 / 1024).toFixed(1)} MB` : `${Math.round(n / 1024)} KB`;
}
function extOf(mime: string): string {
return mime === 'image/png' ? 'png' : mime === 'image/webp' ? 'webp' : 'jpg';
}
function baseName(f?: File): string {
return (f?.name ?? 'image').replace(/\.[^.]+$/, '');
}
function canvasToBlob(canvas: HTMLCanvasElement, mime: string, q: number): Promise<Blob> {
return new Promise(resolve => canvas.toBlob(b => resolve(b!), mime, q / 100));
}
function loadCanvasFromImg(img: HTMLImageElement): HTMLCanvasElement {
const c = document.createElement('canvas');
c.width = img.naturalWidth;
c.height = img.naturalHeight;
c.getContext('2d')!.drawImage(img, 0, 0);
return c;
}
// ---------- mosaic canvas (interactive) ----------
function drawMosaicCanvas() {
const c = mosaicCanvas.value;
const img = mainImg.value;
if (!c || !img) {
return;
}
const maxW = 640;
const scale = Math.min(1, maxW / img.naturalWidth);
displayScale.value = scale;
c.width = Math.round(img.naturalWidth * scale);
c.height = Math.round(img.naturalHeight * scale);
const ctx = c.getContext('2d')!;
ctx.drawImage(img, 0, 0, c.width, c.height);
drawMosaicBox();
}
function drawMosaicBox() {
const c = mosaicCanvas.value;
const box = mosaicBox.value;
if (!c) {
return;
}
drawMosaicCanvasBase();
if (box) {
const ctx = c.getContext('2d')!;
ctx.strokeStyle = '#d03050';
ctx.lineWidth = 2;
ctx.setLineDash([6, 4]);
ctx.strokeRect(box.x1, box.y1, box.x2 - box.x1, box.y2 - box.y1);
ctx.setLineDash([]);
ctx.fillStyle = 'rgba(208, 48, 80, 0.18)';
ctx.fillRect(box.x1, box.y1, box.x2 - box.x1, box.y2 - box.y1);
}
}
function drawMosaicCanvasBase() {
const c = mosaicCanvas.value;
const img = mainImg.value;
if (!c || !img) {
return;
}
const ctx = c.getContext('2d')!;
ctx.clearRect(0, 0, c.width, c.height);
ctx.drawImage(img, 0, 0, c.width, c.height);
}
function mosaicPos(e: MouseEvent) {
const c = mosaicCanvas.value!;
const r = c.getBoundingClientRect();
return { x: e.clientX - r.left, y: e.clientY - r.top };
}
function onMosaicDown(e: MouseEvent) {
if (tab.value.key !== 'mosaic') {
return;
}
mosaicDrawing = true;
const p = mosaicPos(e);
mosaicBox.value = { x1: p.x, y1: p.y, x2: p.x, y2: p.y };
}
function onMosaicMove(e: MouseEvent) {
if (!mosaicDrawing) {
return;
}
const p = mosaicPos(e);
const box = mosaicBox.value;
if (box) {
box.x2 = p.x;
box.y2 = p.y;
drawMosaicBox();
}
}
function onMosaicUp() {
mosaicDrawing = false;
}
// ---------- actions ----------
async function execute() {
errorMsg.value = '';
statusMsg.value = '';
const k = tab.value.key;
if (k === 'qrgen') {
await doQrGen();
return;
}
if (!files.value.length) {
errorMsg.value = '请先选择图片';
return;
}
busy.value = true;
statusMsg.value = '处理中…';
const start = performance.now();
try {
if (k === 'compress') {
await doCompress();
}
else if (k === 'convert') {
await doConvert();
}
else if (k === 'resize') {
await doResize();
}
else if (k === 'crop') {
await doCrop();
}
else if (k === 'rotate') {
await doRotate();
}
else if (k === 'filter') {
await doFilter();
}
else if (k === 'mosaic') {
await doMosaic();
}
else if (k === 'exif') {
await doExif();
}
else if (k === 'qrread') {
await doQrRead();
}
else if (k === 'watermark') {
await doWatermark();
}
else if (k === 'stitch') {
await doStitch();
}
const ms = Math.round(performance.now() - start);
statusMsg.value = `完成,用时 ${ms}ms`;
}
catch (e: any) {
errorMsg.value = `处理失败:${e?.message ?? e}`;
statusMsg.value = '';
}
finally {
busy.value = false;
}
}
async function doCompress() {
const img = mainImg.value!;
const c = loadCanvasFromImg(img);
const blob = await canvasToBlob(c, 'image/jpeg', quality.value);
const name = `${baseName(files.value[0])}-compressed.jpg`;
setOutput(blob, name, {
title: `压缩 ${files.value[0].name}`,
detail: `${fmtSize(files.value[0].size)} → ${fmtSize(blob.size)}(质量${quality.value})`,
});
resultDim.value = `${c.width}×${c.height}`;
}
async function doConvert() {
const img = mainImg.value!;
const c = loadCanvasFromImg(img);
const blob = await canvasToBlob(c, convFormat.value, quality.value);
const name = `${baseName(files.value[0])}.${extOf(convFormat.value)}`;
setOutput(blob, name, {
title: `转换格式 ${files.value[0].name}`,
detail: `→ ${extOf(convFormat.value).toUpperCase()} · ${fmtSize(blob.size)}`,
});
resultDim.value = `${c.width}×${c.height}`;
}
async function doResize() {
const img = mainImg.value!;
let w = Math.max(1, Math.round(rsW.value));
let h = Math.max(1, Math.round(rsH.value));
if (rsKeep.value) {
const r = img.naturalHeight / img.naturalWidth;
h = Math.round(w * r);
}
const c = document.createElement('canvas');
c.width = w;
c.height = h;
c.getContext('2d')!.drawImage(img, 0, 0, w, h);
const blob = await canvasToBlob(c, files.value[0].type === 'image/png' ? 'image/png' : 'image/jpeg', 92);
setOutput(blob, `${baseName(files.value[0])}-${w}x${h}.${extOf(blob.type)}`, {
title: `调整尺寸 ${files.value[0].name}`,
detail: `${img.naturalWidth}×${img.naturalHeight} → ${w}×${h}`,
});
resultDim.value = `${w}×${h}`;
}
async function doCrop() {
const img = mainImg.value!;
const x = Math.max(0, Math.round(cropX.value));
const y = Math.max(0, Math.round(cropY.value));
const w = Math.min(img.naturalWidth - x, Math.max(1, Math.round(cropW.value)));
const h = Math.min(img.naturalHeight - y, Math.max(1, Math.round(cropH.value)));
const c = document.createElement('canvas');
c.width = w;
c.height = h;
c.getContext('2d')!.drawImage(img, x, y, w, h, 0, 0, w, h);
const blob = await canvasToBlob(c, files.value[0].type === 'image/png' ? 'image/png' : 'image/jpeg', 92);
setOutput(blob, `${baseName(files.value[0])}-crop.${extOf(blob.type)}`, {
title: `裁剪 ${files.value[0].name}`,
detail: `区域 (${x},${y}) ${w}×${h}`,
});
resultDim.value = `${w}×${h}`;
}
async function doRotate() {
const img = mainImg.value!;
const total = ((rotAngle.value + rotFree.value) % 360 + 360) % 360;
const swap = total === 90 || total === 270;
const c = document.createElement('canvas');
c.width = swap ? img.naturalHeight : img.naturalWidth;
c.height = swap ? img.naturalWidth : img.naturalHeight;
const ctx = c.getContext('2d')!;
ctx.translate(c.width / 2, c.height / 2);
ctx.rotate((total * Math.PI) / 180);
ctx.drawImage(img, -img.naturalWidth / 2, -img.naturalHeight / 2);
const blob = await canvasToBlob(c, files.value[0].type === 'image/png' ? 'image/png' : 'image/jpeg', 92);
setOutput(blob, `${baseName(files.value[0])}-rot${total}.${extOf(blob.type)}`, {
title: `旋转 ${total}°`,
detail: `${files.value[0].name} · ${c.width}×${c.height}`,
});
resultDim.value = `${c.width}×${c.height}`;
}
async function doFilter() {
const img = mainImg.value!;
const c = document.createElement('canvas');
c.width = img.naturalWidth;
c.height = img.naturalHeight;
const ctx = c.getContext('2d')!;
const css: Record<string, string> = {
none: 'none',
grayscale: 'grayscale(1)',
bw: 'grayscale(1) contrast(2)',
vintage: 'sepia(0.8) contrast(0.9) brightness(1.05)',
bright: 'brightness(1.25) saturate(1.1)',
blur: 'blur(2px)',
invert: 'invert(1)',
warm: 'sepia(0.35) saturate(1.4) hue-rotate(-10deg)',
};
ctx.filter = css[filterKind.value] ?? 'none';
ctx.drawImage(img, 0, 0);
const blob = await canvasToBlob(c, 'image/jpeg', 92);
setOutput(blob, `${baseName(files.value[0])}-${filterKind.value}.jpg`, {
title: `滤镜:${FILTERS[filterKind.value]}`,
detail: files.value[0].name,
});
resultDim.value = `${c.width}×${c.height}`;
}
async function doMosaic() {
const img = mainImg.value!;
const box = mosaicBox.value;
if (!box || Math.abs(box.x2 - box.x1) < 4 || Math.abs(box.y2 - box.y1) < 4) {
throw new Error('请先在图片上拖拽框选打码区域');
}
const s = displayScale.value;
const rx = Math.round(Math.min(box.x1, box.x2) / s);
const ry = Math.round(Math.min(box.y1, box.y2) / s);
const rw = Math.round(Math.abs(box.x2 - box.x1) / s);
const rh = Math.round(Math.abs(box.y2 - box.y1) / s);
const c = loadCanvasFromImg(img);
const ctx = c.getContext('2d')!;
if (mosaicKind.value === 'black') {
ctx.fillStyle = '#000';
ctx.fillRect(rx, ry, rw, rh);
}
else {
const block = 16;
const tiny = document.createElement('canvas');
tiny.width = Math.max(1, Math.round(rw / block));
tiny.height = Math.max(1, Math.round(rh / block));
const tctx = tiny.getContext('2d')!;
tctx.imageSmoothingEnabled = true;
tctx.drawImage(c, rx, ry, rw, rh, 0, 0, tiny.width, tiny.height);
ctx.imageSmoothingEnabled = false;
ctx.drawImage(tiny, 0, 0, tiny.width, tiny.height, rx, ry, rw, rh);
ctx.imageSmoothingEnabled = true;
}
const blob = await canvasToBlob(c, 'image/jpeg', 92);
setOutput(blob, `${baseName(files.value[0])}-mosaic.jpg`, {
title: `打码(${mosaicKind.value === 'black' ? '涂黑' : '马赛克'})`,
detail: `${files.value[0].name} · 区域 ${rw}×${rh}`,
});
resultDim.value = `${c.width}×${c.height}`;
}
async function doExif() {
const f = files.value[0];
const data = await exifr.parse(f, { gps: true }).catch(() => null);
const rows: { k: string; v: string }[] = [];
if (!data) {
rows.push({ k: '提示', v: '未读取到 EXIF 信息(PNG/WebP 或截图通常没有)' });
}
else {
const map: [string, string][] = [
['相机品牌', data.Make],
['相机型号', data.Model],
['镜头', data.LensModel],
['拍摄时间', data.DateTimeOriginal ? String(data.DateTimeOriginal) : undefined],
['光圈', data.FNumber ? `f/${data.FNumber}` : undefined],
['快门', data.ExposureTime ? `${data.ExposureTime}s` : undefined],
['ISO', data.ISO ? String(data.ISO) : undefined],
['焦距', data.FocalLength ? `${data.FocalLength}mm` : undefined],
['方向', data.Orientation ? String(data.Orientation) : undefined],
['图像宽度', data.ExifImageWidth ? `${data.ExifImageWidth}px` : undefined],
['图像高度', data.ExifImageHeight ? `${data.ExifImageHeight}px` : undefined],
['GPS', data.latitude ? `${data.latitude.toFixed(5)}, ${data.longitude.toFixed(5)}` : undefined],
['软件', data.Software],
['色彩空间', data.ColorSpace],
];
for (const [k, v] of map) {
if (v !== undefined && v !== '') {
rows.push({ k, v: String(v) });
}
}
}
exifInfo.value = rows;
resultUrl.value = '';
genHist.add({ title: `EXIF:${f.name}`, detail: rows.length > 1 ? `${rows.length} 项信息` : '无 EXIF' });
}
async function doQrGen() {
const text = qrText.value.trim();
if (!text) {
throw new Error('请输入文字或链接');
}
const url = await QRCode.toDataURL(text, { width: qrSize.value, margin: 2, color: { dark: '#000000', light: '#ffffff' } });
const blob = await (await fetch(url)).blob();
setOutput(blob, 'qrcode.png', {
title: `生成二维码:${text.slice(0, 40)}`,
detail: `${qrSize.value}px`,
});
resultDim.value = `${qrSize.value}×${qrSize.value}`;
}
async function doQrRead() {
const f = files.value[0];
const bytes = new Uint8Array(await f.arrayBuffer());
const found = await readBarcodes(bytes, { tryHarder: true, maxNumberOfSymbols: 0 });
if (!found.length) {
throw new Error('未识别到二维码/条码,可尝试更清晰的图片');
}
decodeText.value = found.map(r => r.text).join('\n');
genHist.add({ title: found[0].text.slice(0, 60), detail: `${found[0].format}${found.length > 1 ? ` 等 ${found.length} 个` : ''}` });
statusMsg.value = `识别成功,共 ${found.length} 个`;
}
async function copyDecode() {
try {
await navigator.clipboard.writeText(decodeText.value);
qrCopied.value = true;
setTimeout(() => (qrCopied.value = false), 1500);
}
catch { /* ignore */ }
}
async function doWatermark() {
const img = mainImg.value!;
const text = wmText.value.trim();
if (!text) {
throw new Error('请输入水印文字');
}
const c = loadCanvasFromImg(img);
const ctx = c.getContext('2d')!;
const size = Math.max(16, Math.round(Math.min(c.width, c.height) / 16));
ctx.font = `${size}px sans-serif`;
ctx.fillStyle = `rgba(255,255,255,${wmOpacity.value / 100})`;
ctx.strokeStyle = `rgba(0,0,0,${wmOpacity.value / 200})`;
ctx.textBaseline = 'middle';
if (wmMode.value === 'center') {
const tw = ctx.measureText(text).width;
ctx.fillText(text, (c.width - tw) / 2, c.height / 2);
ctx.strokeText(text, (c.width - tw) / 2, c.height / 2);
}
else {
const tw = ctx.measureText(text).width;
const stepX = tw + size * 3;
const stepY = size * 4;
for (let y = stepY / 2; y < c.height; y += stepY) {
for (let x = -tw / 2; x < c.width + tw; x += stepX) {
ctx.fillText(text, x, y);
ctx.strokeText(text, x, y);
}
}
}
const blob = await canvasToBlob(c, 'image/jpeg', 92);
setOutput(blob, `${baseName(files.value[0])}-wm.jpg`, {
title: `加水印「${text.slice(0, 20)}」`,
detail: `${wmMode.value === 'center' ? '居中' : '平铺'} · ${files.value[0].name}`,
});
resultDim.value = `${c.width}×${c.height}`;
}
async function doStitch() {
if (files.value.length < 2) {
throw new Error('请至少选择 2 张图片');
}
const imgs: HTMLImageElement[] = [];
for (const f of files.value) {
imgs.push(await new Promise((resolve, reject) => {
const url = URL.createObjectURL(f);
const im = new Image();
im.onload = () => resolve(im);
im.onerror = () => reject(new Error(`${f.name} 加载失败`));
im.src = url;
}));
}
const gap = Math.max(0, stitchGap.value);
let canvas: HTMLCanvasElement;
if (stitchDir.value === 'h') {
const maxH = Math.max(...imgs.map(i => i.naturalHeight));
const totalW = imgs.reduce((s, i) => s + Math.round(i.naturalWidth * (maxH / i.naturalHeight)), 0) + gap * (imgs.length - 1);
canvas = document.createElement('canvas');
canvas.width = totalW;
canvas.height = maxH;
const ctx = canvas.getContext('2d')!;
ctx.fillStyle = '#ffffff';
ctx.fillRect(0, 0, totalW, maxH);
let x = 0;
for (const im of imgs) {
const w = Math.round(im.naturalWidth * (maxH / im.naturalHeight));
ctx.drawImage(im, x, 0, w, maxH);
x += w + gap;
}
}
else {
const maxW = Math.max(...imgs.map(i => i.naturalWidth));
const totalH = imgs.reduce((s, i) => s + Math.round(i.naturalHeight * (maxW / i.naturalWidth)), 0) + gap * (imgs.length - 1);
canvas = document.createElement('canvas');
canvas.width = maxW;
canvas.height = totalH;
const ctx = canvas.getContext('2d')!;
ctx.fillStyle = '#ffffff';
ctx.fillRect(0, 0, maxW, totalH);
let y = 0;
for (const im of imgs) {
const h = Math.round(im.naturalHeight * (maxW / im.naturalWidth));
ctx.drawImage(im, 0, y, maxW, h);
y += h + gap;
}
}
const blob = await canvasToBlob(canvas, 'image/jpeg', 92);
setOutput(blob, `stitched-${imgs.length}.jpg`, {
title: `拼接 ${imgs.length} 张图片`,
detail: `${stitchDir.value === 'h' ? '水平' : '垂直'} · ${canvas.width}×${canvas.height}`,
});
resultDim.value = `${canvas.width}×${canvas.height}`;
}
// fit viewport
const rootEl = ref<HTMLElement>();
const rootStyle = ref<Record<string, string>>({});
function fit() {
const el = rootEl.value;
if (!el) {
return;
}
const top = el.getBoundingClientRect().top;
const height = Math.max(360, window.innerHeight - top - 12);
rootStyle.value = { height: `${height}px`, flex: '1 1 100%' };
}
watch(tabKey, () => nextTick(drawMosaicCanvas));
onMounted(() => {
fit();
window.addEventListener('resize', fit);
});
onUnmounted(() => {
window.removeEventListener('resize', fit);
clearOutput();
});
</script>
<template>
<div ref="rootEl" class="it-root" :style="rootStyle">
<input ref="fileInput" type="file" accept="image/*" :multiple="tab.multi" style="display:none" @change="onInputChange">
<!-- head -->
<div class="it-head">
<span class="it-title">图片工具</span>
<span class="it-badge">🛡 本地处理</span>
<span v-if="files.length" class="it-count">已选 {{ files.length }} 张 · {{ (files.reduce((s, f) => s + f.size, 0) / 1024 / 1024).toFixed(1) }} MB</span>
</div>
<!-- tabs -->
<div class="it-tabs">
<button
v-for="t in TABS"
:key="t.key"
class="it-tab"
:class="{ active: t.key === tabKey }"
@click="onTabChange(t)"
>
{{ t.label }}
</button>
</div>
<!-- description -->
<div class="it-desc">
{{ tab.desc }}
</div>
<!-- body -->
<div class="it-body">
<!-- upload / preview area -->
<div class="it-left">
<div
v-if="!tab.noFile"
class="it-upload"
:class="{ active: dragActive, has: files.length }"
@click="!files.length && pickFiles()"
@dragover.prevent="dragActive = true"
@dragleave.prevent="dragActive = false"
@drop.prevent="onDrop"
>
<template v-if="files.length && tab.key === 'mosaic'">
<div class="it-mosaic-wrap">
<canvas
ref="mosaicCanvas"
class="it-mosaic"
@mousedown="onMosaicDown"
@mousemove="onMosaicMove"
@mouseup="onMosaicUp"
@mouseleave="onMosaicUp"
/>
</div>
</template>
<template v-else-if="files.length">
<div class="it-files">
<div v-for="(f, i) in files" :key="i" class="it-file">
<span class="it-file-name">🖼 {{ f.name }}</span>
<span class="it-file-size">{{ (f.size / 1024 / 1024).toFixed(2) }} MB<template v-if="i === 0 && mainImg"> · {{ mainImg.naturalWidth }}×{{ mainImg.naturalHeight }}</template></span>
<a href="javascript:;" class="it-file-del" @click.stop="removeFile(i)">✕</a>
</div>
<a v-if="tab.multi" href="javascript:;" class="it-add-more" @click.stop="pickFiles">+ 继续添加</a>
</div>
</template>
<template v-else>
<div class="it-upload-icon">⬆️</div>
<div class="it-upload-big">
选择图片
</div>
<div class="it-upload-sub">
点击或拖拽文件到此处
</div>
<div class="it-upload-sub">
上限 {{ MAX_MB }} MB · 全程本地处理,图片不会上传
</div>
</template>
</div>
<!-- qr gen input -->
<div v-else class="it-qrbox">
<textarea v-model="qrText" class="it-qr-input" placeholder="输入文字或链接,如 https://example.com" />
</div>
<!-- options -->
<div class="it-options">
<template v-if="tab.key === 'compress'">
<label>质量</label>
<input v-model.number="quality" type="range" min="10" max="100" class="it-range">
<span class="it-val">{{ quality }}</span>
</template>
<template v-else-if="tab.key === 'convert'">
<label>格式</label>
<button v-for="(lab, f) in { 'image/webp': 'WebP', 'image/png': 'PNG', 'image/jpeg': 'JPEG' }" :key="f" class="it-chip" :class="{ on: convFormat === f }" @click="convFormat = f as any">
{{ lab }}
</button>
</template>
<template v-else-if="tab.key === 'resize'">
<label>宽</label>
<input v-model.number="rsW" type="number" class="it-input n60">
<label>高</label>
<input v-model.number="rsH" type="number" class="it-input n60" :disabled="rsKeep">
<label class="it-check"><input v-model="rsKeep" type="checkbox"> 按原比例(自动算高)</label>
</template>
<template v-else-if="tab.key === 'crop'">
<label>X</label><input v-model.number="cropX" type="number" class="it-input n60">
<label>Y</label><input v-model.number="cropY" type="number" class="it-input n60">
<label>宽</label><input v-model.number="cropW" type="number" class="it-input n60">
<label>高</label><input v-model.number="cropH" type="number" class="it-input n60">
</template>
<template v-else-if="tab.key === 'rotate'">
<button v-for="a in [90, 180, 270]" :key="a" class="it-chip" :class="{ on: rotAngle === a }" @click="rotAngle = a; rotFree = 0">
{{ a }}°
</button>
<label>微调</label>
<input v-model.number="rotFree" type="range" min="-45" max="45" class="it-range">
<span class="it-val">{{ rotFree }}°</span>
</template>
<template v-else-if="tab.key === 'filter'">
<button v-for="(lab, k) in FILTERS" :key="k" class="it-chip" :class="{ on: filterKind === k }" @click="filterKind = k">
{{ lab }}
</button>
</template>
<template v-else-if="tab.key === 'mosaic'">
<label>方式</label>
<button class="it-chip" :class="{ on: mosaicKind === 'pixel' }" @click="mosaicKind = 'pixel'">
马赛克
</button>
<button class="it-chip" :class="{ on: mosaicKind === 'black' }" @click="mosaicKind = 'black'">
涂黑
</button>
<span class="it-hint">在左侧图片上按住拖拽框选打码区域</span>
</template>
<template v-else-if="tab.key === 'qrgen'">
<label>尺寸</label>
<select v-model.number="qrSize" class="it-select">
<option :value="200">200px</option>
<option :value="300">300px(推荐)</option>
<option :value="500">500px</option>
<option :value="800">800px</option>
</select>
</template>
<template v-else-if="tab.key === 'watermark'">
<label>文字</label>
<input v-model="wmText" class="it-input wide" placeholder="水印文字">
<label>位置</label>
<button class="it-chip" :class="{ on: wmMode === 'tile' }" @click="wmMode = 'tile'">
平铺
</button>
<button class="it-chip" :class="{ on: wmMode === 'center' }" @click="wmMode = 'center'">
居中
</button>
<label>透明度</label>
<input v-model.number="wmOpacity" type="range" min="10" max="70" class="it-range">
<span class="it-val">{{ wmOpacity }}%</span>
</template>
<template v-else-if="tab.key === 'stitch'">
<label>方向</label>
<button class="it-chip" :class="{ on: stitchDir === 'h' }" @click="stitchDir = 'h'">
水平
</button>
<button class="it-chip" :class="{ on: stitchDir === 'v' }" @click="stitchDir = 'v'">
垂直
</button>
<label>间距</label>
<input v-model.number="stitchGap" type="range" min="0" max="40" step="2" class="it-range">
<span class="it-val">{{ stitchGap }}px</span>
</template>
</div>
</div>
<!-- result -->
<div class="it-right">
<div v-if="exifInfo.length" class="it-exif">
<div v-for="r in exifInfo" :key="r.k" class="it-exif-row">
<span class="it-exif-k">{{ r.k }}</span>
<span class="it-exif-v">{{ r.v }}</span>
</div>
</div>
<div v-else-if="decodeText" class="it-decode">
<div class="it-decode-label">识别结果</div>
<pre class="it-decode-text">{{ decodeText }}</pre>
<a href="javascript:;" class="it-copy" @click="copyDecode">{{ qrCopied ? '已复制 ✓' : '复制内容' }}</a>
</div>
<div v-else-if="resultUrl" class="it-result">
<img :src="resultUrl" alt="结果" class="it-result-img">
<div class="it-result-meta">
{{ outputName }} · {{ fmtSize(outputSize) }}<template v-if="resultDim"> · {{ resultDim }}</template>
</div>
</div>
<div v-else class="it-empty">
{{ tab.key === 'qrgen' ? '点击执行生成二维码' : '处理结果将显示在这里' }}
</div>
</div>
</div>
<div v-if="statusMsg" class="it-status">
{{ statusMsg }}
</div>
<div v-if="errorMsg" class="it-error">
{{ errorMsg }}
</div>
<!-- bottom -->
<div class="it-bottom">
<GenHistory tool="image-tools" position="bottom" label="处理记录" />
<div class="it-actions">
<c-button v-if="outputUrl" @click="downloadOutput">
⬇ 下载 {{ outputName }}
</c-button>
<c-button type="primary" class="it-exec" :disabled="busy || (!tab.noFile && !files.length)" @click="execute">
{{ busy ? '处理中…' : '⇧ 执行' }}
</c-button>
</div>
</div>
</div>
</template>
<style lang="less" scoped>
.it-root {
display: flex;
flex-direction: column;
width: 100%;
min-height: 0;
overflow: hidden;
box-sizing: border-box;
background: #fff;
border: 1px solid rgba(128, 128, 128, 0.2);
border-radius: 12px;
padding: 14px 16px;
}
.it-head {
display: flex;
align-items: center;
gap: 10px;
flex-shrink: 0;
margin-bottom: 10px;
.it-title {
font-size: 16px;
font-weight: 700;
}
.it-badge {
font-size: 11.5px;
color: #18a058;
background: rgba(24, 160, 88, 0.1);
border-radius: 999px;
padding: 2px 12px;
}
.it-count {
margin-left: auto;
font-size: 12px;
opacity: 0.55;
}
}
.it-tabs {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: 2px;
flex-shrink: 0;
padding-bottom: 10px;
.it-tab {
border: none;
background: transparent;
padding: 5px 12px;
font-size: 13px;
color: #666;
border-radius: 7px;
cursor: pointer;
transition: all 0.15s;
&.active {
background: #18a058;
color: #fff;
font-weight: 600;
}
&:not(.active):hover {
color: #18a058;
}
}
}
.it-desc {
flex-shrink: 0;
background: rgba(128, 128, 128, 0.07);
border-radius: 7px;
padding: 7px 12px;
font-size: 12.5px;
color: #666;
margin-bottom: 12px;
}
.it-body {
display: flex;
gap: 14px;
flex: 1;
min-height: 0;
@media (max-width: 860px) {
flex-direction: column;
}
}
.it-left {
flex: 1 1 55%;
min-width: 0;
min-height: 0;
display: flex;
flex-direction: column;
gap: 10px;
}
.it-right {
flex: 1 1 45%;
min-width: 0;
min-height: 0;
display: flex;
flex-direction: column;
}
.it-upload {
flex: 1;
min-height: 170px;
border: 2px dashed rgba(128, 128, 128, 0.4);
border-radius: 10px;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
cursor: pointer;
transition: border-color 0.15s;
overflow: hidden;
box-sizing: border-box;
&:hover,
&.active {
border-color: #18a058;
}
&.has {
cursor: default;
justify-content: flex-start;
padding: 10px 14px;
}
.it-upload-icon {
font-size: 36px;
}
.it-upload-big {
font-size: 16px;
font-weight: 600;
margin-top: 4px;
}
.it-upload-sub {
font-size: 12px;
opacity: 0.55;
margin-top: 4px;
}
.it-files {
width: 100%;
display: flex;
flex-direction: column;
gap: 6px;
.it-file {
display: flex;
align-items: center;
gap: 10px;
background: rgba(24, 160, 88, 0.06);
border-radius: 7px;
padding: 6px 12px;
.it-file-name {
flex: 1;
min-width: 0;
font-size: 13px;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.it-file-size {
font-size: 12px;
opacity: 0.55;
flex-shrink: 0;
}
.it-file-del {
color: #999;
text-decoration: none;
font-size: 12px;
&:hover {
color: #d03050;
}
}
}
.it-add-more {
align-self: flex-start;
color: #18a058;
text-decoration: none;
font-size: 12.5px;
padding: 2px 4px;
}
}
}
.it-mosaic-wrap {
width: 100%;
display: flex;
justify-content: center;
.it-mosaic {
max-width: 100%;
cursor: crosshair;
border-radius: 6px;
}
}
.it-qrbox {
flex: 1;
min-height: 120px;
display: flex;
.it-qr-input {
flex: 1;
border: 1px solid rgba(128, 128, 128, 0.35);
border-radius: 8px;
padding: 10px 12px;
font-size: 13px;
font-family: inherit;
resize: none;
outline: none;
&:focus {
border-color: #18a058;
}
}
}
.it-options {
display: flex;
align-items: center;
gap: 8px;
flex-wrap: wrap;
flex-shrink: 0;
min-height: 30px;
label {
font-size: 12.5px;
opacity: 0.7;
&.it-check {
display: flex;
align-items: center;
gap: 4px;
}
}
.it-range {
width: 130px;
accent-color: #18a058;
}
.it-val {
font-size: 12px;
opacity: 0.6;
min-width: 40px;
}
.it-chip {
border: 1px solid rgba(128, 128, 128, 0.35);
background: transparent;
border-radius: 6px;
padding: 4px 12px;
font-size: 12.5px;
color: #666;
cursor: pointer;
&.on {
background: #18a058;
border-color: #18a058;
color: #fff;
}
}
.it-input {
border: 1px solid rgba(128, 128, 128, 0.35);
border-radius: 6px;
padding: 4px 8px;
font-size: 12.5px;
outline: none;
&:focus {
border-color: #18a058;
}
&.n60 {
width: 62px;
}
&.wide {
width: 180px;
}
}
.it-select {
border: 1px solid rgba(128, 128, 128, 0.35);
border-radius: 6px;
padding: 4px 8px;
font-size: 12.5px;
background: #fff;
outline: none;
}
.it-hint {
font-size: 12px;
color: #18a058;
opacity: 0.85;
}
}
.it-empty {
flex: 1;
display: flex;
align-items: center;
justify-content: center;
border: 1px solid rgba(128, 128, 128, 0.2);
border-radius: 8px;
opacity: 0.45;
font-size: 13.5px;
min-height: 140px;
}
.it-result {
flex: 1;
min-height: 0;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
border: 1px solid rgba(128, 128, 128, 0.2);
border-radius: 8px;
padding: 10px;
background: repeating-conic-gradient(#f6f6f6 0% 25%, #fff 0% 50%) 50% / 16px 16px;
.it-result-img {
max-width: 100%;
max-height: 100%;
object-fit: contain;
border-radius: 4px;
}
.it-result-meta {
font-size: 12px;
opacity: 0.6;
margin-top: 8px;
}
}
.it-exif {
flex: 1;
min-height: 0;
overflow-y: auto;
border: 1px solid rgba(128, 128, 128, 0.2);
border-radius: 8px;
padding: 6px;
.it-exif-row {
display: flex;
gap: 12px;
padding: 6px 10px;
border-radius: 6px;
font-size: 13px;
&:nth-child(odd) {
background: rgba(128, 128, 128, 0.05);
}
.it-exif-k {
flex-shrink: 0;
width: 90px;
opacity: 0.6;
}
.it-exif-v {
word-break: break-all;
}
}
}
.it-decode {
flex: 1;
min-height: 0;
display: flex;
flex-direction: column;
border: 1px solid rgba(128, 128, 128, 0.2);
border-radius: 8px;
padding: 12px;
.it-decode-label {
font-size: 13px;
font-weight: 600;
margin-bottom: 6px;
}
.it-decode-text {
flex: 1;
margin: 0;
font-size: 13px;
font-family: monospace;
word-break: break-all;
white-space: pre-wrap;
overflow-y: auto;
}
.it-copy {
align-self: flex-start;
color: #18a058;
font-size: 12.5px;
text-decoration: none;
margin-top: 8px;
}
}
.it-status {
flex-shrink: 0;
font-size: 12.5px;
color: #18a058;
padding-top: 6px;
}
.it-error {
flex-shrink: 0;
font-size: 12.5px;
color: #d03050;
padding-top: 6px;
}
.it-bottom {
flex-shrink: 0;
display: flex;
align-items: flex-end;
gap: 12px;
padding-top: 8px;
.it-actions {
margin-left: auto;
display: flex;
gap: 10px;
.it-exec {
background: #18a058 !important;
color: #fff;
min-width: 110px;
font-weight: 600;
&:disabled {
opacity: 0.45;
cursor: not-allowed;
}
}
}
}
</style>