Base64
Base64 (Binary-to-Text Encoding)
An encoding scheme that converts binary data into a text string using 64 printable ASCII characters (A-Z, a-z, 0-9, +, /), allowing binary content like images or files to be safely embedded in text-based formats.
技術的詳細
Base64 groups every 3 input bytes (24 bits) into 4 output characters (6 bits each), using = padding when the input length is not divisible by 3. This results in approximately 33% size overhead. The URL-safe variant (base64url, RFC 4648) replaces + with - and / with _ to avoid issues in URLs and filenames. In JavaScript, btoa()/atob() handle Latin-1 strings; for Unicode, data must first be UTF-8 encoded. Data URIs embed base64-encoded content directly in HTML/CSS using the data: scheme.
例
```javascript
// Encode string to Base64
const encoded = btoa('Hello, World!'); // 'SGVsbG8sIFdvcmxkIQ=='
// Decode Base64 to string
const decoded = atob('SGVsbG8sIFdvcmxkIQ=='); // 'Hello, World!'
// File to Base64 Data URI
const reader = new FileReader();
reader.onload = () => console.log(reader.result);
// → 'data:image/png;base64,iVBORw0KGgo...'
reader.readAsDataURL(file);
```