如何从base64编码重建文件



我正在尝试用base64对一个文件进行编码,然后发送编码的数据并在另一端重建文件。例如,我想打开位于桌面上的.png文件,对其进行编码,然后对其进行解码,并将新的.png保存在不同的目录中。

我被推荐使用以下文章,但我收到了一个错误,如下所示:https://www.programcreek.com/2013/09/convert-image-to-string-in-python/

import base64
with open('path_to_file', 'rb') as imageFile:
x = base64.b64encode(imageFile.read())
fh = open('imageToSave.png', 'wb')
fh.write(x.decode('base64'))
fh.close()
File "directory", line 7, in <module>
fh.write(x.decode('base64'))
LookupError: 'base64' is not a text encoding; use codecs.decode() to handle arbitrary codecs

我试着在stackoverflow上寻找类似的问题,但我不理解其他解决方案,也无法在我的案例中实现它们。如果有更好的方法来完成这项任务,请告诉我。

为什么使用decode而不是base64.b64decode()

因为这很好:

>>> base64.b64encode(b"foo")
b'Zm9v'
>>> base64.b64decode('Zm9v')
b'foo'

或者,在您的情况下:

import base64
with open('path_to_file', 'rb') as imageFile:
x = base64.b64encode(imageFile.read())
fh = open('imageToSave.png', 'wb')
fh.write(base64.b64decode(x))
fh.close()

不过,Python 2和Python 3之间有区别。str.decode('base64')似乎在Python 2中工作,但在3中不工作。

最新更新