binascii.Error:即使字符串长度是4的倍数,填充也不正确
我正在尝试通过python代码将base64字符串转换为图像,但是却出现 binascii.Error:填充不正确我的解决方案,但他们仅建议将校验字符串的长度整除4,如果不能通过在base64编码的字符串末尾添加'='使其4整除.请帮忙.
I am trying to convert base64 string to image by python code, but I am getting binascii.Error: Incorrect padding I have gone through with my solution but they only suggest check string length is divisible 4, if not make it divisible by 4 by adding '=' characters at the end of base64 encoded sting. Please help in this.
PYTHON代码:(请从驱动器中检查代码以获取可见度更高
PYTHON CODE: (please check code from drive for more visibility)
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
通过检查链接,您的字符串可以有200000字节,但是包含标头:
by checking your link, your string has 200000 bytes all right, but it contains the header:
strOne = b"data:image/png;base64,iVBORw0KGgoAAAANSU...
这是MIME消息或其他内容的一部分.您必须先剥离它.
This is part of MIME message or something. You have to strip this first.
strOne = strOne.partition(",")[2]
然后按一下(如果需要)
then pad (if needed)
pad = len(strOne)%4
strOne += b"="*pad
然后使用 codecs
(兼容python 3)进行解码
then decode using codecs
(python 3 compliant)
codecs.decode(strOne.strip(),'base64')
=>我们相信团队合作":)
=> "we believe in team work" :)