Files
it-tools-pro/src/tools/code-reader/code-reader.vue
T

956 lines
23 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 GenHistory from '@/tools/gen-history/GenHistory.vue';
import { useGenHistory } from '@/tools/gen-history/gen-history';
const genHist = useGenHistory('code-reader');
import { prepareZXingModule, readBarcodes } from 'zxing-wasm/reader';
import wasmUrl from 'zxing-wasm/reader/zxing_reader.wasm?url';
// load wasm from our own bundle instead of jsdelivr CDN (works offline / in CN)
prepareZXingModule({
overrides: {
locateFile: () => wasmUrl,
},
fireImmediately: true,
});
interface CodeResult {
format: string;
symbology: string;
contentType: string;
text: string;
}
const fileInput = ref<HTMLInputElement>();
const imageSrc = ref('');
const fileName = ref('');
const results = ref<CodeResult[]>([]);
const loading = ref(false);
const error = ref('');
const dragActive = ref(false);
const elapsed = ref(0);
function pickFile() {
fileInput.value?.click();
}
async function handleFile(file?: File | null) {
if (!file) {
return;
}
if (!file.type.startsWith('image/')) {
error.value = '请选择图片文件(png/jpg/webp/bmp 等)';
return;
}
error.value = '';
const reader = new FileReader();
reader.onload = () => {
imageSrc.value = String(reader.result ?? '');
fileName.value = file.name;
recognize(file);
};
reader.readAsDataURL(file);
}
function onInputChange(e: Event) {
const input = e.target as HTMLInputElement;
handleFile(input.files?.[0]);
input.value = '';
}
function onDrop(e: DragEvent) {
dragActive.value = false;
handleFile(e.dataTransfer?.files?.[0]);
}
// paste image from clipboard
function onPaste(e: ClipboardEvent) {
const items = e.clipboardData?.items;
if (!items) {
return;
}
for (const item of items) {
if (item.type.startsWith('image/')) {
handleFile(item.getAsFile());
return;
}
}
}
// flatten onto a white canvas first: ZXing handles transparent PNGs poorly
async function toFlattenedBlob(file: File | Blob): Promise<Blob> {
const bitmap = await createImageBitmap(file);
const canvas = document.createElement('canvas');
canvas.width = bitmap.width;
canvas.height = bitmap.height;
const ctx = canvas.getContext('2d')!;
ctx.fillStyle = '#ffffff';
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.drawImage(bitmap, 0, 0);
bitmap.close();
return new Promise(resolve => canvas.toBlob(b => resolve(b!), 'image/png'));
}
async function recognize(file: File | Blob) {
loading.value = true;
error.value = '';
results.value = [];
const start = performance.now();
try {
const flattened = await toFlattenedBlob(file);
const found = await readBarcodes(flattened, {
tryHarder: true,
tryRotate: true,
tryInvert: true,
maxNumberOfSymbols: 0, // no limit
});
results.value = found.map(r => ({
format: r.format,
symbology: r.symbology,
contentType: r.contentType,
text: r.text,
}));
if (!found.length) {
error.value = '未识别到条码/二维码,可尝试更清晰、完整(含留白)的图片';
}
else {
genHist.add({
title: found[0].text.slice(0, 60),
detail: `${found[0].format}${found.length > 1 ? ` 等 ${found.length} 个` : ''}`,
});
}
}
catch (e: any) {
error.value = `识别失败:${e?.message ?? e}`;
}
finally {
elapsed.value = Math.round(performance.now() - start);
loading.value = false;
}
}
function reRecognize() {
if (!imageSrc.value) {
return;
}
fetch(imageSrc.value)
.then(r => r.blob())
.then(blob => recognize(blob));
}
const allText = computed(() => results.value.map(r => r.text).join('\n'));
// ================= 生成二维码 =================
import QRCode from 'qrcode';
const mode = ref<'read' | 'gen'>('read');
const genText = ref('https://it.88531.cn');
const genSize = ref(512);
const genDark = ref('#000000');
const genLight = ref('#ffffff');
const genLogo = ref(''); // 本地图片 dataURL
const genLogoName = ref('');
const genLogoRatio = ref(0.22); // 中心图片占 QR 比例
const genPng = ref(''); // 生成结果 dataURL
const genScanning = ref(false);
const genScanMsg = ref('');
const genScanOk = ref(false);
const genError = ref('');
const logoInput = ref<HTMLInputElement>();
const DARK_PRESETS = ['#000000', '#165DFF', '#00B42A', '#D03050', '#722ED1', '#FF7D00'];
const LIGHT_PRESETS = ['#ffffff', '#F7F9FC', '#FFF7E8', '#E8F3FF', '#F0FFF4', '#FFF0F0'];
function pickLogo() {
logoInput.value?.click();
}
function onLogoChange(e: Event) {
const input = e.target as HTMLInputElement;
const f = input.files?.[0];
input.value = '';
if (!f) {
return;
}
if (!f.type.startsWith('image/')) {
genError.value = '中间图片请选择图片文件';
return;
}
const reader = new FileReader();
reader.onload = () => {
genLogo.value = String(reader.result ?? '');
genLogoName.value = f.name;
genError.value = '';
renderGen();
};
reader.readAsDataURL(f);
}
function removeLogo() {
genLogo.value = '';
genLogoName.value = '';
renderGen();
}
let genTimer: ReturnType<typeof setTimeout> | undefined;
function renderGenDebounced() {
clearTimeout(genTimer);
genTimer = setTimeout(renderGen, 250);
}
async function renderGen() {
genError.value = '';
genScanMsg.value = '';
const text = genText.value.trim();
if (!text) {
genPng.value = '';
return;
}
try {
// 有中心图片时必须 H 级纠错(容 ~30% 损毁)
const dataUrl = await QRCode.toDataURL(text, {
width: genSize.value,
margin: 2,
errorCorrectionLevel: genLogo.value ? 'H' : 'M',
color: { dark: genDark.value, light: genLight.value },
});
if (!genLogo.value) {
genPng.value = dataUrl;
autoScan();
return;
}
// 中心贴本地图片(白色圆角垫底,保证可扫)
const qrImg = await loadImage(dataUrl);
const canvas = document.createElement('canvas');
canvas.width = genSize.value;
canvas.height = genSize.value;
const ctx = canvas.getContext('2d')!;
ctx.drawImage(qrImg, 0, 0, canvas.width, canvas.height);
const logo = await loadImage(genLogo.value);
const side = Math.round(canvas.width * genLogoRatio.value);
// 白垫比 logo 大 12%,留静区
const pad = Math.round(side * 1.12);
const cx = canvas.width / 2;
const cy = canvas.height / 2;
ctx.fillStyle = genLight.value;
roundRect(ctx, cx - pad / 2, cy - pad / 2, pad, pad, Math.round(pad * 0.18));
ctx.fill();
const k = Math.min(side / logo.width, side / logo.height);
const lw = Math.round(logo.width * k);
const lh = Math.round(logo.height * k);
ctx.drawImage(logo, cx - lw / 2, cy - lh / 2, lw, lh);
genPng.value = canvas.toDataURL('image/png');
autoScan();
}
catch (e: any) {
genPng.value = '';
genError.value = `生成失败:${e?.message ?? e}(内容过长?二维码上限约 2000 字符)`;
}
}
function loadImage(src: string): Promise<HTMLImageElement> {
return new Promise((resolve, reject) => {
const im = new Image();
im.onload = () => resolve(im);
im.onerror = () => reject(new Error('图片加载失败'));
im.src = src;
});
}
function roundRect(ctx: CanvasRenderingContext2D, x: number, y: number, w: number, h: number, r: number) {
ctx.beginPath();
ctx.moveTo(x + r, y);
ctx.arcTo(x + w, y, x + w, y + h, r);
ctx.arcTo(x + w, y + h, x, y + h, r);
ctx.arcTo(x, y + h, x, y, r);
ctx.arcTo(x, y, x + w, y, r);
ctx.closePath();
}
// 生成后自扫验证:复用本页 ZXing,证明颜色/中心图片没破坏可扫性
async function autoScan() {
if (!genPng.value) {
return;
}
genScanning.value = true;
genScanMsg.value = '';
try {
const blob = await (await fetch(genPng.value)).blob();
const found = await readBarcodes(blob, { tryHarder: true, tryInvert: true, maxNumberOfSymbols: 0 });
const hit = found.find(f => f.text === genText.value.trim());
if (hit) {
genScanOk.value = true;
genScanMsg.value = `可正常扫出(${hit.format})· 与输入内容一致`;
}
else if (found.length) {
genScanOk.value = false;
genScanMsg.value = `扫出内容与输入不一致,请检查颜色对比度`;
}
else {
genScanOk.value = false;
genScanMsg.value = '扫不出来:请增大前景/背景对比度,或缩小中心图片比例';
}
genHist.add({ title: genText.value.trim().slice(0, 60), detail: `生成 ${genSize.value}px${genLogo.value ? ' + 中心图片' : ''}` });
}
catch (e: any) {
genScanOk.value = false;
genScanMsg.value = `自扫异常:${e?.message ?? e}`;
}
finally {
genScanning.value = false;
}
}
function downloadGen() {
if (!genPng.value) {
return;
}
const a = document.createElement('a');
a.href = genPng.value;
a.download = 'qr-code.png';
a.click();
}
function clearGen() {
genText.value = '';
genLogo.value = '';
genLogoName.value = '';
genPng.value = '';
genScanMsg.value = '';
genError.value = '';
}
function setMode(m: 'read' | 'gen') {
mode.value = m;
if (m === 'gen' && !genPng.value) {
renderGen();
}
}
async function copyText(text: string) {
try {
await navigator.clipboard.writeText(text);
}
catch {
const ta = document.createElement('textarea');
ta.value = text;
document.body.appendChild(ta);
ta.select();
document.execCommand('copy');
ta.remove();
}
}
function downloadTxt() {
if (!allText.value) {
return;
}
const blob = new Blob([allText.value], { type: 'text/plain;charset=utf-8' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = 'code-results.txt';
a.click();
URL.revokeObjectURL(url);
}
function clearAll() {
imageSrc.value = '';
fileName.value = '';
results.value = [];
error.value = '';
}
// fit viewport: no page scroll
const rootEl = ref<HTMLElement>();
const rootStyle = ref<Record<string, string>>({});
function fit() {
const el = rootEl.value;
if (!el) {
return;
}
const top = el.getBoundingClientRect().top;
// 高度按「内容滚动区底边」计算,而不是 window.innerHeight:
// 功能页底部预留了固定页脚的空间,用视口高度会把内容撑到页脚下方,既遮挡又产生滚动条
const scroller = el.closest('.n-layout-scroll-container');
const bottom = scroller
? scroller.getBoundingClientRect().bottom - Number.parseFloat(getComputedStyle(scroller).paddingBottom || '0')
: window.innerHeight - 12;
const height = Math.max(300, bottom - top);
rootStyle.value = { height: `${height}px`, flex: '1 1 100%' };
}
let observer: ResizeObserver | undefined;
onMounted(() => {
fit();
renderGen();
window.addEventListener('resize', fit);
window.addEventListener('paste', onPaste);
observer = new ResizeObserver(() => fit());
if (rootEl.value) {
observer.observe(rootEl.value);
}
});
onUnmounted(() => {
window.removeEventListener('resize', fit);
window.removeEventListener('paste', onPaste);
observer?.disconnect();
});
</script>
<template>
<div ref="rootEl" class="cr-root" :style="rootStyle">
<input
ref="fileInput"
type="file"
accept="image/*"
style="display:none"
@change="onInputChange"
>
<input
ref="logoInput"
type="file"
accept="image/*"
style="display:none"
@change="onLogoChange"
>
<div class="toolbar">
<div class="cr-tabs">
<button type="button" :class="{ on: mode === 'read' }" @click="setMode('read')">
📷 识别
</button>
<button type="button" :class="{ on: mode === 'gen' }" @click="setMode('gen')">
🧩 生成
</button>
</div>
<div v-if="mode === 'read'" class="stats">
<template v-if="results.length">
识别到 {{ results.length }} 个码 · {{ elapsed }}ms
</template>
</div>
<template v-if="mode === 'read'">
<c-button :disabled="!imageSrc || loading" @click="reRecognize">
重新识别
</c-button>
<c-button :disabled="!results.length" @click="copyText(allText)">
复制全部
</c-button>
<c-button :disabled="!results.length" @click="downloadTxt">
下载TXT
</c-button>
<c-button @click="clearAll">
清空
</c-button>
</template>
<template v-else>
<c-button :disabled="!genPng" @click="downloadGen">
下载PNG
</c-button>
<c-button :disabled="!genText.trim() && !genLogo" @click="clearGen">
清空
</c-button>
</template>
</div>
<div v-if="mode === 'read'" class="body">
<!-- left: image -->
<div class="pane">
<div
class="dropzone"
:class="{ active: dragActive, hasImage: !!imageSrc }"
@click="pickFile"
@dragover.prevent="dragActive = true"
@dragleave.prevent="dragActive = false"
@drop.prevent="onDrop"
>
<img v-if="imageSrc" :src="imageSrc" alt="待识别图片">
<div v-else class="drop-hint">
<div class="icon">
🔍
</div>
<div>点击选择图片</div>
<div class="sub">或拖拽图片到此处 / Ctrl+V 粘贴截图</div>
<div class="sub">支持二维码、条形码混合识别</div>
</div>
</div>
<div v-if="fileName" class="hint">
{{ fileName }}
</div>
</div>
<!-- right: results -->
<div class="pane">
<n-spin :show="loading">
<div v-if="error && !results.length" class="cr-error">
{{ error }}
</div>
<div v-else-if="!results.length" class="empty">
识别结果将显示在这里
</div>
<div v-else class="results">
<div v-for="(r, i) in results" :key="i" class="result-item">
<div class="result-head">
<span class="badge">{{ r.format }}</span>
<span class="meta">{{ r.contentType }} · {{ r.symbology }}</span>
<c-button size="small" @click="copyText(r.text)">
复制
</c-button>
</div>
<div class="result-text">
{{ r.text }}
</div>
</div>
</div>
</n-spin>
<div v-if="error && results.length" class="warn">
{{ error }}
</div>
</div>
</div>
<!-- 生成面板 -->
<div v-else-if="mode === 'gen'" class="body">
<!-- left: form -->
<div class="pane gen-form">
<div class="f-sec">
<div class="f-label">
二维码内容
</div>
<textarea v-model="genText" class="gen-text" rows="4" spellcheck="false" placeholder="网址 / 文本 / 名片信息…" @input="renderGenDebounced" />
<div class="f-count">
{{ genText.length }} 字符
</div>
</div>
<div class="f-sec">
<div class="f-label">
尺寸
</div>
<div class="row">
<select v-model.number="genSize" class="sel" @change="renderGen()">
<option :value="256">
256 px
</option>
<option :value="512">
512 px
</option>
<option :value="1024">
1024 px
</option>
<option :value="2048">
2048 px(高清)
</option>
</select>
<span class="tip">输出图片边长</span>
</div>
</div>
<div class="f-sec">
<div class="f-label">
颜色
</div>
<div class="row color-row">
<span>前景</span>
<input v-model="genDark" type="color" class="color" @input="renderGenDebounced">
<span class="hex">{{ genDark }}</span>
<span>背景</span>
<input v-model="genLight" type="color" class="color" @input="renderGenDebounced">
<span class="hex">{{ genLight }}</span>
</div>
<div class="row presets-row">
<span class="tip">前景快捷</span>
<button v-for="c in DARK_PRESETS" :key="c" type="button" class="swatch" :style="{ background: c }" @click="genDark = c; renderGen()" />
<span class="tip">背景快捷</span>
<button v-for="c in LIGHT_PRESETS" :key="c" type="button" class="swatch" :style="{ background: c }" @click="genLight = c; renderGen()" />
</div>
</div>
<div class="f-sec">
<div class="f-label">
中心图片(本地图片,不上传云端)
</div>
<div class="row">
<c-button @click="pickLogo">
{{ genLogo ? '更换图片' : '选择图片' }}
</c-button>
<c-button v-if="genLogo" size="small" @click="removeLogo">
移除
</c-button>
<span v-if="genLogoName" class="tip">{{ genLogoName }}</span>
</div>
<div v-if="genLogo" class="row">
<span class="tip">大小</span>
<input v-model.number="genLogoRatio" type="range" min="0.10" max="0.35" step="0.01" class="ratio" @input="renderGenDebounced">
<span class="tip">{{ Math.round(genLogoRatio * 100) }}%(自动 H 级纠错)</span>
</div>
</div>
</div>
<!-- right: preview -->
<div class="pane">
<div class="gen-preview">
<img v-if="genPng" :src="genPng" class="qr-img" alt="二维码预览">
<div v-else class="empty">
输入内容后自动生成
</div>
</div>
<div v-if="genError" class="cr-error">
{{ genError }}
</div>
<div class="scan-line">
<n-spin v-if="genScanning" :size="14" />
<span v-if="genScanMsg" class="scan-msg" :class="{ ok: genScanOk }">{{ genScanMsg }}</span>
<span v-else-if="!genScanning && genPng" class="scan-msg">自扫验证中…</span>
</div>
</div>
</div>
<GenHistory tool="code-reader" position="bottom" label="识别记录" />
</div>
</template>
<style lang="less" scoped>
.cr-root {
display: flex;
flex-direction: column;
width: 100%;
min-height: 0;
box-sizing: border-box;
}
.toolbar {
display: flex;
flex-direction: row;
align-items: center;
justify-content: flex-end;
gap: 10px;
padding-bottom: 12px;
flex-shrink: 0;
.stats {
margin-right: auto;
font-size: 13px;
opacity: 0.65;
}
}
.body {
display: flex;
flex-direction: row;
gap: 16px;
flex: 1;
min-height: 0;
@media (max-width: 760px) {
flex-direction: column;
}
}
.pane {
flex: 1;
min-width: 0;
min-height: 0;
display: flex;
flex-direction: column;
}
.dropzone {
flex: 1;
min-height: 180px;
border: 2px dashed rgba(128, 128, 128, 0.45);
border-radius: 10px;
display: flex;
align-items: center;
justify-content: center;
cursor: pointer;
overflow: hidden;
transition: border-color 0.2s, background-color 0.2s;
box-sizing: border-box;
&:hover,
&.active {
border-color: #18a058;
background-color: rgba(24, 160, 88, 0.06);
}
img {
max-width: 100%;
max-height: 100%;
object-fit: contain;
}
.drop-hint {
text-align: center;
font-size: 14px;
opacity: 0.75;
.icon {
font-size: 40px;
margin-bottom: 8px;
}
.sub {
font-size: 12px;
opacity: 0.6;
margin-top: 6px;
}
}
}
.hint {
font-size: 12px;
opacity: 0.55;
margin-top: 6px;
flex-shrink: 0;
}
.empty {
display: flex;
align-items: center;
justify-content: center;
height: 100%;
min-height: 150px;
border: 1px solid rgba(128, 128, 128, 0.3);
border-radius: 6px;
opacity: 0.5;
font-size: 14px;
}
.cr-error {
color: #d03050;
font-size: 13px;
padding: 12px;
border: 1px solid rgba(208, 48, 80, 0.35);
border-radius: 6px;
}
.warn {
font-size: 12px;
color: #d03050;
margin-top: 8px;
opacity: 0.85;
}
.results {
height: 100%;
overflow-y: auto;
border: 1px solid rgba(128, 128, 128, 0.3);
border-radius: 6px;
padding: 8px;
box-sizing: border-box;
display: flex;
flex-direction: column;
gap: 8px;
}
.cr-tabs {
display: flex;
gap: 6px;
button {
border: 1.5px solid rgba(128, 128, 128, 0.35);
background: transparent;
color: inherit;
font-size: 13.5px;
font-weight: 600;
padding: 6px 18px;
border-radius: 8px;
cursor: pointer;
transition: all 0.15s;
&.on {
border-color: #18a058;
background: #18a058;
color: #fff;
}
}
}
.gen-form {
overflow-y: auto;
gap: 14px;
padding-right: 4px;
box-sizing: border-box;
}
.f-sec {
display: flex;
flex-direction: column;
gap: 7px;
}
.f-label {
font-size: 13px;
font-weight: 700;
opacity: 0.85;
}
.gen-text {
width: 100%;
border: 1px solid rgba(128, 128, 128, 0.4);
border-radius: 8px;
padding: 9px 11px;
font-size: 13px;
line-height: 1.55;
background: transparent;
color: inherit;
resize: vertical;
box-sizing: border-box;
&:focus {
outline: none;
border-color: #18a058;
}
}
.f-count {
font-size: 11px;
opacity: 0.45;
text-align: right;
}
.row {
display: flex;
align-items: center;
gap: 9px;
flex-wrap: wrap;
font-size: 12.5px;
}
.sel {
border: 1px solid rgba(128, 128, 128, 0.4);
border-radius: 7px;
padding: 6px 9px;
font-size: 12.5px;
background: transparent;
color: inherit;
}
.tip {
opacity: 0.5;
font-size: 11.5px;
}
.color {
width: 34px;
height: 28px;
border: 1px solid rgba(128, 128, 128, 0.35);
border-radius: 6px;
padding: 2px;
background: transparent;
cursor: pointer;
}
.hex {
font-family: ui-monospace, Menlo, Consolas, monospace;
font-size: 11.5px;
opacity: 0.55;
}
.swatch {
width: 20px;
height: 20px;
border: 2px solid rgba(128, 128, 128, 0.4);
border-radius: 50%;
cursor: pointer;
padding: 0;
&:hover {
border-color: #18a058;
transform: scale(1.1);
}
}
.presets-row {
gap: 6px;
}
.ratio {
flex: 1;
min-width: 100px;
accent-color: #18a058;
}
.gen-preview {
flex: 1;
min-height: 180px;
border: 1px dashed rgba(128, 128, 128, 0.45);
border-radius: 10px;
display: flex;
align-items: center;
justify-content: center;
overflow: hidden;
padding: 10px;
box-sizing: border-box;
.qr-img {
max-width: 100%;
max-height: calc(100vh - 420px);
min-height: 160px;
object-fit: contain;
}
}
.scan-line {
display: flex;
align-items: center;
gap: 8px;
flex-shrink: 0;
min-height: 26px;
font-size: 12.5px;
margin-top: 8px;
.scan-msg {
color: #d03050;
}
.scan-msg.ok {
color: #18a058;
font-weight: 600;
}
}
.result-item {
border: 1px solid rgba(128, 128, 128, 0.22);
border-radius: 6px;
padding: 8px 10px;
user-select: text;
.result-head {
display: flex;
align-items: center;
gap: 8px;
margin-bottom: 6px;
.badge {
background: rgba(24, 160, 88, 0.14);
color: #18a058;
font-size: 12px;
font-weight: 600;
padding: 1px 8px;
border-radius: 10px;
white-space: nowrap;
}
.meta {
font-size: 11px;
opacity: 0.5;
flex: 1;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
}
.result-text {
font-size: 13.5px;
line-height: 1.6;
word-break: break-all;
white-space: pre-wrap;
}
}
</style>