How Data URLs Work
Use this image to Data URL online converter to turn uploads into Base64 Data URIs for inline HTML and CSS embedding. A Data URL consists of four parts:
- The prefix
data: - A MIME type indicating the data format (
[<mediatype>]). See mime-db for all MIME types - An optional
;base64token for binary data (e.g. images) - The data itself
data:[<mediatype>][;base64],<data>
Any resource with a valid MIME type can be represented as a Data URL — not just images.
Converting Images to Data URLs
There are two common approaches to generate a Data URL from an image:
- Blob → FileReader → Data URL
- Blob → ArrayBuffer → Data URL
Here is an implementation using the FileReader API:
function blobToDataURL(blob: Blob): Promise<string> {
const reader = new FileReader();
return new Promise((resolve, reject) => {
reader.addEventListener('load', () => {
const url = reader.result as string
resolve(url)
}, false)
reader.addEventListener('error', (e) => {
reject(e)
}, false)
reader.readAsDataURL(blob)
})
}
Practical Use in Build Tools
In front-end engineering, images smaller than about 8 KiB are often inlined as Base64 Data URLs within the HTML, eliminating extra HTTP requests and improving page performance.
Webpack 4 configuration:
module.exports = {
module: {
rules: [
{
test: /\.(png|jpg|gif)$/i,
use: [
{
loader: 'url-loader',
options: {
limit: 8192,
}
},
],
},
]
}
}
Webpack 5 configuration:
{
test: /\.(png|jpe|gif)$/,
type: 'asset',
parser: {
dataUrlCondition: {
maxSize: 8192
}
}
}