2017-08-25 74 views
1

我試圖通過Python代碼爲base64字符串轉換成圖像,但我正在逐漸binascii.Error多:不正確的填充我走過了我的solution但是他們只建議檢查字符串的長度是可以被整除的4,如果不能通過在base64編碼的sting結尾添加'='字符使它被4整除。 請幫忙。binascii.Error:不正確的填充,即使字符串長度的4

PYTHON CODE:(請從驅動器代碼,更多的知名度)

import base64 

strOne= 'data:image/png;base64,iVBORw0KGgoAAAANSU...string has 200000 character thats why I couldn t paste' 
print 'strOne Length',len(strOne) 
print 'StrOne Length is completely divisible by 4 (len%4),(len/4):', len(strOne)%4,len(strOne)/4 

with open("imageToSave.png", "wb") as fh: 
    fh.write(strOne.strip().decode('base64')) 

輸出:

strOne Length 200000 
StrOne Length is completely divisible by 4 (len%4),(len/4): 0 50000 
Traceback (most recent call last): 
    File "/tests.py", line 13, in <module> 
    fh.write(strOne.strip().decode('base64')) 
    File "/usr/lib/python2.7/encodings/base64_codec.py", line 42, in base64_decode 
    output = base64.decodestring(input) 
    File "/usr/lib/python2.7/base64.py", line 328, in decodestring 
    return binascii.a2b_base64(s) 
binascii.Error: Incorrect padding 

回答

2

通過檢查你的鏈接,你的字符串中有200000個字節的所有權利,它包含了標題:

strOne = b"data:image/png;base64,iVBORw0KGgoAAAANSU... 

這是MIME消息的一部分。你必須先脫光。

strOne = strOne.partition(",")[2] 

然後墊(如果需要)

pad = len(strOne)%4 
strOne += b"="*pad 

然後解碼使用codecs(蟒蛇3標準)

codecs.decode(strOne.strip(),'base64') 

=> 「我們相信團隊合作」 :)

+1

謝謝@ Jean-FrançoisFabre –

+0

這工作很好! – varagrawal

相關問題