Take the 2-minute tour ×

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

            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.

share|improve this question
For reading into the buffer, try var buffer = File.ReadAllBytes(filename); –  Jim Mischel Feb 2 '11 at 23:57

2 Answers 2

up vote 7 down vote accepted

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.

share|improve this answer
Actually a 167% increase, since Convert.ToBase64String returns a unicode string. –  MusiGenesis Feb 2 '11 at 23:47
@MusiGenesis: ...which, when encoded using a proper transport encoding (UTF-8), doesn't take any more space than a latin-1 string, for instance. –  Matti Virkkunen Feb 2 '11 at 23:49
True, but while it's still a .Net string it's twice as big. I'm not sure what this person is trying to accomplish, but you're right that they're presumably sending this somewhere, and not keeping it in-memory or writing it into a DB text field or something. –  MusiGenesis Feb 2 '11 at 23:52

You're losing - the base64 string will use more bytes to store than would your original image. Possibly a lot more, if this is all in-memory: strings in .Net are unicode, so they use twice as many bytes as an ASCII-encoded string would.

share|improve this answer

Your Answer


