小编Tom*_*Tom的帖子

Python:如何将 IMAGE 转换为 STRING 并返回?

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

在此处输入图片说明

现在我想把它变成一个python string,它不应该是二进制的,我该怎么做?因为当我尝试编码时,出现以下错误:

我的代码:

from PIL import Image

img = Image.open("testImage.jpeg")
string = img.tobytes()
string = string.decode("ascii")
Run Code Online (Sandbox Code Playgroud)

输出:

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)
Run Code Online (Sandbox Code Playgroud)

当这有效时,我还想将字符串重新转换为图像

其它的方法还没有借机d对我来说:

  • 直接从文件中读取图像open("file","rb"),然后对其进行编码。
  • 使用codecs库对其进行编码。( string = codecs.encode(string, "base64"))
  • 使用base64库对其进行编码(能够将其转换为字符串,但字符串如下所示:///////.(仅斜线))

感谢您的回答!

string byte image python-imaging-library python-3.x

10
推荐指数
1
解决办法
1万
查看次数

标签 统计

byte ×1

image ×1

python-3.x ×1

python-imaging-library ×1

string ×1