作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有一个像这样的图像加载到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
库对其进行编码(能够将其转换为字符串,但是字符串看起来像这样:///////
(仅斜线))最佳答案
您可以将其转换为这样的字符串:
import base64
with open("image.png", "rb") as image:
b64string = base64.b64encode(image.read())
base64 < image.png
from PIL import Image
import io
f = io.BytesIO(base64.b64decode(b64string))
pilimage = Image.open(f)
base64 -D < "STRING" > recoveredimage.png
关于python-3.x - Python : How to turn an IMAGE into a STRING and back?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54147694/
我是一名优秀的程序员,十分优秀!