Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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();
image.src = 'data:image/jpeg;base64,someBase64ImageString';

console.log(image.width + 'x' + image.height);

I cannot figure out how to get this information.

like image 782
methgaard Avatar asked Jun 01 '17 11:06

methgaard


People also ask

How do I find the size of an image in Base64?

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.

How do I decode a Base64 file?

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.

Does converting image to Base64 reduce size?

It will be bigger in base64. Base64 uses 6 bits per byte to encode data, whereas binary uses 8 bits per byte.


1 Answers

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.

like image 172
Emissary Avatar answered Sep 20 '22 17:09

Emissary