Home >Web Front-end >JS Tutorial >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) })
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!