0

I know base64 encoded binary data is equal to 1.37 times the original data according to Wikipedia.

What if you decode that string with php function base64_decode($encoded_string); and then make image out of that imagecreatefromstring($data); like so:

//Decode 
$data = base64_decode($encoded_string);

//Create image
$img = imagecreatefromstring($data);
$output = imagejpeg($img, $filepath, 100);

My question is, will the final file size of the image also be 1.37 times the original data? Currently I think so but I am not 100% sure what causes my final picture size to be larger.

2
  • 2
    No, the result of base64_decode($encoded_string) should be exactly your original image, so the same size. Commented Aug 4, 2016 at 9:46
  • How is the image encoded? Commented Aug 4, 2016 at 15:05

1 Answer 1

1

The base64 encoding is a way to encode binary data using only a set to 64 printable characters.

The trick is to regroup the original bits in packets of 6 bits (6 bits can take a value from 0 to 63) and then send the corresponding letter in its ascii encoding of 8 bits. So each group of 3 binary bytes (3*8=24 bits) can be encoded into 4 base64 digits (4x6=24). If your total number of bytes is not a multiple of 3, your 4 last base64 digits will have some padding characters that will tell about the number of useless bits.

So the exact length of the base64 encoding is: floor((binary_size+2) / 3) * 4 . The ratio base64/original converges to 4/3 for large sizes, but for small data the ratio can be higher (e.g. time 4 for a 1 byte original message). As base64_encode() encodes in MIME compliant way, you have to count in addition the newlines (at least one every 76 base64 chars).

For decoding it's just the opposite. To calculate the exact length you'd need to know if there's one or two padding characters at the end, but if you want to know a maximum size, it's just (base64_size/4)*3.

But regardless of the more or less inflated size of the base64 encoding: your decoded image should have exactly the same size than the encoded one. The base64 encoding schema guarantees that.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.