我正在尝试使用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
,而不是base.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()