开发者

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 win开发者_JAVA技巧ning or losing by using converting it.


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜