0

Hi i have problem because i wanted to have xml file with binary. The problem is with base64 encoding i dont knew how to encode image and add to string. I want after that parse this and decode image.

stringResult = ResultXMLTag.ROOT_BEGIN + '\n'

f = open('id_'+str(1)+'.png','rb+')

stringResult += ResultXMLTag.RESULT_BEGIN+' '+'ID=\'1\'>\n'
stringResult += ResultXMLTag.CDATA_BEGIN+'\n'
stringResult += base64.b64encode(f.read())

stringResult2 = '\n'+ ResultXMLTag.CDATA_END+'\n'
stringResult2 += ResultXMLTag.RESULT_END+'\n'
stringResult2 += ResultXMLTag.ROOT_END
    return stringResult + stringResult2

data = ET.fromstring(self.downloadData(connection))
for result in data.findall('./RESULT'):
    _id = result.get('ID')
    out = open('id_'+_id+'.png','wb+')
    out.write(base64.decode(result.findtext('').encode()))

EDIT error is in line with base64 "TypeError: Can't convert 'bytes' object to str implicitly"

EDIT example

>>> x = b'cat' + (base64.b64encode(b'dog'))
>>> x
b'catZG9n'

second version

>>> x = 'cat' + str(base64.b64encode(b'dog'))
>>> x
"catb'ZG9n'"

Witch version i should use to send image? I think all my problem are because how u append string and bytes. It simple to say encode image and then decode but this is not in my situation.

Luffy
  • 677
  • 1
  • 6
  • 19

2 Answers2

2

In Python 3, b64encode returns a byte string. You need to convert that to a Unicode string. The output is guaranteed to be ASCII bytes so the conversion is trivial.

stringResult += base64.b64encode(f.read()).decode('ascii')
Mark Ransom
  • 299,747
  • 42
  • 398
  • 622
0

UPDATE: The problem could also be with downloadData(). Are you using urlopen()? Are you sure you are explicitly converting to string after you receive from downloadData()?

The problem could be with how you are creating your XML. In line:

stringResult += ResultXMLTag.RESULT_BEGIN+' '+'ID=\'1\'>\n'

Where are the quotes around the attribute "ID"?

Can you parse this XML without the IMAGE data? Concatenating a base 64 encoded string with a non-encoded string shouldn't cause any issues, they are both strings.

Sid
  • 7,511
  • 2
  • 28
  • 41