我有一张像这样的图片,已经加载到了PIL.Image
中:
现在我想把它转化为一个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)
当这个功能实现后,我还希望将字符串转换回图像。
其他方法也都对我不起作用:
- 使用
open("file","rb")
直接从文件中读取图像,然后进行编码。 - 使用
codecs
库进行编码。(string = codecs.encode(string, "base64"
) - 使用
base64
库进行编码(能够将其转换为字符串,但该字符串看起来像这样:///////
。(只有斜杠)
感谢您的答案!
.decode('ASCII')
,将字节转换为字符串。 - Mark Setchell