Skip to content

Commit 4fed38a

Browse files
authored
Merge pull request ZToolsCenter#588 from fuyanghulin/plugin/base64
Add plugin Base64 编解码 v1.0.0
2 parents 38ba75a + a94f79f commit 4fed38a

20 files changed

Lines changed: 1137 additions & 0 deletions

‎plugins/base64/.gitignore‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
node_modules/
2+
dist/
3+
release/
4+
test-results/

‎plugins/base64/CHANGELOG.md‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
# 更新记录
2+
3+
## 1.0.0
4+
5+
- 首次发布离线 Base64 文本与图片编解码插件。
6+
- 支持 UTF-8、URL-safe Base64、Data URL、缺省填充及换行内容。
7+
- 支持图片选择、拖放、粘贴、解码预览和原始字节保存。
8+
- ZTools 原生图片选择对话框避免选图时宿主窗口失焦隐藏,取消或失败保留当前结果。
9+
- 提供自动转换、快捷键、内容清空、深色与窄窗口布局。
10+
- 提供 ZPX、ZIP 安装包及逐字节包内容校验。

‎plugins/base64/README.md‎

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
# Base64 编解码 · ZTools 插件
2+
3+
纯 HTML/CSS/JavaScript 插件,无运行时第三方依赖、无需构建、无需联网。
4+
5+
## 下载与截图
6+
7+
从 [GitHub Releases](https://github.com/fuyanghulin/base64-ztools/releases/latest) 下载 `.zpx` 安装包,导入 ZTools 即可使用。`.zip` 提供完整插件文件。
8+
9+
![文本编码](https://raw.githubusercontent.com/fuyanghulin/base64-ztools/main/docs/screenshots/text-encode.png)
10+
11+
![图片解码与保存](https://raw.githubusercontent.com/fuyanghulin/base64-ztools/main/docs/screenshots/image-decode.png)
12+
13+
## 使用
14+
15+
在 ZTools 的本地插件开发/导入入口选择本目录的 `plugin.json`。保持同目录中的 HTML、JS、CSS 和 logo.png 完整。搜索 `base64`、`base64编码` 或 `base64解码` 打开插件。
16+
17+
- **文本编码**:输入或粘贴文本,自动转换;支持中文、Emoji、多行和空白字符。
18+
- **图片编码**:切换到「图片」,选择、拖入或粘贴图片。可切换纯 Base64 / 含 Data URL 前缀。
19+
- **解码**:粘贴 Base64;文本直接显示,图片自动预览,点击「保存图片」选择保存位置。图片按原始字节保存,不重新压缩或转码。
20+
- 支持 PNG、JPEG、GIF、WebP、BMP、ICO、AVIF、SVG 的内容识别;实际预览取决于宿主浏览器的格式支持与文件完整性。
21+
- 支持标准 Base64、URL-safe、缺省末尾填充和含换行的内容。文本按 UTF-8 解码,非法文本或无法识别的二进制会显示错误。
22+
- 输入后 250 ms 自动转换,也可以使用 `Ctrl / ⌘ + Enter`。编码和解码各自保留本次会话的输入;输入区底部的「清空内容」用于清空当前模式的内容和结果。
23+
- 最大原始内容 20 MB;不上传内容,不记录历史。SVG 仅以图片元素预览,不注入页面。
24+
25+
也可以直接在浏览器打开 `index.html` 使用。浏览器环境的保存走下载功能,ZTools 环境使用原生保存对话框。
26+
27+
### 原生图片选择
28+
29+
ZTools 中的「选择图片」和「更换图片」改用 `ztools.showOpenDialog`。宿主会在对话框期间抑制失焦自动隐藏,解决 HTML 文件选择框导致整个 ZTools 窗口消失的问题。取消选图或读取失败时保留当前图片及结果;浏览器独立使用时仍采用 HTML 文件选择框。
30+
31+
## 开发与验证
32+
33+
```shell
34+
npm ci
35+
npm test
36+
npm run test:ui
37+
npm run package
38+
npm run verify
39+
```
40+
41+
`npm test` 验证编解码、格式识别、边界校验及 preload 保存字节/取消/错误处理。`npm run test:ui` 默认通过本机 Microsoft Edge 运行 Playwright,检查真实页面交互、下载文件、图片预览、窄窗口和深色样式。可设置 `BROWSER_CHANNEL=chrome` 使用 Chrome。
42+
43+
`npm run package` 自动整理最新插件文件到 `dist/base64/`,再生成安装包,无需先执行 build,也无需到 ZTools 界面手动打包。打包脚本参考同级 `json-formatter-ztools`,ZPX 使用 ASAR + Brotli(压缩级别 5),并额外输出 ZIP 文件包。
44+
45+
生成文件位于 `release/`,文件名自动读取 `plugin.json` 的 `name` 和 `version`。当前为:
46+
47+
- `release/base64-1.0.0.zpx`:ZTools 安装包。
48+
- `release/base64-1.0.0.zip`:插件文件压缩包。
49+
50+
`npm run verify` 解压检查两种包的文件清单、入口及配置,并逐字节核对包内文件与当前源码是否一致。需要重新打包时再次运行 `npm run package` 即可;其他版本的发布文件会保留。只想生成插件目录时使用 `npm run build`。
51+
52+
打包依赖仅供开发使用(Node.js >= 22.12.0),不会装进插件包。无需携带 node_modules 或测试文件,命令不会发布到插件市场。
53+
54+
文件分工:`codec.js` 为共享编解码与图片识别逻辑;`app.js` 为交互;`preload.js` 调用 ZTools 保存对话框并写入文件;`plugin.json` 注册功能命令。preload 保留可读 CommonJS 源码。
55+
56+
## 开发依据
57+
58+
- [快速开始](https://ohmyztools.cc/getting-started.html)
59+
- [插件配置](https://ohmyztools.cc/plugin-json.html)
60+
- [preload 规范](https://ohmyztools.cc/preload-js.html)
61+
- [插件 API:进入事件、复制、保存对话框](https://ohmyztools.cc/plugin-api.html)
62+
63+
自动测试中的 ZTools API 使用替身验证契约。v1.0.0 已通过逻辑与浏览器交互测试;作者已在真实 ZTools 中确认打开插件、文本编解码、选择图片和保存图片正常。

‎plugins/base64/app.js‎

Lines changed: 269 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,269 @@
1+
'use strict';
2+
const $ = id => document.getElementById(id);
3+
const codec = window.Base64Codec;
4+
let mode = 'encode';
5+
let source = 'text';
6+
let selected = null;
7+
let result = null;
8+
let sourceUrl = '';
9+
let resultUrl = '';
10+
let revision = 0;
11+
let selectionRevision = 0;
12+
let timer;
13+
let toastTimer;
14+
const drafts = { encode: '', decode: '' };
15+
16+
function sizeLabel(size) {
17+
return size < 1024 ? `${size} B` : size < 1024 * 1024 ? `${(size / 1024).toFixed(1)} KB` : `${(size / 1024 / 1024).toFixed(2)} MB`;
18+
}
19+
function notify(message) {
20+
$('status').textContent = message;
21+
$('status').classList.add('visible');
22+
clearTimeout(toastTimer);
23+
toastTimer = setTimeout(() => $('status').classList.remove('visible'), 3000);
24+
}
25+
function revokeResult() {
26+
if (resultUrl) URL.revokeObjectURL(resultUrl);
27+
resultUrl = '';
28+
$('decoded-preview').removeAttribute('src');
29+
}
30+
function resetResult() {
31+
revision++;
32+
clearTimeout(timer);
33+
result = null;
34+
revokeResult();
35+
$('output').value = '';
36+
for (const id of ['output', 'image-result', 'error', 'save']) $(id).hidden = true;
37+
$('empty-result').hidden = false;
38+
$('copy').disabled = true;
39+
$('copy').textContent = '复制结果';
40+
$('output-count').textContent = '等待输入';
41+
$('result-type').textContent = mode === 'encode' ? 'BASE64' : '自动识别';
42+
}
43+
function renderMode() {
44+
const encode = mode === 'encode';
45+
const image = encode && source === 'image';
46+
for (const value of ['encode', 'decode']) {
47+
$(`${value}-mode`).classList.toggle('active', mode === value);
48+
$(`${value}-mode`).setAttribute('aria-pressed', String(mode === value));
49+
}
50+
for (const value of ['text', 'image']) {
51+
$(`${value}-source`).classList.toggle('active', source === value);
52+
$(`${value}-source`).setAttribute('aria-pressed', String(source === value));
53+
}
54+
$('source-controls').hidden = !encode;
55+
$('input').hidden = image;
56+
$('image-input').hidden = !image;
57+
$('output-options').hidden = !image;
58+
$('input-title').textContent = encode ? '原始内容' : 'Base64 内容';
59+
$('output-title').textContent = encode ? '编码结果' : '解码结果';
60+
$('input').placeholder = encode ? '在这里输入或粘贴文本…\n\n支持中文、Emoji 和多行文本。' : '在这里粘贴 Base64…\n\n支持纯 Base64 或 data:image/…;base64,…\n图片将自动显示预览。';
61+
$('input-help').textContent = image ? '保留原图格式与质量' : encode ? '文本使用 UTF-8 编码' : '自动忽略空格与换行';
62+
$('input-count').textContent = image ? selected ? sizeLabel(selected.bytes.length) : '未选择图片' : `${$('input').value.length.toLocaleString()} 字符`;
63+
$('pick-image').hidden = !!selected;
64+
$('selected-image').hidden = !selected;
65+
}
66+
function changeMode(next) {
67+
if (mode !== next) {
68+
drafts[mode] = $('input').value;
69+
mode = next;
70+
$('input').value = drafts[mode];
71+
selectionRevision++;
72+
}
73+
renderMode();
74+
convert();
75+
}
76+
function changeSource(next) {
77+
source = next;
78+
selectionRevision++;
79+
renderMode();
80+
convert();
81+
}
82+
function showError(error) {
83+
$('empty-result').hidden = true;
84+
$('error').hidden = false;
85+
$('error').textContent = error.message || '转换失败,请检查输入内容。';
86+
$('output-count').textContent = '请检查内容';
87+
}
88+
function convert() {
89+
resetResult();
90+
const current = revision;
91+
try {
92+
if (mode === 'encode') {
93+
if (source === 'image' && !selected || source === 'text' && !$('input').value) return;
94+
const text = source === 'image' ? ($('data-url').checked ? `data:${selected.mime};base64,` : '') + selected.base64 : codec.encodeText($('input').value);
95+
result = { kind: 'text', text };
96+
$('output').value = text;
97+
$('output').hidden = false;
98+
$('output-count').textContent = `${text.length.toLocaleString()} 字符`;
99+
} else {
100+
if (!$('input').value.trim()) return;
101+
result = codec.decode($('input').value);
102+
if (result.kind === 'image') {
103+
const imageResult = result;
104+
$('result-type').textContent = result.extension.toUpperCase();
105+
$('image-result').hidden = false;
106+
$('save').hidden = false;
107+
$('copy').textContent = '复制 Base64';
108+
$('output-count').textContent = sizeLabel(result.bytes.length);
109+
$('image-meta').textContent = `${result.mime} · 正在加载预览…`;
110+
const img = $('decoded-preview');
111+
img.onload = () => {
112+
if (current !== revision) return;
113+
$('image-meta').textContent = `${img.naturalWidth} × ${img.naturalHeight} px · ${imageResult.mime} · ${sizeLabel(imageResult.bytes.length)}`;
114+
};
115+
img.onerror = () => {
116+
if (current !== revision) return;
117+
$('image-meta').textContent = '图片数据已识别,但预览失败;可能文件损坏或当前环境不支持此格式。仍可保存原文件。';
118+
};
119+
resultUrl = URL.createObjectURL(new Blob([result.bytes], { type: result.mime }));
120+
img.src = resultUrl;
121+
} else {
122+
$('result-type').textContent = 'UTF-8';
123+
$('output').hidden = false;
124+
$('output').value = result.text;
125+
$('output-count').textContent = `${result.text.length.toLocaleString()} 字符 · ${sizeLabel(result.bytes.length)}`;
126+
}
127+
}
128+
$('empty-result').hidden = true;
129+
$('copy').disabled = false;
130+
} catch (error) { showError(error); }
131+
}
132+
async function selectImage(file) {
133+
if (!file) return;
134+
if (mode !== 'encode') changeMode('encode');
135+
source = 'image';
136+
const current = ++selectionRevision;
137+
selected = null;
138+
if (sourceUrl) URL.revokeObjectURL(sourceUrl);
139+
sourceUrl = '';
140+
$('source-preview').removeAttribute('src');
141+
resetResult();
142+
renderMode();
143+
try {
144+
codec.checkSize(file.size);
145+
const bytes = new Uint8Array(typeof file.arrayBuffer === 'function' ? await file.arrayBuffer() : file.bytes);
146+
if (current !== selectionRevision) return;
147+
const mime = codec.imageMime(bytes);
148+
if (!mime) throw new Error('无法识别此图片,请选择 PNG、JPG、GIF、WebP、BMP、ICO、AVIF 或 SVG。');
149+
selected = { bytes, mime, base64: codec.encodeBytes(bytes) };
150+
sourceUrl = URL.createObjectURL(new Blob([bytes], { type: mime }));
151+
$('source-preview').src = sourceUrl;
152+
$('source-preview').onerror = () => { if (current === selectionRevision) notify('当前环境无法预览此图片,仍可编码和保存原始数据。'); };
153+
$('file-info').textContent = `${file.name || '粘贴的图片'} · ${sizeLabel(bytes.length)}`;
154+
renderMode();
155+
convert();
156+
} catch (error) { if (current === selectionRevision) showError(error); }
157+
}
158+
$('encode-mode').onclick = () => changeMode('encode');
159+
$('decode-mode').onclick = () => changeMode('decode');
160+
$('text-source').onclick = () => changeSource('text');
161+
$('image-source').onclick = () => changeSource('image');
162+
$('data-url').onchange = convert;
163+
$('input').addEventListener('input', () => {
164+
drafts[mode] = $('input').value;
165+
renderMode();
166+
resetResult();
167+
timer = setTimeout(convert, 250);
168+
});
169+
$('clear').onclick = () => {
170+
selectionRevision++;
171+
$('input').value = '';
172+
drafts[mode] = '';
173+
if (mode === 'encode') {
174+
selected = null;
175+
if (sourceUrl) URL.revokeObjectURL(sourceUrl);
176+
sourceUrl = '';
177+
$('source-preview').removeAttribute('src');
178+
$('file-input').value = '';
179+
}
180+
resetResult();
181+
renderMode();
182+
};
183+
async function pickImage() {
184+
// 网页预览使用 HTML file input;ZTools 必须走宿主的防失焦对话框。
185+
if (!window.ztools) {
186+
$('file-input').click();
187+
return;
188+
}
189+
const current = selectionRevision;
190+
const buttons = [$('pick-image'), $('replace-image')];
191+
buttons.forEach(button => { button.disabled = true; });
192+
try {
193+
if (!window.base64Native?.openImage) throw new Error('选图接口未加载,请重新加载插件后重试。');
194+
const image = await window.base64Native.openImage();
195+
if (current !== selectionRevision) return;
196+
if (image.canceled) return;
197+
await selectImage({ name: image.name, size: image.bytes.length, bytes: image.bytes });
198+
} catch (error) {
199+
if (current === selectionRevision) notify(`选图失败:${error.message}`);
200+
} finally {
201+
buttons.forEach(button => { button.disabled = false; });
202+
}
203+
}
204+
for (const id of ['pick-image', 'replace-image']) $(id).onclick = pickImage;
205+
$('file-input').onchange = event => {
206+
selectImage(event.target.files[0]);
207+
event.target.value = '';
208+
};
209+
document.addEventListener('keydown', event => {
210+
if ((event.ctrlKey || event.metaKey) && event.key === 'Enter') { event.preventDefault(); convert(); }
211+
});
212+
document.addEventListener('paste', event => {
213+
if (mode !== 'encode') return;
214+
const image = [...(event.clipboardData?.items || [])].find(item => item.type.startsWith('image/'));
215+
if (image) { event.preventDefault(); selectImage(image.getAsFile()); }
216+
});
217+
const inputPanel = document.querySelector('.input-panel');
218+
document.addEventListener('dragover', event => { event.preventDefault(); if (mode === 'encode') inputPanel.classList.add('dragging'); });
219+
document.addEventListener('dragleave', event => { if (!event.relatedTarget) inputPanel.classList.remove('dragging'); });
220+
document.addEventListener('drop', event => {
221+
event.preventDefault();
222+
inputPanel.classList.remove('dragging');
223+
if (mode === 'encode' && event.dataTransfer.files.length) selectImage(event.dataTransfer.files[0]);
224+
});
225+
$('copy').onclick = async () => {
226+
if (!result) return;
227+
const text = result.kind === 'image' ? `data:${result.mime};base64,${result.base64}` : result.text;
228+
try {
229+
if (window.ztools?.copyText) {
230+
if (await window.ztools.copyText(text) === false) throw new Error('复制失败,请重试。');
231+
} else await navigator.clipboard.writeText(text);
232+
notify('已复制到剪贴板');
233+
} catch (error) { notify(error.message || '复制失败,请手动选择结果复制。'); }
234+
};
235+
$('save').onclick = async () => {
236+
if (result?.kind !== 'image') return;
237+
const image = result;
238+
try {
239+
if (window.base64Native?.saveImage) {
240+
const saved = await window.base64Native.saveImage(image.base64);
241+
notify(saved.canceled ? '已取消保存' : '图片已保存');
242+
} else {
243+
const url = URL.createObjectURL(new Blob([image.bytes], { type: image.mime }));
244+
const link = document.createElement('a');
245+
link.href = url;
246+
link.download = `base64-image.${image.extension}`;
247+
document.body.append(link);
248+
link.click();
249+
link.remove();
250+
setTimeout(() => URL.revokeObjectURL(url), 30000);
251+
notify('已发起图片下载');
252+
}
253+
} catch (error) { notify(`保存失败:${error.message}`); }
254+
};
255+
if (window.ztools?.onPluginEnter) {
256+
window.ztools.onPluginEnter(param => {
257+
if (param.code === 'decode' || param.code === 'encode') changeMode(param.code);
258+
if ((param.type === 'over' || param.type === 'regex') && typeof param.payload === 'string') {
259+
source = 'text';
260+
$('input').value = param.payload;
261+
drafts[mode] = param.payload;
262+
renderMode();
263+
convert();
264+
}
265+
if (!$('input').hidden) $('input').focus();
266+
});
267+
}
268+
renderMode();
269+
resetResult();

0 commit comments

Comments
 (0)