Skip to content Skip to sidebar Skip to footer

Get Dimensions From Base64 Encoded Image

I have an Angular application where i need the dimensions of an Base64 encoded image. I have tried to load it into an Image but it just says it is 0x0 const image = new Image();

Solution 1:

The step between setting the src and the image being in a "loaded" state (thus having dimensions) is asynchronous - this seems to apply to data URIs as well as external resources (at least in Chrome).

To safely guarantee the width and height are populated, logic should be run in a callback - i.e.

let im = newImage;
im.src = 'data:image/png;base64,whatever';
im.onload = () =>console.log(im.width);

Note this is only an issue the first time an image is loaded, your code works as-is for successive calls - presumable this has something to do with the way the browser is processing and caching the data.

Solution 2:

Make sure you prepend src with data:image/png;base64,

So it should be

img.src= 'data:image/png;base64,' + b64string;

Post a Comment for "Get Dimensions From Base64 Encoded Image"