问题
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 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'))
output:
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:
by checking your link, your string has 200000 bytes all right, but it contains the header:
strOne = b"data:image/png;base64,iVBORw0KGgoAAAANSU...
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
then decode using codecs
(python 3 compliant)
codecs.decode(strOne.strip(),'base64')
=> "we believe in team work" :)
来源:https://stackoverflow.com/questions/45879045/binascii-error-incorrect-padding-even-when-string-length-is-multiple-of-4