1

My code (adapted from answer on embedding image data here: Convert binary data to base64 with javascript)

<!DOCTYPE HTML>
<HTML>
<HEAD>

<script src ="./jquery-3.3.1.min.js" type="text/javascript"></script>
<script>
console.log('test');
$(function() {
  $.ajax({url:'favicon2.png'}).done(function(data) {

    console.log('data length: ' + data.length);
    document.getElementById('ta').value = btoa(unescape(encodeURIComponent(data)));
    var img = document.createElement("img");
    img.src = "data:image/png;base64," + btoa(unescape(encodeURIComponent(data)));
    document.body.appendChild(img);
    console.log('done');
  });
});
</script>
</HEAD>
<BODY>
<textarea id='ta'>

</textarea>
</BODY>
</HTML>

This code is not generating valid base64 image data. I tested by taking the string in the textarea and creating a static img with it. I also tested using the string from the question here: Add image into div and convert base64 string into thumbnail using jQuery

The string from the SO question is working and the image loads. But my image is not loading - neither dynamically or statically. I tried both the suggestions about substituting decodeURI for unescape and use FileReader but neither worked.

So my question is: What am I doing wrong/why is the base64 image data I am producing incorrect?

PS. I also noticed that data.length was 3 bytes less than it appears to be when I open the file properties through windows OS.

ControlAltDel
  • 33,923
  • 10
  • 53
  • 80

1 Answers1

0

I found an answer that worked for me here: How can I convert an image into Base64 string using JavaScript?

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();
}

$(function() {

//toDataURL('https://www.gravatar.com/avatar/d50c83cc0c6523b4d3f6085295c953e0', function(dataUrl) {
toDataURL('favicon2.png', function(dataUrl) {
  console.log('RESULT:', dataUrl)
  var img = document.createElement("img");
  img.src = dataUrl;
  document.body.appendChild(img);
  
});
ControlAltDel
  • 33,923
  • 10
  • 53
  • 80