跳到主要内容

Image to Data URL Online

Image size: 507 B

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:

  1. The prefix data:
  2. A MIME type indicating the data format ([<mediatype>]). See mime-db for all MIME types
  3. An optional ;base64 token for binary data (e.g. images)
  4. 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:

  1. Blob → FileReader → Data URL
  2. 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
    }
  }
}