Get Image File Size From Base64 String

Viewed 12874

I'm working on a python web service. It calls another web service to change the picture of a profile.

It connects to another web service. This web service can only accept pictures that are 4 MB or smaller.

I will put the checking in the first web service. It uses PIL to check if the base64 string is a valid image. However, how do I check if the base64 string will create a 4 MB or smaller image?

3 Answers

image size can be calculated from the string length. Since every character represents 6 bits and every '=' sign shows lack of 8 bits. ref

file_size = (len(base64_string) * 6 - base64_string.count('=') * 8) / 8

or

file_size = len(base64_string) * 3 / 4 - base64_string.count('=')

will give the file size in byte and, dividing it in mega(=1000000) will give the file size in megabyte

Related