Rya*_*nan 10 python arrays base64
基本上,我需要做这个,但是在Python而非JavaScript.我从socketio连接接收到base64编码的字符串,将其转换为uint8并对其进行处理,然后需要将其转换为base64字符串,以便我可以将其发回.
所以,到目前为止,我已经得到了这个(我data从socketio服务器获取字典):
import pickle
import base64
from io import BytesIO
from PIL import Image
base64_image_string = data["image"]
image = Image.open(BytesIO(base64.b64decode(base64_image_string)))
img = np.array(image)
Run Code Online (Sandbox Code Playgroud)
我如何扭转这个过程从img回到base64_image_string?
更新:
我已通过以下方式解决了这个问题(从上面的代码片段继续):
pil_img = Image.fromarray(img)
buff = BytesIO()
pil_img.save(buff, format="JPEG")
new_image_string = base64.b64encode(buff.getvalue()).decode("utf-8")
Run Code Online (Sandbox Code Playgroud)
有点令人困惑,new_image_string不一样,base64_image_string但是new_image_string看起来相同的图像,所以我很满意!
我相信由于numpy.arrays 支持缓冲协议,您只需要以下内容:
processed_string = base64.b64encode(img)
Run Code Online (Sandbox Code Playgroud)
因此,例如:
>>> encoded = b"aGVsbG8sIHdvcmxk"
>>> img = np.frombuffer(base64.b64decode(encoded), np.uint8)
>>> img
array([104, 101, 108, 108, 111, 44, 32, 119, 111, 114, 108, 100], dtype=uint8)
>>> img.tobytes()
b'hello, world'
>>> base64.b64encode(img)
b'aGVsbG8sIHdvcmxk'
>>>
Run Code Online (Sandbox Code Playgroud)
ral*_*htp -1
来自http://www.programcreek.com/2013/09/convert-image-to-string-in-python/:
import base64
with open("t.png", "rb") as imageFile:
str = base64.b64encode(imageFile.read())
print str
Run Code Online (Sandbox Code Playgroud)
是二进制读取
https://docs.python.org/2/library/base64.html
| 归档时间: |
|
| 查看次数: |
11153 次 |
| 最近记录: |