-3

So what I did up to now :

I have a file "http://www.example.com/picture.png"

And I read it into a variable

    function aGET(uri, callback) {
        let xhttp = new XMLHttpRequest();
        xhttp.open("GET", uri );
        xhttp.send();
        xhttp.onreadystatechange = function() {
            if ( this.readyState === 4 && callback ) {
            callback(xhttp.responseText);
            };
        };
    }

    uurl = "http://www.example.com/picture.png";
    
    aGET(uurl, function(logoImage) { 
        console.log("logoImage : "+logoImage);
    });

At this moment logoImage looks like this, it is a binary format but does not appear to be a blob:

�PNG

� ��� IHDR�������v�������ܛ����zTXtRaw profile type exif��x��Yr#9�E��

because when I tried to transform it into a base64 with btoa

    aGET(uurl, function(logoImage) { 
      var base64EncodedStr = "data:image/png;base64," + btoa(unescape(encodeURIComponent(logoImage)));
      console.log("base64EncodedStr : "+base64EncodedStr );
    });

I received some wired string that looks like a base64 but is none.

data:image/png;base64,R0lGODlhDAAMAKIFAF5LAP/zxAAAANyuAP/gaP///wAAAAAAACH5BAEAAA

So my Question is still open: How can I transform it into base64 to get something like this :

Max Muster
  • 1,490
  • 2
  • 14
  • 40
  • 2
    Why not just use `imgElement.src = 'http://www.example.com/picture.png';`? You haven't been drinking the Decaf, have you? – StackSlave Apr 13 '21 at 00:20
  • 2
    Can you explain why you're using AJAX to get this image rather than just creating an `` and seeing the `src` property? – Tangentially Perpendicular Apr 13 '21 at 00:20
  • @StackSlave hi, ice to meet you :)) eeeehm I try it in a minute but my question is how to transform this. I want to learn JavaScript. – Max Muster Apr 13 '21 at 00:31
  • @TangentiallyPerpendicular also nice to meet you :)) as I said, I am in the process to learn JavaScript, so I try different things. – Max Muster Apr 13 '21 at 00:33

1 Answers1

2

You can use URL.createObjectURL(blob)

fetch('https://placekitten.com/300/300').then(res => res.blob())
  .then(blob => {
    document.querySelector('img').src = URL.createObjectURL(blob);
  })
img {
  width: 300px;
  height: 300px
}
<img>
charlietfl
  • 169,044
  • 13
  • 113
  • 146
  • I was too fast, and didn't realize that this solution also creates only a blob. My question was how to create a base64 from an image. Quickly you have dispatched me and deleted the question. – Max Muster Apr 14 '21 at 13:13
  • What is this tricky thing :)) why is it not working with https://www.ccc.de/images/header.png ?? – Max Muster Apr 14 '21 at 15:57