Base64 is everywhere in web development—from embedding images in HTML to handling API authentication. Yet many developers use it without fully understanding what it does or when it's appropriate. This guide demystifies Base64 encoding and helps you use it effectively.
什么是 Base64 编码?
Base64 is a binary-to-text encoding scheme that converts binary data into a string of 64 printable ASCII characters. It was designed to transmit binary data through systems that only handle text.
The "64" comes from the 64-character alphabet used:
- Uppercase letters: A-Z (26 characters)
- Lowercase letters: a-z (26 characters)
- Digits: 0-9 (10 characters)
- Special characters: + and / (2 characters)
- Padding character: = (used when input isn't divisible by 3)
💡 Key Point: Base64 is NOT encryption. It's encoding. Anyone can decode Base64 instantly—it provides zero security. Never use it to "hide" sensitive data.
Base64 的工作原理
The encoding process:
- Take the binary representation of the input
- Split into groups of 6 bits (instead of 8-bit bytes)
- Convert each 6-bit group to its corresponding Base64 character
- Add padding (=) if the input length isn't divisible by 3
示例:编码“Hi”
ASCII: 72, 105
Binary: 01001000 01101001
Split into 6-bit groups: 010010 000110 1001
Add padding bits: 010010 000110 100100
Base64 values: 18, 6, 36
Base64 characters: S, G, k
Result: "SGk=" (= added for padding)
尺寸增加 33%
Because we're representing 8-bit data as 6-bit characters, Base64 output is always about 33% larger than the input. Three bytes of binary become four Base64 characters.
⚠️ Size Consideration: A 1MB image becomes ~1.33MB when Base64 encoded. For large files, this overhead matters. Consider whether Base64 is truly necessary.
常见用例
1. 数据 URL(在 HTML/CSS 中嵌入图像)
Instead of referencing an external file, embed the image directly:
/* In CSS */
background-image: url('data:image/svg+xml;base64,PHN2Zy...');
Pros: Fewer HTTP requests, no broken image links
Cons: Larger HTML file, not cached separately, hurts readability
2. 电子邮件附件 (MIME)
Email was designed for text only. Binary attachments (images, PDFs) are Base64 encoded within the email message, then decoded by the recipient's mail client.
3. 基本认证
// Decoded: "username:password"
HTTP Basic Auth encodes credentials in Base64. Remember: this is encoding, not encryption—always use HTTPS!
4.JSON网络令牌(JWT)
JWTs consist of three Base64-encoded parts:
|____ Header ____|.|____ Payload ____|.|_ Signature _|
5. 在 JSON/XML 中存储二进制
Since JSON doesn't support binary data natively, binary fields (like thumbnails) are often Base64 encoded:
"filename": "photo.jpg",
"data": "base64-encoded-content-here",
"mimeType": "image/jpeg"
}
何时不使用 Base64
- Large files: The 33% overhead adds up. Use proper file transfer instead.
- Security: Base64 is trivially decodable. Use encryption for secrets.
- Frequently accessed images: External files can be cached; embedded data cannot.
- Dynamic content: Changing embedded content requires regenerating the entire document.
✅ 最佳实践
Use Base64 for small, critical images (icons, logos) that should load with the page. For larger images or those that change frequently, use traditional file references.
JavaScript 中的 Base64
const encoded = btoa("Hello, World!");
console.log(encoded); // "SGVsbG8sIFdvcmxkIQ=="
// Decoding
const decoded = atob("SGVsbG8sIFdvcmxkIQ==");
console.log(decoded); // "Hello, World!"
// For Unicode (modern browsers)
const unicodeEncode = btoa(unescape(encodeURIComponent("Hello 🌍")));
const unicodeDecode = decodeURIComponent(escape(atob(encoded)));
Base64 变体
Standard Base64 uses + and /, which are problematic in URLs. Variants exist:
- Base64URL: Replaces + with - and / with _ (used in JWTs)
- Base32: Uses 32 characters, case-insensitive (used in 2FA codes)
- Base16 (Hex): Uses 16 characters (0-9, A-F)
🔧 需要编码或解码 Base64?
Use our free Base64 tool for instant encoding and decoding in your browser.
打开 Base64 工具 →结论
Base64 is a simple but essential tool in web development. It bridges the gap between binary data and text-based systems, enabling everything from email attachments to JWT tokens.
Remember: use it when you need to transmit binary through text channels, but always consider the size overhead and never mistake it for security. With this understanding, you can confidently apply Base64 where it truly adds value.