binascii.Error:即使字符串长度是4的倍数,填充也不正确 [英] binascii.Error: Incorrect padding, even when string length is multiple of 4

查看:90
本文介绍了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" :)

这篇关于binascii.Error:即使字符串长度是4的倍数,填充也不正确的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆