10

我已经提取了图像的前色、纹理和边缘图值的 base64 字符串,我有一个具有以下结构的列表:

forecolor=AgCEAg4DUQQCBQQGARMBFQE1AmUB
edge=AfCAFg5iIATCPwTAEIiBFggBDw
forecolor=AgAsAQ0CJAMcDRgOGg8DHQYeBzYBPQ4-DU0ETgNtBm4CfQI

我正在尝试解码这些值,但我收到了不正确的填充错误,这是确切的错误:

Traceback (most recent call last):
  File "ImageVectorData.py", line 44, in <module>
    print "Decoded String: " + decoded.decode('base64', 'strict')
  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/encodings/base64_codec.py", line 42, in base64_decode
    output = base64.decodestring(input)
  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/base64.py", line 321, in decodestring
    return binascii.a2b_base64(s)
binascii.Error: Incorrect padding

这是我的代码:

for item in value:
    print "String before Split: " + item
    if item.split("=")[0] == "forecolor":
        decoded = (item.split("=")[1])
        print "String to be decoded: " + decoded
        print "Decoded String: " + decoded.decode('base64', 'strict')

当第一个前色 base64 字符串被解码时,我还看到了一个有趣的输出:这是输出:

String before Split: forecolor=AgCEAg4DUQQCBQQGARMBFQE1AmUB
String to be decoded: AgCEAg4DUQQCBQQGARMBFQE1AmUB
Decoded String: ?Q5e

我不确定我在这里做错了什么。我查看了以下 python 文档并尝试了,但这也不起作用: http ://docs.python.org/library/base64.html

4

1 回答 1

8

您正在尝试解码没有填充的 Base64 字符串。尽管许多 Base64 风格没有填充,但 Python 需要填充以进行标准 base64 解码。这个 StackOverflow 问题有更深入的解释:Python: Ignore 'Incorrect padding' error when base64 decoder

对于您的代码,我将进行类似于以下的修改:

for item in value:
    print "String before Split: " + item
    if item.split("=")[0] == "forecolor":
        decoded = (item.split("=")[1])
        print "String to be decoded: " + decoded
        # Add Padding if needed
        decoded += "===" # Add extra padding if needed
        print "Decoded String: " + decoded.decode('base64', 'strict')

根据您的评论,您似乎还需要将 base64 解码返回的字节数组转换为整数列表。我假设整数是小端短整数。

import struct
x = "AgAsAQ0CJAMcDRgOGg8DHQYeBzYBPQ4-DU0ETgNtBm4CfQI"
x += "==="
y = x.decode('base64', 'strict')
intList = [struct.unpack('<h', y[i] + y[i+1]) for i in xrange(0, len(y), 2)]
print intList

结果是:

[(2,), (300,), (525,), (804,), (3356,), (3608,), (3866,), (7427,), (7686,), (13831,), (15617,), (782,), (16723,), (-32749,), (16859,), (-32613,), (16543,)]
于 2012-07-25T19:46:42.463 回答