binascii.Error:填充不正确,即使字符串长度是4的倍数

时间:2017-08-25 10:05:02

标签: python python-2.7 base64

我正在尝试通过python代码将base64字符串转换为图像,但是我得到 binascii.Error:填充不正确我已经使用了我的solution,但他们只建议检查字符串长度是可整除的4,如果不能通过添加' ='使其可被4整除。 base64编码刺痛结束时的字符。 请帮忙。

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

1 个答案:

答案 0 :(得分:6)

通过检查你的链接,你的字符串有200000字节,它包含标题:

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

这是MIME消息的一部分。你必须先剥离它。

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

然后填充(如果需要)

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

然后使用codecs(符合python 3)

进行解码
codecs.decode(strOne.strip(),'base64')

=&GT; &#34;我们相信团队合作&#34; :)