gpt4 book ai didi

python - 解码python base64字符串

转载 作者:太空狗 更新时间:2023-10-29 18:31:46 24 4
gpt4 key购买 nike

我已经提取了图像的前景色、纹理和边缘图值的 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')

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

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

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

最佳答案

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

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

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,)]

关于python - 解码python base64字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11656115/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com