7

I have a file encoded in Base64 with a certain file length. How do I get the size in bytes?

Example:

var size= canvas.toDataURL();   

console.log(resizeCanvasURL.length);


// -> 132787  base64 length
daisy
  • 615
  • 2
  • 8
  • 15
  • You mean the length of the file after you decode it from base64? You have to decode it first. – Robert Harvey Jul 01 '13 at 16:41
  • Base64 - 5 bits, Normal chars - 8 bits => `size * 1.6` – mishik Jul 01 '13 at 16:43
  • Take a look at: http://stackoverflow.com/questions/1533113/calculate-the-size-to-a-base-64-encoded-message and (http://stackoverflow.com/questions/4715415/base64-what-is-the-worst-possible-increase-in-space-usage) (you will need to reverse those formulas) – Anthony Accioly Jul 01 '13 at 16:48

3 Answers3

10

Each symbol in Base64 encoding holds 6 bits of information. Each symbol in normal file hold 8 bits. Since after decoding you have the same amount of information you need:

normal file size - 1000 bytes
base64 file size - 1333 bytes
mishik
  • 9,973
  • 9
  • 45
  • 67
8

The answer from mishik is wrong.

Base64 is filled up with =-chars (to have the right amount of bits). So it should be

    var byteLength = parseInt((str).replace(/=/g,"").length * 0.75));
Vincent Hoch-Drei
  • 603
  • 2
  • 7
  • 21
0
const stringLength = resizeCanvasURL.length 
const sizeInBytes = 4 * Math.ceil(stringLength / 3) * 0.5624896334383812;
const sizeInKb = sizeInBytes / 1000;

OR

 const stringLength = resizeCanvasURL.length 
 const sizeInBytes = stringLength * (3 / 4) - 2;
 const sizeInKb = sizeInBytesNew / 1000;