0

I am trying to get the base64 of some images in Javascript and was using this function:

function getBase64Image(img) {
    return new Promise((data) => {
        var canvas = document.createElement("canvas");
        canvas.width = img.naturalWidth;
        canvas.height = img.naturalHeight;
        var ctx = canvas.getContext("2d");
        ctx.drawImage(img, 0, 0);
        data(canvas.toDataURL("image/png").replace(/^data:image\/(png|jpg|jpeg);base64,/, ""))
    })
}

Then I call the function to load in the image using:

var img = new Image();
img.crossOrigin = 'Anonymous';
img.onload = function () {
    getBase64Image(this).then(data => {})
}
img.src = wha[1][0]

If I look at the naturalWidth of the image (96px), it is different from the actual image itself (640px). I had been looking at other methods of getting base64 from an image but they also return the same results.

J370
  • 1
  • 1
  • Please supply details of where, when, and how are you measuring the image width of 640px. Also does supplying natural width and height values of the downloaded image to the `canvas.drawImage` method, as its fourth and fifth arguments, make a difference? – traktor May 24 '21 at 06:20
  • Hi @traktor, I don't think it has anything to do with the canvas itself because if I were to do a breakpoint for the image once it had been loaded, the width and height are already incorrect. The width I measured is by opening the URL and just viewing the image itself. – J370 May 24 '21 at 08:29
  • I assume that this a problem with a particular image and not all images. Have you seen [How do I get natural dimensions of an image using javascript or jquery?](https://stackoverflow.com/q/16342936/5217142), which has multiple answers about a similar problem. – traktor May 24 '21 at 09:35
  • Hi @traktor, nopes, this problem occurs with all the images that I query. I had looked through the link that you shared but I can't see any errors that might have occured. I am also doing this in chrome extension. Not sure if that affects anything but I did faced some problems in relation to that before. – J370 May 24 '21 at 11:31

0 Answers0