使用 Python 转换图像

Converting Images with Python

我在从 bytes/strings/etc 转换图像时遇到问题。我可以将图像转换为字符串或字节数组,或对其使用 b64encode,但是当我尝试 decode/revert 将其转换回图像时,它永远无法工作。我已经尝试了很多东西,在本地转换图像然后重新转换它,以不同的名称保存它。但是,生成的文件实际上永远不会显示任何内容。 (Linux 为黑色,windows 为 "can't display image")

我最基本的b64encoding脚本如下:

import base64

def convert(image):
    f = open(image)
    data = f.read()
    f.close()
    string = base64.b64encode(data)
    convertit = base64.b64decode(string)

    t = open("Puppy2.jpg", "w+")
    t.write(convertit)
    t.close()


if __name__ == "__main__":
    convert("Puppy.jpg")

我已经坚持了一段时间。我确信这是一个简单的解决方案,但作为 Python 的新手,尝试解决问题有点困难。 如果它有助于任何洞察力,这里的最终目标是通过网络传输图像,可能是 MQTT。

非常感谢任何帮助。谢谢!

编辑** 这是在 Python 2.7 中。 编辑 2** 哇,你们动作真快。多么棒的社区介绍 - 非常感谢您的快速响应和超快的结果!

对于python3,需要以二进制方式打开写入:

def convert(image):
    f = open(image,"rb")
    data = f.read()
    f.close()
    string = base64.b64encode(data)
    convert = base64.b64decode(string)
    t = open("Puppy2.jpg", "wb")
    t.write(convert)
    t.close()

在 linux 上使用 python 2,只需 rw 就可以正常工作。在 windows 上,您需要执行与上述相同的操作。

来自 docs:

On Windows, 'b' appended to the mode opens the file in binary mode, so there are also modes like 'rb', 'wb', and 'r+b'. Python on Windows makes a distinction between text and binary files; the end-of-line characters in text files are automatically altered slightly when data is read or written. This behind-the-scenes modification to file data is fine for ASCII text files, but it’ll corrupt binary data like that in JPEG or EXE files. Be very careful to use binary mode when reading and writing such files. On Unix, it doesn’t hurt to append a 'b' to the mode, so you can use it platform-independently for all binary files.

您还可以通过使用 with 打开您的文件并自动为您关闭它们来更简洁地编写代码:

from base64 import b64encode, b64decode

def convert(image):
    with open(image, "rb") as f, open("Puppy2.jpg", "wb") as t:
        conv = b64decode(b64encode(f.read()))
        t.write(conv)
import base64

def convert(image):
    f = open(image)
    data = f.read()
    f.close()
    return data

if __name__ == "__main__":
    data = convert("Puppy2.jpg")
    string = base64.b64encode(data)
    convert = base64.b64decode(string)

    t = open("Puppy2.jpg", "w+")
    t.write(convert)
    t.close()