Convert Image to Base64 String in JavaScript
When interacting with remote servers or handling image data in JavaScript, converting images to Base64 strings becomes a necessity. A Base64 string represents binary data in a text format, enabling secure transmission of images over networks.
There are several techniques available for this conversion:
1. FileReader Approach:
This approach involves loading the image as a blob using XMLHttpRequest and then employing the FileReader API's readAsDataURL() method to transform it into a dataURL. A dataURL consists of a header (indicating the data format) and the Base64-encoded image data.
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) })
By passing the dataURL to the callback function, you can retrieve the Base64-encoded image string.
The above is the detailed content of How to Convert an Image to a Base64 String in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!