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

How Can I Convert an Image to a Base64 String Using JavaScript?

Susan Sarandon
Release: 2024-12-18 06:25:10
Original
423 people have browsed it

How Can I Convert an Image to a Base64 String Using JavaScript?

Converting Image to Base64 String with JavaScript

The Requirement:

You need to convert an image into a Base64 string to send it to a server.

The Solutions:

JavaScript offers several approaches for image-to-Base64 conversion.

1. FileReader Approach:

This approach utilizes the FileReader API (specifically, readAsDataURL()) to convert a blob loaded from an image URL into a dataURL.

Code Example:

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

This approach involves using XMLHttpRequest to fetch the image as a blob and then employing FileReader to convert it to a dataURL.

The above is the detailed content of How Can I Convert an Image to a Base64 String Using 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