Home > Web Front-end > JS Tutorial > How to Convert an Image to a Base64 String in JavaScript?

How to Convert an Image to a Base64 String in JavaScript?

Susan Sarandon
Release: 2024-12-27 16:54:15
Original
925 people have browsed it

How to Convert an Image to a Base64 String in JavaScript?

Convert Image to Base64 String in JavaScript

When interacting with remote servers or handling image data in JavaScript, converting images to Base64 strings becomes a necessity. A Base64 string represents binary data in a text format, enabling secure transmission of images over networks.

There are several techniques available for this conversion:

1. FileReader Approach:

This approach involves loading the image as a blob using XMLHttpRequest and then employing the FileReader API's readAsDataURL() method to transform it into a dataURL. A dataURL consists of a header (indicating the data format) and the Base64-encoded image data.

function toDataURL(url, callback) {
  var xhr = new XMLHttpRequest();
  xhr.onload = function() {
    var reader = new FileReader();
    reader.onloadend = function() {
      callback(reader.result);
    }
    reader.readAsDataURL(xhr.response);
  };
  xhr.open('GET', url);
  xhr.responseType = 'blob';
  xhr.send();
}

toDataURL('https://www.gravatar.com/avatar/d50c83cc0c6523b4d3f6085295c953e0', function(dataUrl) {
  console.log('RESULT:', dataUrl)
})
Copy after login

By passing the dataURL to the callback function, you can retrieve the Base64-encoded image string.

The above is the detailed content of How to Convert an Image to a Base64 String in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template