How to base64 encode/decode binary files in python?

一曲冷凌霜 提交于 2020-12-30 07:56:18

问题


I'm trying to encode and decode the same image file using python using following simple code. But every time output file is larger than input file and it can't open. What's the problem in this code?

import base64

with open("img.jpeg", "rb") as image_file:
    encoded_string = base64.b64encode(image_file.read())

    decoded_string = base64.b64decode(encoded_string)
    with open("test_img.jpeg", "w") as image_file2:
        image_file2.write(decoded_string);

Original file: https://filebin.ca/3j6aIDlWEYdV/img.jpeg
Result file: https://filebin.ca/3j6arBo85Lcg/test_img.jpeg


回答1:


Try changing the write mode to "wb". Your writing and reading as different formats right now.



来源:https://stackoverflow.com/questions/47580772/how-to-base64-encode-decode-binary-files-in-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!