gpt4 book ai didi

python - 使用 Python 转换图像

转载 作者:太空宇宙 更新时间:2023-11-04 05:44:46 25 4
gpt4 key购买 nike

我在将图像从字节/字符串/等中转换出来时遇到问题。我可以将图像转换为字符串或字节数组,或对其使用 b64encode,但是当我尝试将其解码/恢复为图像时,它永远无法工作。我已经尝试了很多东西,在本地转换图像然后重新转换它,以不同的名称保存它。但是,生成的文件实际上永远不会显示任何内容。 (在 Linux 上为黑色,在 Windows 上“无法显示图像”)

我最基本的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** 哇,你们 Action 真快。多么棒的社区介绍 - 非常感谢您的快速响应和超快的结果!

最佳答案

对于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)

关于python - 使用 Python 转换图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32699308/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com