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

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

DDD
Release: 2024-12-20 14:12:11
Original
520 people have browsed it

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

Convert an Image to Base64 String in JavaScript

Converting an image to a Base64 string is a common task in web development, especially when you need to send an image to a server. Here are two popular JavaScript approaches to achieve this:

1. FileReader Approach:

This approach utilizes the FileReader API to read the image as a blob and then convert it to a data URL:

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

2. HTML Canvas Approach:

Another option is to create an HTML canvas, draw the image onto it, and then convert the canvas to a data URL:

const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');

// Resize the canvas to the image's size
canvas.width = image.width;
canvas.height = image.height;

// Draw the image onto the canvas
ctx.drawImage(image, 0, 0);

// Convert the canvas to a data URL
const dataUrl = canvas.toDataURL('image/jpeg');
Copy after login

The above is the detailed content of How Can I Convert an Image to a Base64 String 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template