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) })
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');
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!