Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 can I test the before and after size? ie. the image file size and the size of the base 64 string. I want to check if I am winning or losing by using converting it.

like image 678
amateur Avatar asked Feb 02 '11 23:02

amateur


1 Answers

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

int base64EncodedSize = 4 * originalSizeInBytes / 3;

Depending on how the data is padded it might be off by a character or two but that shouldn't make a difference.

Also, if you suspect base64 might be more efficient, what on earth are you comparing it with? Compared to raw binary, it always causes a 33% increase in size.

like image 154
Matti Virkkunen Avatar answered Sep 26 '22 10:09

Matti Virkkunen