Files
it-tools-pro/src/tools/code-reader/code-reader.vue
T
personal82555 01ff133ac9 IT-TOOLS-PRO v1 - 定制版开发者工具站
12个原创工具(批量条码/二维码识别/在线翻译/OCR/面单设计/AI修图/网站收藏/PDF工具/图片工具/文档转换等)
+ 卡密授权系统(CardAuth对接,30分钟试用,换卡/撤销)
+ 体验优化(中文默认/收藏/最近使用/菜单展开/宽屏/品牌页脚)
2026-10-11 23:58:39 +08:00

473 lines
11 KiB
Vue

<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'));
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;
const height = Math.max(300, window.innerHeight - top - 12);
rootStyle.value = { height: `${height}px`, flex: '1 1 100%' };
}
let observer: ResizeObserver | undefined;
onMounted(() => {
fit();
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"
>
<div class="toolbar">
<div class="stats">
<template v-if="results.length">
识别到 {{ results.length }} 个码 · {{ elapsed }}ms
</template>
</div>
<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>
</div>
<div 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>
<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;
}
.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>