繁体   English   中英

将base64的字符串转换回base64字节

[英]Convert string of base64 back to base64 bytes

我已经使用OpenCV上传了图片,然后使用base64b64encode使用base64编码对其进行了编码。

>>> import cv2
>>> import base64
>>> image = cv2.cvtColor(cv2.imread("some_image.jpg"), cv2.COLOR_BGR2RGB)
>>> image_64 = base64.b64encode(image)
>>> image_64
b'//////////////////...
>>> type(image_64)
<class 'bytes'>

然后,我使用str()方法将其转换为字符串。 这将创建一个字符串的编码图像。

>>> image_64str = str(image_64)
>>> image_64str
b'//////////////////...
>>> type(image_64str)
<class 'str'>

两者( <class 'bytes'>类型和<class 'str'> )看起来都相似。 我试图使用base64b64decodeb64decode decode()函数decode() 但是,当我解码image_64str时发生了错误。

>>> image_64str.decode()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'str' object has no attribute 'decode'
>>> base64.b64decode(image_64str)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/base64.py", line 87, in b64decode
    return binascii.a2b_base64(s)
binascii.Error: Incorrect padding

我完全理解错误是想告诉我什么。 但是我的问题是, 如何将编码图像的字符串( image_64str )转换回字节?

我尝试再次在字符串上使用base64的'b64encode`。 但是,它返回一个错误。

>>> str_to_b64 = base64.b64encode(image_64str)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/base64.py", line 58, in b64encode
    encoded = binascii.b2a_base64(s, newline=False)
TypeError: a bytes-like object is required, not 'str'

请告诉是否有人注意到我失踪了。 我正在使用Python 3.6。 提前致谢。

编辑:为我的问题添加更多描述。

我能够启用AWS API Gateway二进制支持。 我的目的是通过POST请求将图像作为二进制数据传递给API,并将其转换为PIL对象,以便我可以使用AWS Lambda在后端对其进行处理。 使用API​​ Gateway,二进制数据使用base64二进制编码。

我使用python的open函数将图像作为二进制数据open (我想通过API传递两个图像)。 然后我用字典来保存两个图像的二进制数据,例如

data = {"data1": img_binary_data_1, "data2": img_binary_data_2}

我使用python request库发送POST请求。 我可以在post函数中传递的参数之一是data ,因此我使用它传递了图像数据。

我能够发送请求。 在Lambda后端中,我想将二进制数据转换为PIL对象以进行进一步处理。 但是,似乎数据已打包为JSON格式,并且base64编码的二进制映像已上载为python字符串。 我通过在AWS CloudWatch日志中打印数据来确认这一点。

我尝试使用.decode() ,但是根据这里您不能解码字符串。

我能够使用b64decode()解码字符串,返回一个字节对象。 但是,当尝试将其转换为PIL对象时

img = imread(io.BytesIO(base64.b64decode(b64_string)))

我收到一条错误消息,说

OSError: cannot identify image file <_io.BytesIO object at 0x1101dadb0>

我从此链接尝试了一些解决方案,但是显然您不能使用字节对象来做到这一点。

我试过使用PIL.frombufferPIL.frombytes 但是,当我非常确定图像的sizer(在这种情况下(256, 256) )时,它们返回的not enough datanot enough data

所以我的问题是, 如何将base64图像转换为PIL对象? 我希望这有助于更好地理解我的问题。 提前致谢。

Base64是二进制-> char编码,因此对图像进行编码很有意义,您将获得文本字节,其中6位一组被视为字符。

现在,即使上面的字节是字符,它们也不是python字符串,因为python字符串是utf-8。

当您将字节转换为字符串时,它将字节转换为utf-8并弄乱了base64填充(仅=允许填充),您得到的是一个python字符串。

现在,在解码时会收到错误,因为它不再是base64编码。 您还不能对字符串进行编码,因为base64是字节-> char并且字符串不是字节。

为什么无论如何要将编码的字节转换为字符串? 对用例进行更多描述会有所帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM