[英]Sending image from server to client via base64 encoding
我在通过我的 python 服务器向我的 javascript 客户端发送图像(np.ndarray)时遇到问题。
从 python 服务器开始,我像这样处理 img:
1) Load img as np.ndarray
2) enc_img = base64.b64encode(img.copy(order='C'))
3) utf8_img = enc_img.decode("utf-8")
4) json = {
...
"img": utf8_img,
...
}
5) req_return = json.dumps(json, ensure_ascii=False)
// 我在 SO 上找到的下面的 fct.. 对于客户端(javascript),我执行以下操作:
function b64EncodeUnicode(str) {
return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g, function(match, p1) {
return String.fromCharCode(parseInt(p1, 16))
}))
}
img_64 = b64EncodeUnicode(jsonRes.fs_dict.face)
var src = "data:image/jpg;base64,";
src += img_64;
var newImage = document.createElement('img');
newImage.src = src;
newImage.width = newImage.height = "100";
document.querySelector('#face_img').innerHTML = newImage.outerHTML;
综上所述,我想通过 API 发送图像并将其转换为有效的 base64 格式以通过 html 显示。 经过一番试验后,我有时会得到“没有有效的 base64 格式”,但是使用提供的代码我没有收到任何错误。 图像没有显示出来。
重要的是不要在我的场景中保存文件。
所以我想出了问题所在。 我在将图像(nparray)编码为正确的 base64 编码时遇到了麻烦。
pil_img = Image.fromarray(nparray_img)
buff = BytesIO()
pil_img.save(buff, format="JPEG")
enc_img = base64.b64encode(buff.getvalue()).decode("utf-8")
这为我解决了编码问题。 然后我返回一个包含 img 的字典,如下所示:
res = {
"img": enc_img
}
return res
通过json.dumps(res)
将其转换为 JSON 后,我通过 API 将其发送到我的 Z686E95AF75A60EDF7D 客户端。
当收到 JSON 时,我首先解析它以再次访问字典,如下所示:
jsonRes = JSON.parse(xhr.responseText);
img = jsonRes.img;
最后是 output 通过 HTML 使用 jQuery :
var source = "data:image/jpg;base64,";
source += img;
$(document).ready(function() {
$('#face_img').attr('src',source).height(100).width(100).show();
});
这
('#face_img')
是我的 HTML 的 ID,如下所示:
<img id="face_img" src="" alt="img_face" />
希望这可以帮助某人。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.