✨ 新工具「Base64图片互转」:一页双Tab双向转换,三种输入形态/魔数嗅探/三档输出格式,纯浏览器本地;隐藏「AI 无痕改字」(四处摘除,源码保留)

This commit is contained in:
personal82555 committed 2026-10-22 18:57:14 +08:00
1 parent 7f915b07ec
commit 458b508d7e
8 files changed
+501 -3

No files matched your search

@@ -0,0 +1,468 @@
<script setup lang="ts">
// Base64图片互转:Base64→图片 + 图片→Base64,一页双功能,纯浏览器本地(不上传)
type TabKey = 'b2i' | 'i2b';
const tab = ref<TabKey>('b2i');
// ---------- Tab A:Base64 → 图片 ----------
const b64Input = ref('');
const imgType = ref('auto');
const TYPES = [
{ v: 'auto', t: '自动识别' },
{ v: 'image/png', t: 'png' },
{ v: 'image/jpeg', t: 'jpeg' },
{ v: 'image/webp', t: 'webp' },
{ v: 'image/gif', t: 'gif' },
{ v: 'image/bmp', t: 'bmp' },
{ v: 'image/svg+xml', t: 'svg' },
{ v: 'image/x-icon', t: 'ico' },
];
const b2iErr = ref('');
const b2iInfo = ref('');
const b2iUrl = ref(''); // objectURL
const b2iMime = ref('');
const b2iExt = ref('png');
const EXT: Record<string, string> = {
'image/png': 'png', 'image/jpeg': 'jpg', 'image/webp': 'webp', 'image/gif': 'gif',
'image/bmp': 'bmp', 'image/svg+xml': 'svg', 'image/x-icon': 'ico', 'image/avif': 'avif',
};
/** 三种输入形态都吃:裸 base64 / data:mediatype;base64,xxx / url("data:...") */
function parseB64(raw: string): { mediatype: string; data: string } {
let s = raw.trim();
if (!s) throw new Error('请输入 Base64 内容');
// url("data:...") 或 url(data:...)
const urlM = s.match(/^url\(\s*(['"]?)([\s\S]*?)\1\s*\)$/i);
if (urlM) s = urlM[2].trim();
// data:mediatype;base64,xxx
const dataM = s.match(/^data:([^;,]+)?(?:;[^;,]*)*;base64,([\s\S]*)$/i);
if (dataM) return { mediatype: (dataM[1] || '').toLowerCase().split(';')[0], data: dataM[2].replace(/\s+/g, '') };
// 裸 base64(去空白)
return { mediatype: '', data: s.replace(/\s+/g, '') };
}
/** 魔数嗅探真实类型 */
function sniffMime(bytes: Uint8Array): string {
if (bytes.length >= 8 && bytes[0] === 0x89 && bytes[1] === 0x50 && bytes[2] === 0x4e && bytes[3] === 0x47) return 'image/png';
if (bytes.length >= 3 && bytes[0] === 0xff && bytes[1] === 0xd8 && bytes[2] === 0xff) return 'image/jpeg';
if (bytes.length >= 6 && bytes[0] === 0x47 && bytes[1] === 0x49 && bytes[2] === 0x46) return 'image/gif';
if (bytes.length >= 12 && bytes[0] === 0x52 && bytes[1] === 0x49 && bytes[2] === 0x46 && bytes[3] === 0x46 && bytes[8] === 0x57 && bytes[9] === 0x45 && bytes[10] === 0x42 && bytes[11] === 0x50) return 'image/webp';
if (bytes.length >= 2 && bytes[0] === 0x42 && bytes[1] === 0x4d) return 'image/bmp';
if (bytes.length >= 4 && bytes[0] === 0x00 && bytes[1] === 0x00 && bytes[2] === 0x01 && bytes[3] === 0x00) return 'image/x-icon';
return '';
}
function b64ToBytes(data: string): Uint8Array {
const clean = data.replace(/-/g, '+').replace(/_/g, '/');
const pad = clean.length % 4 === 0 ? '' : '='.repeat(4 - (clean.length % 4));
const bin = atob(clean + pad); // 非法字符会抛错
const out = new Uint8Array(bin.length);
for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);
return out;
}
function convertB2I() {
b2iErr.value = '';
b2iInfo.value = '';
try {
const { mediatype, data } = parseB64(b64Input.value);
const bytes = b64ToBytes(data);
if (!bytes.length) throw new Error('Base64 内容为空');
const sniffed = sniffMime(bytes);
let mime = mediatype || sniffed || (imgType.value !== 'auto' ? imgType.value : '');
if (!mime) throw new Error('无法识别图片类型:请在「图片类型」中手动选择');
if (imgType.value !== 'auto' && !mediatype) mime = imgType.value; // 手动选择优先(对应参考图提示)
// SVG 特判:无魔数,按文本嗅探
if (mime === 'image/svg+xml' && !sniffed) {
const head = new TextDecoder().decode(bytes.slice(0, 400));
if (!/\<svg|\<\?xml/i.test(head)) throw new Error('内容不是有效的 SVG');
}
const blob = new Blob([bytes], { type: mime });
const url = URL.createObjectURL(blob);
// 用 Image 验证可解码,失败给友好错误
const probe = new Image();
probe.onload = () => {
if (b2iUrl.value) URL.revokeObjectURL(b2iUrl.value);
b2iUrl.value = url;
b2iMime.value = mime;
b2iExt.value = EXT[mime] || 'bin';
b2iInfo.value = `类型 ${mime} · 尺寸 ${probe.naturalWidth}×${probe.naturalHeight} · 大小 ${(blob.size / 1024).toFixed(1)} KB`;
};
probe.onerror = () => {
URL.revokeObjectURL(url);
b2iUrl.value = '';
b2iErr.value = `解码出的 ${mime} 数据无法渲染为有效图片,请检查 Base64 是否完整或图片类型选择是否正确`;
};
probe.src = url;
}
catch (e: any) {
b2iErr.value = String(e?.message || e);
b2iUrl.value = '';
}
}
function downloadB2I() {
if (!b2iUrl.value) return;
const a = document.createElement('a');
a.href = b2iUrl.value;
a.download = `converted-image.${b2iExt.value}`;
a.click();
}
function clearB2I() {
b64Input.value = '';
b2iErr.value = '';
b2iInfo.value = '';
if (b2iUrl.value) URL.revokeObjectURL(b2iUrl.value);
b2iUrl.value = '';
}
// ---------- Tab B:图片 → Base64 ----------
const file = ref<File | null>(null);
const fileUrl = ref('');
const i2bErr = ref('');
const i2bInfo = ref('');
const outFormat = ref<'raw' | 'data' | 'css'>('data');
const b64Out = ref('');
const copied = ref(false);
const lastRaw = ref(''); // 本图的裸 base64,供格式切换重排
const lastMime = ref('');
const FORMATS = [
{ v: 'raw', t: '纯 base64' },
{ v: 'data', t: 'data: URI' },
{ v: 'css', t: 'CSS url()' },
];
function setFile(f: File) {
if (!f.type.startsWith('image/')) {
i2bErr.value = '仅支持图片文件';
return;
}
clearI2B(false);
file.value = f;
if (fileUrl.value) URL.revokeObjectURL(fileUrl.value);
fileUrl.value = URL.createObjectURL(f);
i2bErr.value = '';
}
function onPick(e: Event) {
const f = (e.target as HTMLInputElement).files?.[0];
if (f) setFile(f);
}
function onDrop(e: DragEvent) {
const f = e.dataTransfer?.files?.[0];
if (f) setFile(f);
}
function convertI2B() {
i2bErr.value = '';
b64Out.value = '';
if (!file.value) {
i2bErr.value = '请先选择图片';
return;
}
const fr = new FileReader();
fr.onload = () => {
const dataUrl = String(fr.result || '');
const m = dataUrl.match(/^data:([^;,]+)?(?:;[^;,]*)*;base64,([\s\S]*)$/);
if (!m) {
i2bErr.value = '读取图片失败';
return;
}
const mime = m[1] || file.value!.type || 'image/png';
i2bInfo.value = `原始:${file.value!.name} · ${mime} · ${(file.value!.size / 1024).toFixed(1)} KB`;
lastRaw.value = m[2];
lastMime.value = mime;
emitOut(mime, m[2]);
};
fr.onerror = () => {
i2bErr.value = '读取图片失败(文件可能被占用)';
};
fr.readAsDataURL(file.value);
}
function emitOut(mime: string, raw: string) {
if (outFormat.value === 'raw') b64Out.value = raw;
else if (outFormat.value === 'data') b64Out.value = `data:${mime};base64,${raw}`;
else b64Out.value = `url("data:${mime};base64,${raw}")`;
}
/** 切换输出格式时按记录的 mime+裸串重排(不重读文件) */
function onFormatChange() {
if (!lastRaw.value) return;
emitOut(lastMime.value || file.value?.type || 'image/png', lastRaw.value);
}
async function copyOut() {
if (!b64Out.value) return;
try {
await navigator.clipboard.writeText(b64Out.value);
copied.value = true;
setTimeout(() => {
copied.value = false;
}, 1500);
}
catch {
i2bErr.value = '复制失败,请手动全选复制';
}
}
function clearI2B(resetFile = true) {
if (resetFile) {
file.value = null;
lastRaw.value = '';
lastMime.value = '';
if (fileUrl.value) URL.revokeObjectURL(fileUrl.value);
fileUrl.value = '';
i2bInfo.value = '';
b64Out.value = '';
}
i2bErr.value = '';
}
function onGoToB2I() {
// 参考图的「Base64转图片」按钮:带当前输出切到另一半页
if (b64Out.value) {
b64Input.value = b64Out.value;
tab.value = 'b2i';
nextTick(convertB2I);
}
else {
tab.value = 'b2i';
}
}
onBeforeUnmount(() => {
if (b2iUrl.value) URL.revokeObjectURL(b2iUrl.value);
if (fileUrl.value) URL.revokeObjectURL(fileUrl.value);
});
</script>
<template>
<div class="b64c-root">
<div class="b64c-note">
说明:使用浏览器 API 实现,您的文件不会被上传到云端,完全本地处理。
</div>
<!-- 双功能切换 -->
<div class="b64c-tabs">
<button class="b64c-tab" :class="{ on: tab === 'b2i' }" @click="tab = 'b2i'">Base64 转图片</button>
<button class="b64c-tab" :class="{ on: tab === 'i2b' }" @click="tab = 'i2b'">图片 转 Base64</button>
</div>
<!-- ============ Tab A:Base64 → 图片 ============ -->
<div v-show="tab === 'b2i'" class="b64c-panel">
<div class="b64c-label">输入内容</div>
<textarea
v-model="b64Input"
class="b64c-textarea"
rows="7"
spellcheck="false"
placeholder="base64-string 或者&#10;data:mediatype;base64,base64-string 或者&#10;url(&quot;data:mediatype;base64,base64-string&quot;)"
/>
<div class="b64c-row">
<span class="b64c-label b64c-label-inline">图片类型</span>
<select v-model="imgType" class="b64c-select">
<option v-for="t in TYPES" :key="t.v" :value="t.v">{{ t.t }}</option>
</select>
<span class="b64c-hint">如果输入内容中不包含 mediatype,则按此处选择的类型处理(自动识别优先读文件魔数)</span>
</div>
<div class="b64c-btns">
<button class="b64c-btn b64c-btn-pri" @click="convertB2I">转换</button>
<button class="b64c-btn" :disabled="!b2iUrl" @click="downloadB2I">下载</button>
<button class="b64c-btn" @click="clearB2I">清空</button>
</div>
<div v-if="b2iErr" class="b64c-err">{{ b2iErr }}</div>
<div v-else-if="b2iInfo" class="b64c-info">{{ b2iInfo }}</div>
<div v-if="b2iUrl" class="b64c-preview">
<img :src="b2iUrl" alt="preview">
</div>
</div>
<!-- ============ Tab B:图片 → Base64 ============ -->
<div v-show="tab === 'i2b'" class="b64c-panel">
<div
class="b64c-drop"
@click="!file && ($refs.pickInput as HTMLInputElement).click()"
@dragover.prevent
@drop.prevent="onDrop"
>
<template v-if="fileUrl">
<img :src="fileUrl" class="b64c-drop-img" alt="">
<div class="b64c-drop-bar">
<span class="b64c-drop-name">{{ file?.name }}</span>
<a href="javascript:;" class="b64c-drop-x" @click.stop="clearI2B()">✕ 重新选择</a>
</div>
</template>
<template v-else>
<div class="b64c-drop-icon">☁️⬆️</div>
<div class="b64c-drop-t">点击选择,或将文件拖拽到此处</div>
<div class="b64c-drop-s">支持 png / jpeg / webp / gif / bmp / svg / ico</div>
</template>
<input ref="pickInput" type="file" accept="image/*" style="display: none" @change="onPick">
</div>
<div class="b64c-row">
<span class="b64c-label b64c-label-inline">输出格式</span>
<div class="b64c-segs">
<button
v-for="f in FORMATS"
:key="f.v"
class="b64c-seg"
:class="{ on: outFormat === f.v }"
@click="outFormat = f.v; onFormatChange()"
>{{ f.t }}</button>
</div>
<span class="b64c-hint">三种格式都可直接粘回「Base64 转图片」侧</span>
</div>
<div class="b64c-btns">
<button class="b64c-btn b64c-btn-pri" @click="convertI2B()">图片转 Base64</button>
<button class="b64c-btn b64c-btn-pri2" @click="onGoToB2I">Base64 转图片</button>
<button class="b64c-btn" :disabled="!b64Out" @click="copyOut">{{ copied ? '✓ 已复制' : '复制结果' }}</button>
<button class="b64c-btn" @click="clearI2B()">清空</button>
</div>
<div v-if="i2bErr" class="b64c-err">{{ i2bErr }}</div>
<div v-else-if="i2bInfo" class="b64c-info">{{ i2bInfo }}</div>
<div class="b64c-out">
<div class="b64c-out-h">Base64内容</div>
<textarea v-model="b64Out" class="b64c-textarea b64c-out-ta" rows="8" readonly spellcheck="false" placeholder="转换后的内容会显示在这里" />
</div>
</div>
</div>
</template>
<style scoped>
.b64c-root { max-width: 860px; }
.b64c-note {
background: rgba(13, 148, 136, 0.08);
border-left: 4px solid #0d9488;
border-radius: 6px;
font-size: 13px;
padding: 10px 14px;
margin-bottom: 16px;
opacity: 0.95;
}
.b64c-tabs { display: flex; gap: 8px; margin-bottom: 16px; }
.b64c-tab {
border: 1.5px solid rgba(128, 128, 128, 0.35);
background: transparent;
color: inherit;
font-size: 14px;
font-weight: 600;
padding: 9px 22px;
border-radius: 8px;
cursor: pointer;
transition: all 0.12s;
}
.b64c-tab.on { border-color: #0d9488; background: #0d9488; color: #fff; }
.b64c-panel { display: flex; flex-direction: column; gap: 12px; }
.b64c-label { font-size: 13.5px; font-weight: 700; opacity: 0.85; }
.b64c-label-inline { flex-shrink: 0; margin-right: 2px; }
.b64c-textarea {
width: 100%;
border: 1px solid rgba(128, 128, 128, 0.4);
border-radius: 8px;
padding: 11px 13px;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 12.5px;
line-height: 1.6;
background: transparent;
color: inherit;
resize: vertical;
word-break: break-all;
}
.b64c-textarea:focus { outline: none; border-color: #0d9488; }
.b64c-textarea::placeholder { opacity: 0.42; }
.b64c-out-ta { background: rgba(128, 128, 128, 0.04); }
.b64c-row { display: flex; align-items: center; gap: 10px; flex-wrap: wrap; }
.b64c-select {
border: 1px solid rgba(128, 128, 128, 0.4);
border-radius: 7px;
padding: 6px 10px;
font-size: 13px;
background: transparent;
color: inherit;
cursor: pointer;
}
.b64c-hint { font-size: 12px; opacity: 0.5; }
.b64c-segs { display: flex; gap: 6px; }
.b64c-seg {
border: 1.5px solid rgba(128, 128, 128, 0.35);
background: transparent;
color: inherit;
font-size: 12.5px;
padding: 5px 13px;
border-radius: 999px;
cursor: pointer;
transition: all 0.12s;
}
.b64c-seg.on { border-color: #0d9488; color: #0d9488; background: rgba(13, 148, 136, 0.1); font-weight: 700; }
.b64c-btns { display: flex; gap: 9px; flex-wrap: wrap; }
.b64c-btn {
border: 1px solid rgba(128, 128, 128, 0.4);
background: transparent;
color: inherit;
font-size: 13.5px;
font-weight: 600;
padding: 9px 20px;
border-radius: 8px;
cursor: pointer;
transition: all 0.12s;
}
.b64c-btn:hover:not(:disabled) { border-color: #0d9488; color: #0d9488; }
.b64c-btn:disabled { opacity: 0.4; cursor: not-allowed; }
.b64c-btn-pri { background: #0d9488; border-color: #0d9488; color: #fff; }
.b64c-btn-pri:hover:not(:disabled) { filter: brightness(1.08); color: #fff; }
.b64c-btn-pri2 { background: transparent; border-color: #0d9488; color: #0d9488; }
.b64c-err { background: rgba(229, 57, 53, 0.08); border: 1px solid rgba(229, 57, 53, 0.35); color: #e53935; border-radius: 8px; font-size: 12.5px; padding: 9px 12px; word-break: break-all; }
.b64c-info { background: rgba(13, 148, 136, 0.07); border: 1px solid rgba(13, 148, 136, 0.28); border-radius: 8px; font-size: 12.5px; padding: 9px 12px; }
.b64c-preview { border: 1px dashed rgba(128, 128, 128, 0.45); border-radius: 8px; padding: 14px; display: flex; justify-content: center; align-items: center; min-height: 120px; background: rgba(128, 128, 128, 0.03); }
.b64c-preview img { max-width: 100%; max-height: 340px; border-radius: 6px; }
.b64c-drop {
border: 2px dashed rgba(13, 148, 136, 0.5);
border-radius: 10px;
min-height: 150px;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
cursor: pointer;
transition: border-color 0.15s;
overflow: hidden;
padding: 8px;
}
.b64c-drop:hover { border-color: #0d9488; background: rgba(13, 148, 136, 0.03); }
.b64c-drop-icon { font-size: 30px; }
.b64c-drop-t { margin-top: 8px; font-size: 14px; font-weight: 600; color: #0d9488; }
.b64c-drop-s { margin-top: 5px; font-size: 11.5px; opacity: 0.5; }
.b64c-drop-img { max-width: 100%; max-height: 230px; border-radius: 7px; display: block; margin: 0 auto; }
.b64c-drop-bar { display: flex; justify-content: space-between; align-items: center; margin-top: 7px; font-size: 12px; width: 100%; }
.b64c-drop-name { opacity: 0.7; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.b64c-drop-x { color: #e53935; text-decoration: none; flex-shrink: 0; margin-left: 8px; }
.b64c-out { border: 1px solid rgba(128, 128, 128, 0.35); border-radius: 8px; overflow: hidden; }
.b64c-out-h { background: rgba(128, 128, 128, 0.1); font-size: 12.5px; font-weight: 700; padding: 7px 13px; opacity: 0.8; }
.b64c-out-ta { border: none; border-radius: 0; }
.b64c-out-ta:focus { border: none; }
</style>
+12
View File
@@ -0,0 +1,12 @@
import { Exchange } from '@vicons/tabler';
import { defineTool } from '../tool';
import { translate } from '@/plugins/i18n.plugin';
export const tool = defineTool({
name: translate('tools.base64-image-converter.title'),
path: '/base64-image-converter',
description: translate('tools.base64-image-converter.description'),
keywords: ['base64', 'image', '图片', '互转', '转图片', '图片转base64', 'base64转图片', 'data uri', '编码', '解码', 'img'],
component: () => import('./base64-image-converter.vue'),
icon: Exchange,
});
+2 -2
View File
@@ -87,7 +87,7 @@ import { tool as sealMaker } from './seal-maker';
import { tool as signaturePad } from './signature-pad';
import { tool as textToImage } from './text-to-image';
import { tool as aiGen } from './ai-gen';
import { tool as aiTextEdit } from './ai-text-edit';
import { tool as base64ImageConverter } from './base64-image-converter';
import { tool as zhConvert } from './zh-convert';
import { tool as pinyinConverter } from './pinyin-converter';
import { tool as aiImageLab } from './ai-image-lab';
@@ -164,7 +164,7 @@ export const toolsByCategory: ToolCategory[] = [
},
{
name: 'Images and videos',
components: [qrCodeGenerator, wifiQrCodeGenerator, batchBarcodeGenerator, codeReader, imageOcr, pdfOcr, pdfTools, imageTools, videoTools, audioTools, sealMaker, signaturePad, textToImage, aiGen, aiTextEdit, docConvert, aiRetouch, labelDesigner, siteBookmarks, svgPlaceholderGenerator, cameraRecorder],
components: [qrCodeGenerator, wifiQrCodeGenerator, batchBarcodeGenerator, codeReader, imageOcr, pdfOcr, pdfTools, imageTools, base64ImageConverter, videoTools, audioTools, sealMaker, signaturePad, textToImage, aiGen, docConvert, aiRetouch, labelDesigner, siteBookmarks, svgPlaceholderGenerator, cameraRecorder],
},
{
name: 'Development',