0

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.

2
  • Do you mean you have this structure: <div><img src="someUrl"></div> and you want to convert that image ? Then do const url = document.querySelector('img').getAttribute('src'); and use that URL in one of the solutions provided in your link. Commented Dec 24, 2021 at 13:59
  • yeap :) i wan to use the image and as well display the base 64 string Commented Dec 24, 2021 at 14:04

1 Answer 1

1

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);
  }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Yes i wan do that as well display a base 64 string data as well

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.