1

Hi i want send via socket xml like this.

<root>
  <image ID='2'>
    <![CDATA[ binary data with image ]]>
  </image>
</root>

I have problem because image is binary data and other part is string. I am sending multiple images and i need to have ID.

The main problem is what to do with binary data and string data. I tried to convert image to str but i cant revert this.

4
  • You can't just, say, base64-encode it, then base64-decode on the other end? Commented Jun 25, 2013 at 14:34
  • I never used base64-encode and i dont knew how to use it. Commented Jun 25, 2013 at 14:37
  • What code do you have so far? Commented Jun 25, 2013 at 14:39
  • I have everything expect sending image but now i will finish this. Commented Jun 25, 2013 at 14:44

2 Answers 2

2

A useful way to embed binary in xml is base64-encoding it. This is the approach XAML uses to send small images for example. You may do like this somewhere in your code:

import base64
img = open('some.png',rb').read()
base64.b64encode(img)

# append it to your buffer

And on the other side:

#get the img portion in the buffer
import base64
img = base64.b64decode(fetched_img)
# write it to disk or whatever

This is the standard/usual way to treat binary files inside XML.

Using base64 is very simple, this is a example in the interpreter:

In [1]: import base64
In [4]: base64.b64encode('example')
Out[4]: 'ZXhhbXBsZQ=='
In [5]: base64.b64decode('ZXhhbXBsZQ==')
Out[5]: 'example'

You can read the docs here.

Hope this helps!

Sign up to request clarification or add additional context in comments.

5 Comments

Inside CDATA[ ... ] there should be only the b64encoded file so this line: stringResult = base64.b64decode(stringResult) + base64.b64encode(f.read()) should be like this I guess: stringResult = base64.b64encode(f.read()). I don't see where you decode it though. Somewhere in the receiver, should be: img_str=CDATA (pseudocode here), img = base64.b64decode(img_str) to get the binaries into img
I have problem because if i want encoded image to string. It is conversion error. If i cast to strin base64 it is parsing but i dont knew how to revert str
Wow, I don't understand you quite well. The order is this: you b64encode something and it returns a string. Then you b64decode it and get what you first encoded back.
Yeah this is order byt b64encode returns bytes not string. Thats why i have problem.
I was able to encode, contatenate and later decode with a binary .pdf file. I don't know what your problem might be. You maybe want to open a new different question about your new problem.
0

Just connect the socket as binary - it is anyway and you probably don't care about newline conversion anyway.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.