Skip to content

base64_encode

The base64_encode filter encodes a string using the Base64 format. This encoding scheme is commonly used to represent binary data (such as images or files) using a restricted set of 64 printable ASCII characters.

Functionality

  • Strings: Takes a string as input.
  • Encoding: Converts the input string into a Base64 representation. This is done by first converting the string to a byte array using UTF-8 encoding, then applying the Base64 algorithm to the bytes.
  • Output: Returns a new string containing the Base64-encoded data.

Syntax

    {{ input_string | base64_encode }}
Arguments

The base64_encode filter does not require any arguments.

Code Samples

Example 1: Encoding a String

    {% assign data = "Hello, world!" %}

    {{ data | base64_encode }}

Output:

SGVsbG8sIHdvcmxkIQ==
Example 2: Encoding Binary Data (e.g., Image)
    {% assign image_data = "binary image data here" %}
    <img src="data:image/png;base64,{{ image_data | base64_encode }}" alt="Encoded Image">
Note: In this example, you would need to replace "binary image data here" with the actual binary data of your image.

Outliers and Special Cases

  • Empty Strings: If the input string is empty, the base64_encode filter returns an empty string.
  • Encoding Binary Data: If you intend to encode binary data, make sure that the data is already in a binary format (byte array) before applying the base64_encode filter. If you have a string that represents binary data (e.g., from a file), you might need to convert it to a byte array first using a suitable method (e.g., Encoding.UTF8.GetBytes() in C#).

Key Points

  • The base64_encode filter is a powerful tool for representing binary data or characters that are not suitable for direct transmission within a text-based format.
  • It is commonly used in web development for embedding images directly into HTML or CSS, as well as in data transmission protocols.
  • Base64-encoded data is generally about 33% larger than the original data.