[英]Convert string of base64 back to base64 bytes
我已經使用OpenCV上傳了圖片,然后使用base64
的b64encode
使用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'>
)看起來都相似。 我試圖使用base64
的b64decode
和b64decode
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.frombuffer
和PIL.frombytes
。 但是,當我非常確定圖像的sizer(在這種情況下(256, 256)
)時,它們返回的not enough data
值not 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.