Home >Web Front-end >JS Tutorial >How to Encode Images to Base64 Strings in JavaScript?

How to Encode Images to Base64 Strings in JavaScript?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-19 19:10:14566browse

How to Encode Images to Base64 Strings in JavaScript?

Encoding Images to Base64 Strings in JavaScript

Question:

How can I convert an image to a Base64-encoded string in JavaScript? This conversion is necessary to send the image to a server for further processing.

Solution:

Approach 1: FileReader

Utilizing the FileReader API, you can initiate XMLHttpRequest to retrieve the image as a blob and then process it.

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

Using this function:

toDataURL('https://www.gravatar.com/avatar/d50c83cc0c6523b4d3f6085295c953e0', dataUrl => {
  console.log('RESULT:', dataUrl);
});

The above is the detailed content of How to Encode Images to Base64 Strings in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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