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();
image.src = 'data:image/jpeg;base64,someBase64ImageString';
console.log(image.width + 'x' + image.height);
I cannot figure out how to get this information.
Base64 encodes 3 bytes of binary data on 4 characters. So to get the size of the original data, you juste have to multiply the stringLength (minus the header) by 3/4.
To decode a file with contents that are base64 encoded, you simply provide the path of the file with the --decode flag. As with encoding files, the output will be a very long string of the original file. You may want to output stdout directly to a file.
It will be bigger in base64. Base64 uses 6 bits per byte to encode data, whereas binary uses 8 bits per byte.
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 = new Image;
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With