简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM