Understanding Base64 Encoding
Base64 encoding is a method of converting binary or text data into a plain text string of ASCII characters. This encoding is widely used in various applications, such as embedding images in HTML, sending data over HTTP, or storing binary data in JSON.
The atob() and btoa() Functions
- btoa() – Encoding: The btoa() function allows you to encode a binary string into a Base64-encoded string. It takes a string as input and returns the Base64-encoded version.
- atob() – Decoding: Conversely, the atob() function decodes a Base64-encoded string back into its original binary form.
Encoding Text Data
To encode a text string, you can simply use the btoa() function like this:
const originalText = "Hello, World!";
const encodedText = btoa(originalText);
console.log(encodedText); // "SGVsbG8sIFdvcmxkIQ=="
Encoding Binary Data
To encode binary data, you first need to convert it to a text string, and then use btoa(). Here’s an example of encoding an image file:
const textData = String.fromCharCode.apply(null, new Uint8Array(binaryData));
const encodedImage = btoa(textData);
- Embedding Images: Base64 encoding is often used to embed images directly into HTML or CSS files, reducing the number of HTTP requests.
- Storing Data in JSON: When you need to include binary data, such as images or files, in a JSON object, Base64 encoding ensures compatibility.
- Data URI: You can create data URIs for resources like images, allowing them to be loaded directly as part of a web page.
- Secure Data Transmission: Base64 encoding is useful when sending sensitive data via URLs or APIs, as it ensures the data is transmitted in a safe and readable format.