python - 如何在 python 中对二进制文件进行 base64 编码/解码?

标签 python base64

我正在尝试使用以下简单代码使用 python 对同一图像文件进行编码和解码。但是每次输出文件都比输入文件大,无法打开。这段代码有什么问题?

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);

原始文件:https://filebin.ca/3j6aIDlWEYdV/img.jpeg
结果文件:https://filebin.ca/3j6arBo85Lcg/test_img.jpeg

最佳答案

尝试将写入模式更改为"wb"。您现在正在以不同的格式写作和阅读。

关于python - 如何在 python 中对二进制文件进行 base64 编码/解码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47580772/

相关文章:

python - 从配置文件中读取 bool 条件?

java - Base64编码-解码(Java中)支持数学符号吗?

python - Windows 上 python 中的 base64 png

python - 如何通过迭代批量数组来创建多维结果

python - 如何在 Python 3.x 中执行循环函数并输出总和?

python - 如何正确刷新 curses 窗口?

java - 从 Base64 DER 构建公钥 - Java

node.js - Base64编码的url安全吗?

javascript - 从网络摄像头捕获图像并在javascript中转换为base64

python - pdf文件中的Scrapy抓取数据