嗨我想通过套接字xml发送这样的内容。
<root>
<image ID='2'>
<![CDATA[ binary data with image ]]>
</image>
</root>
我有问题因为图像是二进制数据而其他部分是字符串。我发送了多张图片,我需要有ID。
主要问题是如何处理二进制数据和字符串数据。我试图将图像转换为str但我无法恢复它。
答案 0 :(得分:2)
在xml
中嵌入二进制文件的一种有用方法是对其进行base64编码。这是XAML
用于发送小图像的方法。您可以在代码中的某处执行此操作:
import base64
img = open('some.png',rb').read()
base64.b64encode(img)
# append it to your buffer
另一方面:
#get the img portion in the buffer
import base64
img = base64.b64decode(fetched_img)
# write it to disk or whatever
这是处理XML
内的二进制文件的标准/通常方法。
使用base64
非常简单,这是解释器中的一个示例:
In [1]: import base64
In [4]: base64.b64encode('example')
Out[4]: 'ZXhhbXBsZQ=='
In [5]: base64.b64decode('ZXhhbXBsZQ==')
Out[5]: 'example'
您可以阅读the docs here。
希望这有帮助!
答案 1 :(得分:0)
只需将套接字连接为二进制文件 - 它无论如何都是你可能并不关心换行转换。