【发布时间】:2018-01-04 00:30:34
【问题描述】:
我正在使用https://github.com/cmcqueen/cobs-python 中提供的库来确保我可以通过串行线路发送数据。 然而,这个库需要一个字符串作为输入,它可以是任何东西(文本文件、图像等)。由于我使用的是没有任何特殊功能的串行线,因此无需担心特殊字符会触发某些事件。
如果可以的话,我会以原始模式发送图像,因为数据如何传递到另一端并不重要,但我需要使用这个库对其进行编码。
我尝试了以下方法:
data = open('img.jpg', 'wb')
cobs_packet = cobs.encode(''.join(data).encode('utf-8'))
这给了我以下错误:
>>> UnicodeDecodeError: 'ascii' codec can't decode byte 0xff in position 0: ordinal not in range(128)
问题是,如果我使用不同的编码类型,数据长度会改变,而这不会发生在我想要做的事情上。
有没有办法简单地将输入转换为字符串?
编辑:我使用的是 python 2.7 版
【问题讨论】:
-
你使用哪个 Python 版本?
-
我使用的是 python 2.7
-
这会改变数据长度吗?
import base64 with open("img.jpg", "rb") as imageFile: str = base64.b64encode(imageFile.read()) print strprogramcreek.com/2013/09/convert-image-to-string-in-python -
是的,我已经通过与os.stat比较并打印编码长度进行了测试,b64增加了数据长度。
-
这会返回与 os.stat 相同的数据长度:
with open('img.jpg', "rb") as f: str_output = io.BytesIO(bytearray(f.read())).getvalue(),取自这个答案stackoverflow.com/questions/41850407/image-from-bytes-python
标签: python string encoding character-encoding encode