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
Release: 2024-12-19 19:10:14
Original
501 people have browsed it

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();
}
Copy after login

Using this function:

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

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!

source:php.cn
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