错误:填充不正确,即使字符串长度是4的倍数

2024-04-26 07:29:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我正试图通过python代码将base64字符串转换为图像,但是我得到了binascii.Error:Incorrect padding我已经完成了我的solution操作,但是他们只建议检查字符串长度是否可以被4整除,如果不能通过在base64编码的字符串末尾添加“=”字符使其可以被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

Tags: 字符串代码inpylenlineerrorlength
1条回答
网友
1楼 · 发布于 2024-04-26 07:29:37

通过检查链接,字符串有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')

=>;“我们相信团队合作”:)

相关问题 更多 >