To convert an image to a Base64 data URI, read the file's bytes, Base64-encode them, and put data:<mime-type>;base64, in front, for example data:image/png;base64,iVBOR.... In a browser, FileReader.readAsDataURL() does all three steps; in Node, use Buffer and add the prefix yourself. Avoid data URIs for large images, images used on several pages, and anything below the fold, because they can't be cached on their own.
What an image Base64 data URI is made of
A data URI is a URL that carries the file itself instead of pointing to it. MDN's data URL reference gives the syntax as data:[<media-type>][;base64],<data>.
| Part | Example | What it does |
|---|---|---|
| Scheme | data: |
Tells the browser the content is inline |
| Media type | image/png |
Says how to read the bytes; if omitted it "defaults to text/plain;charset=US-ASCII" |
| Base64 flag | ;base64 |
"Indicates that the data should be base64-decoded" |
| Comma | , |
Separates the header from the data |
| Data | iVBORw0KGgo... |
The Base64-encoded file bytes |
The media type matters more than people expect. If you leave it out, the browser treats the bytes as plain text and your <img> shows a broken icon.
How to convert an image to a Base64 data URI in the browser
FileReader.readAsDataURL() turns a File or Blob into a complete data URI, prefix included. According to MDN's readAsDataURL page, the result "contains the data as a data: URL representing the file's data as a base64 encoded string."
- Add a file input:
<input type="file" accept="image/*" id="pick">. - Read the chosen file when it changes:
document.getElementById('pick').addEventListener('change', (e) => {
const reader = new FileReader();
reader.onload = () => console.log(reader.result); // "data:image/png;base64,..."
reader.readAsDataURL(e.target.files[0]);
});
- Copy
reader.resultinto your HTML or CSS.
The browser fills in the media type from the file, so you don't have to look it up.
The prefix gotcha when you only want the Base64 part
The result of readAsDataURL() is not plain Base64, and decoding it as-is fails. MDN says: "To retrieve only the Base64 encoded string, first remove data:*/*;base64, from the result."
A safe way is reader.result.split(',')[1]. This matters when an API wants a raw Base64 field, such as a JSON body with an "image" key, rather than a URL.
Why canvas.toDataURL() is not the same as encoding the file
canvas.toDataURL() gives you a data URI of what the canvas shows, not of your original file. MDN's toDataURL reference says it "returns a data URL containing a representation of the image in the format specified by the type parameter," and "The default type is image/png."
This is the part most converter pages skip. If you draw a JPEG onto a canvas and call toDataURL() with no arguments, you get a PNG, freshly encoded from the pixels.
Use canvas only when you actually want to change the image: resize it, crop it, or re-encode it. MDN also warns that toDataURL() "encodes the whole image in an in-memory string" and that "You should generally prefer toBlob() instead." For a byte-for-byte copy of the file, stick with FileReader.
How to do it in Node.js
Node's Buffer handles the Base64 step, and you add the data URI prefix. The Node.js Buffer docs show the encoding with a short string: Buffer.from('hello world', 'utf8').toString('base64') prints aGVsbG8gd29ybGQ=.
For an image, read the file as bytes instead of text:
const fs = require('fs');
const b64 = fs.readFileSync('logo.png').toString('base64');
const uri = `data:image/png;base64,${b64}`;
Set the media type to match the file: image/png, image/jpeg, image/webp, image/gif or image/svg+xml. Node won't guess it for you. If you're encoding text rather than an image, read the note on Base64 and Unicode in JavaScript first.
Using the data URI in HTML and CSS
The string goes anywhere a normal image URL goes. In HTML:
<img src="data:image/png;base64,iVBORw0KGgo..." alt="Company logo">
In CSS:
.icon { background-image: url("data:image/svg+xml;base64,PHN2Zy..."); }
Keep the alt text. A data URI changes where the bytes come from, not what the image means to someone using a screen reader.
When to avoid a Base64 image data URI
Avoid a data URI when the image is large, shared, or not needed right away. The format was designed for small things: RFC 2397, which defines it, says "The data: URL scheme is only useful for short values."
I keep the image as a normal file when:
- It's bigger than a small icon. Base64 output is "about 33 percent larger than the unencoded data," as RFC 2045 puts it. The Base64 size increase post walks through the math.
- Several pages use it. DebugBear's write-up on data URLs notes that "Images embedded directly in HTML also can't be cached separately by the browser." Every page that inlines it pays for it again.
- The CSS carries it. "Since CSS is a render-blocking resource, any CSS with large Base64 images could be unnecessarily big," per DebugBear. The page waits for those bytes before it paints anything.
- Nobody sees it without scrolling. A separate file can be lazy-loaded. An inlined one downloads with the page whether anyone scrolls to it or not.
- You edit it often. Editing the image means changing, and re-downloading, the whole HTML or CSS file around it.
DebugBear's example is a page whose HTML "exceeded 1 megabyte, far above the usual HTML file size, which is typically below 100KB."
When a data URI is the right call
A data URI fits a tiny image that is needed immediately and used in one place. DebugBear's summary is that "Base64 images are best suited for small images such as icons," and the benefit is that they "eliminate the need for an extra request to load the resource."
Good fits include a small logo in an HTML email template, a status badge in a single-file report, or an icon in a self-contained demo page you'll send to someone.
My take: if you're unsure, don't inline. A separate file is easy to cache, easy to swap and easy to debug in DevTools. Inline only after you've measured a real gain on that page.
Size limits and browser rules
There's no single maximum length for a data URI. MDN says "Browsers are not required to support any particular maximum length of data," and lists that "Chromium and Firefox limit data URLs to 512MB, and Safari (WebKit) limits them to 2048MB."
Browsers are only part of the picture. RFC 2397 warns that "some applications that use URLs may impose a length limit," so an email client, a CMS field or a database column may cut the string long before the browser would.
Two more browser rules catch people out. MDN notes that "top-level navigation to data: URLs is blocked in all modern browsers," so pasting one into the address bar from a link won't open it. Data URLs are also treated as unique opaque origins, so scripts inside them don't share your site's origin.
How to check a data URI you already have
To check a data URI, strip the prefix and decode the rest. If the bytes start the way the file type should, the encoding is fine.
You can paste a data URI into the Base64 decoder, which recognises the data: prefix and decodes the payload in your browser. A limitation: it works on pasted text, not uploaded files, so it won't turn an image file into a data URI for you. Use the FileReader or Node snippets above for that step.
If the decoded output looks like garbage when you expected text, the input may be Base64URL rather than standard Base64. The Base64 vs Base64URL guide explains how to tell them apart. If atob() throws an error, see why atob says the string is not correctly encoded.
FAQ
What does a Base64 image data URI look like?
It starts with data:, then the MIME type, then ;base64, then the encoded bytes, for example data:image/png;base64, followed by the Base64 text of the PNG file.
Does a data URI image get cached?
Not on its own. The browser caches the HTML or CSS file that contains it, so the image is downloaded again whenever that file changes or is fetched again.
Is there a size limit for data URIs?
Browsers are not required to support any particular length. MDN lists Chromium and Firefox at 512MB and Safari at 2048MB, but other tools that handle URLs may cut them much shorter.
Why does my decoded data URI fail to open as an image?
Usually the data:image/...;base64, prefix is still attached. Remove everything up to and including the comma before you Base64-decode the rest.