Carlos Aguni

Highly motivated self-taught IT analyst. Always learning and ready to explore new skills. An eternal apprentice.


Download image bitmap

30 Sep 2021 »

https://github.com/chromium/chromium/blob/master/third_party/blink/web_tests/http/tests/security/cross-origin-createImageBitmap.html

https://stackoverflow.com/questions/6150289/how-can-i-convert-an-image-into-base64-string-using-javascript

You can use the HTML5 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).

try

<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/6.2.0/d3.min.js"></script>
</head>
<body>
  <script>
    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();
    }
    let url = "https://miro.medium.com/fit/c/64/64/1*ty4NvNrGg4ReETxqU2N3Og.png"
    toDataURL(url, dataUrl => {
      console.log(dataUrl)
    })
    let canvas = d3.select('body').append('canvas')
    canvas.attr('width', '400px')
    canvas.attr('height', '400px')
    let ctx = canvas.node().getContext('2d')

    let img = new Image()
    img.src = url
    img.onload = function (){
      ctx.drawImage(img, 100, 100)
    }

    d3.select('body')
      .append('img')
      .attr('src', url)
      .on('load', e => {
        console.log('loaded', e)
        createImageBitmap(e.target).then(sprite => {
          ctx.drawImage(sprite, 0, 0)
        })
      })
  </script>
</body>
</html>k