How to convert image into base64 string using javascript
I need to convert my image to a base64 string so that i can send my image to a server. Is there any js file for this... ? Else how to convert it
You can use the HTML5 <canvas>
for it:
Create a canvas, load your image into it and then use toDataURL()
to get the base64 representation (actually, it's a data:
URL but it contains the base64-encoded image).
There are multiple approaches you can choose from:
1. Approach: FileReader
Load the image as blob via XMLHttpRequest and use the FileReader API to convert it to a dataURL:
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 snippet could convert your string,image and even video file to base64 string data. Try it once...
<input id="inputFileToLoad" type="file" onchange="encodeImageFileAsURL();" />
<div id="imgTest"></div>
<script type='text/javascript'>
function encodeImageFileAsURL() {
var filesSelected = document.getElementById("inputFileToLoad").files;
if (filesSelected.length > 0) {
var fileToLoad = filesSelected[0];
var fileReader = new FileReader();
fileReader.onload = function(fileLoadedEvent) {
var srcData = fileLoadedEvent.target.result; // <--- data: base64
var newImage = document.createElement('img');
newImage.src = srcData;
document.getElementById("imgTest").innerHTML = newImage.outerHTML;
alert("Converted Base64 version is " + document.getElementById("imgTest").innerHTML);
console.log("Converted Base64 version is " + document.getElementById("imgTest").innerHTML);
}
fileReader.readAsDataURL(fileToLoad);
}
}
</script>
链接地址: http://www.djcxy.com/p/22140.html
上一篇: 如何编码和解码base64字符串?