Q:

Manually storing picture to mongo db using python2.7

I need to transfer .png picture with multiple HTTP Posts (Arduino cant send it at once). On the server side I need to store that picture to Mongo DB in multiple entries. Then, I need to be able to reassemble and display it on a website.
This is my approach of how I will handle it (offline):
f = open("icon.png", "rb").read()
length = len(f)
chunk1 = base64.b64encode( f[length/2:] )
chunk2 = base64.b64encode( f[:length/2] )

//Store to db
//Retrieve from db into chunk1, chunk2
//Here is the simple idea behind what I want to do(which works fine if I store and retrieve the entire image in one db entry):

html_img = '<img src="data:image/png;base64,{0}{1}">'.format(chunk1.decode(), chunk2.decode())

It does not work. When I retrieve the two chunks they look somewhat like this:
chunk1: iVBORw0KGgoAAAANSUhEUg==
chunk2: AAABAAAAAQAIBgAAAFxyqA==

The whole chunk stored and retrieved in the same fashion looks like this:
iVBORw0KGgoAAAANSUhEUgAAAQAAAAEACAYAAABccqg=

I know I lack understanding in the topic, I hope someone could point the right approach to my problem.

A:

The problem you are having has to do with the handling of padding.
Base-64 units are 6-bits, so every 3 bytes create 4 b64 characters. If the original number of bytes is not a multiple of 3, the 0-value bytes are added to pad out to a multiple of 3. The number of pad ding bytes is indicated by the = characters.
In your example, each half has a single extra byte (needing 2 bytes padding) while the whole string only needed 1.
The second problem is with the <img> tag. If you want to use base64, then you shouldn't be decoding it first; just leave it base 64. The problem is that you can just concatenate the strings the way you have split them.
The solution is to make sure the first chunks are all made from a multiple of 3 bytes. That way, there will be no padding for those, and you can just concatenate the b64 strings together correctly. Only the last chunk will have padding, and the characters will be the same as if you encoded the whole thing at once.

