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!