Convert image to base64 and check size

I am using the following C # code to convert an image file to a base64 string

using (var fs = new FileStream(filename, FileMode.Open, FileAccess.Read)) { var buffer = new byte[fs.Length]; fs.Read(buffer, 0, (int)fs.Length); var base64 = Convert.ToBase64String(buffer); } 

How to check the size before and after? i.e. image file size and base line size 64. I want to check if I won or lost using it.

+4
source share
2 answers

You can calculate it using simple math. One base64 character represents 6 bits, and therefore four characters represent three bytes. Thus, you get 3/4 bytes per character. What gives:

 int base64EncodedSize = 4 * originalSizeInBytes / 3; 

Depending on how the data is supplemented, it can be disabled by a symbol or two, but this should not change.

Also, if you suspect base64 might be more efficient, what do you compare this to? Compared to the source binary, it always causes a 33% increase.

+7
source

You lose - the base64 string will use more bytes for storage than your original image. Perhaps a lot more if it's all in memory: the strings in .Net are unicode, so they use twice as many bytes than an ASCII encoded string.

0
source

Source: https://habr.com/ru/post/1338176/


All Articles