gpt4 book ai didi

python-3.x - Python : How to turn an IMAGE into a STRING and back?

转载 作者:行者123 更新时间:2023-12-05 00:46:24 25 4
gpt4 key购买 nike

我有一个像这样的图像加载到PIL.Image中:

enter image description here

现在,我想将其转换为 python字符串,并且它不应该是二进制的,我该怎么做?
因为当我尝试编码时,出现以下错误:

我的代码:

from PIL import Image

img = Image.open("testImage.jpeg")
string = img.tobytes()
string = string.decode("ascii")

输出:
Traceback (most recent call last):
File "/Users/tomschimansky/Desktop/SenderMAIN.py", line 5, in <module>
string = string.decode("ascii")
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 0: ordinal not in range(128)

当此方法有效时,我还想将字符串 转换回图像

其他方法,即 也对我不起作用 d:
  • 直接使用open("file","rb")从文件中读取图像,然后对其进行编码。
  • 使用codecs库对其进行编码。 (string = codecs.encode(string, "base64"))
  • 使用base64库对其进行编码(能够将其转换为字符串,但是字符串看起来像这样:///////(仅斜线))

  • 感谢您的回答!

    最佳答案

    您可以将其转换为这样的字符串:

    import base64

    with open("image.png", "rb") as image:
    b64string = base64.b64encode(image.read())

    这应该为您提供与在Terminal中运行此结果相同的结果:
    base64 < image.png

    您可以像这样将字符串转换回PIL图像:
    from PIL import Image
    import io

    f = io.BytesIO(base64.b64decode(b64string))
    pilimage = Image.open(f)

    那应该等同于终端中的以下内容:
    base64 -D < "STRING" > recoveredimage.png

    请注意,如果要通过LoRa发送此文件,则最好发送文件的PNG编码版本,就像我在这里一样,因为它已压缩并且会花费更少的时间。或者,您可以发送文件的扩展内存版本,但该文件的内存版本将扩大近50%。 PNG文件为13kB。扩展后的内存版本将为100 * 60 * 3或18kB。

    关于python-3.x - Python : How to turn an IMAGE into a STRING and back?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54147694/

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