14

I do not have very clear what a base64 string is or how it is related to a file.

Right now I have a website that uploads an image as a base64 string to my server. This string is converted back into a bitmap and resized. However, I would like the least amount of memory to be consumed in my server, therefore I would like to restrict the file size of the images being uploaded without processing them.

Is there a way to know the file of a size without actually saving the file into an stream?

luisgepeto
  • 257
  • 1
  • 2
  • 4

2 Answers2

19

You can calculate the file size (in bytes) using below formula:

x = (n * (3/4)) - y

Where:

1. x is the size of a file in bytes

2. n is the length of the Base64 String

3. y will be 2 if Base64 ends with '==' and 1 if Base64 ends with '='.

You can read the algorithm here Base 64 wiki

Harish Moyal
  • 191
  • 1
  • 2
10

Edit: apologies for blatantly wrong info. Acording to this Wikipedia article, it will be a bit larger:

Very roughly, the final size of Base64-encoded binary data is equal to 1.37 times the original data size + 814 bytes (for headers).

You can use ContentLength property of the request to determine what the size is in bytes, although if you are uploading more then one image, it might be trickier.

Alexus
  • 2,368
  • 15
  • 24
  • To help clarify this answer: Each character in a base64 string represents 6 bits, and each of those characters is 8 bits/1byte. So if you know the size of your headers, the size of the image will be `(contentLengthBytes - headerLengthBytes) * 6 / 8` – Maybe_Factor Feb 27 '18 at 00:41
  • i thought the 6:8 ratio would make sense, but then if 8/6=1.333, where does 1.37 come from? – Alexander Taylor Dec 30 '21 at 12:52