I have found some answers related to the topic from How can I convert an image into Base64 string using JavaScript?. I realized they don't have an image on the div tag. Is it possible if I would have the image source?
Answer added for people who want to reference
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("output").src = newImage.src;
alert("Converted Base64 version is " document.getElementById("output").src);
console.log("Converted Base64 version is " document.getElementById("output").src);
}
fileReader.readAsDataURL(fileToLoad);
}
}
<input id="inputFileToLoad" type="file" onchange="encodeImageFileAsURL();" />
<img src="https://mdbootstrap.com/img/Photos/Others/placeholder-avatar.jpg" id="output" width="100" height="100" style="border-radius: 50%;" />
I would like to use the image source to load the image and find out the base 64. Is it possible? Besides using div to create 1 image out where it can't be customized.
CodePudding user response:
I think you want to do this https://jsfiddle.net/samet19/yv9a4op8/
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("output").src = newImage.src;
}
fileReader.readAsDataURL(fileToLoad);
}
}