How to get byte length of a base64 string in node.js?

Viewed 9394

I'd like to calculate the size of an image file received as base64 encoded string like:

'data:image/png;base64,aBdiVBORw0fKGgoAAA...'

in order to make sure that the file is not larger than certain size, say 5MB.

How can I acheive this in node.js?

I've seen similar question here but could not apply the answer in my node app as I get:

SyntaxError: Unexpected token :
3 Answers

You need to remove the data... part

const img = 'data:image/png;base64,aBdiVBORw0fKGgoAAA';
const buffer = Buffer.from(img.substring(img.indexOf(',') + 1));
console.log("Byte length: " + buffer.length);
console.log("MB: " + buffer.length / 1e+6);

Actually, there is not much to it. If you know the size of the Base64 image all you have to do is divide by 1.37. As Base64 algorithm is linear the result is also. For more info see here.

To calculate the string size that you already have you can use this solution:

function byteCount(s) {
    return encodeURI(s).split(/%..|./).length - 1;
}

and divide the result by 1.37.

var src = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7";

var base64str = src.substring(src.indexOf(',') + 1)
var decoded = atob(base64str);

console.log("FileSize: " + decoded.length);
Related