How to Encode Images with Base64

Embedding images directly into HTML, CSS, or JSON payloads is a common technique used by developers to optimize web performance, package assets into single files, and transport media over text-based APIs. Because these text environments cannot handle raw binary image formats (like PNG, JPEG, or WebP), the image must be converted into a text string using Base64.

In this guide, we will walk through exactly how to encode an image, format it properly, and deploy it in your codebase.

The Process: Binary to Text

An image file is fundamentally a collection of binary bytes on a hard drive. To convert it to Base64, the system reads those raw bytes and regroups them, mapping them to the 64-character ASCII index. You can do this programmatically, via the command line, or by using a graphical Base64 Encoder.

Step 1: Encoding the Image

If you are using our online tool:

  1. Navigate to the Encoder workspace.
  2. Select the "Upload File" option (or drag and drop your image).
  3. The tool reads the image locally in your browser and instantly generates the raw Base64 string.

If you are on a Mac or Linux terminal, you can do this natively:

cat logo.png | base64

If you are building a web application, you can use the JavaScript FileReader API to encode images uploaded by a user:

const reader = new FileReader();
reader.onload = (e) => console.log(e.target.result);
reader.readAsDataURL(file);

Step 2: Formatting the Data URI

Once you have the raw Base64 string, you must format it correctly so the web browser understands how to render it. This is done by constructing a Data URI.

The syntax is: data:<mime-type>;base64,<your-base64-string>

For example, if you encoded a PNG image, your Data URI will look like this:

data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAA...

Ensure you use the correct MIME type (image/jpeg for JPGs, image/svg+xml for SVGs, image/webp for WebP).

Step 3: Embedding in HTML

To display the image on a web page without forcing the browser to make a separate HTTP request, you simply paste the entire Data URI directly into the src attribute of an <img> tag.

<img src="data:image/png;base64,iVBORw0KGgoAAA..." alt="Embedded Logo">

Step 4: Embedding in CSS

Base64 encoded images are incredibly useful in CSS for background patterns or UI icons. This ensures the icon renders the exact millisecond the CSS file is parsed, preventing layout shifts.

.profile-placeholder {
    width: 50px;
    height: 50px;
    background-image: url('data:image/svg+xml;base64,PHN2ZyB4...');
    background-size: cover;
}

Best Practices and Warnings

To safely encode your images right now without uploading them to a remote server, use our free, privacy-first Base64 Encoder.