简体   繁体   English

通过 base64 编码将图像从服务器发送到客户端

[英]Sending image from server to client via base64 encoding

I'm facing an issues sending an Image (np.ndarray) over my python server to my javascript client.我在通过我的 python 服务器向我的 javascript 客户端发送图像(np.ndarray)时遇到问题。

Starting with the python server, I process the img like this:从 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)

// The fct below I found on SO.. For the client (javascript) I do the following: // 我在 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;

To sum it up, I want to send an image over the API and convert it into a valid base64 format to display via html.综上所述,我想通过 API 发送图像并将其转换为有效的 base64 格式以通过 html 显示。 After experimenting a little I sometimes got "no valid base64 format" but with the provided code I'm not getting any error.经过一番试验后,我有时会得到“没有有效的 base64 格式”,但是使用提供的代码我没有收到任何错误。 The image doesn't show up though.图像没有显示出来。

It is important to not save the file in my scenario.重要的是不要在我的场景中保存文件。

So I figured the problem.所以我想出了问题所在。 I had troubles encoding the image (nparray) to a proper base64 encoding.我在将图像(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")

this resolved the encoding issues for me.这为我解决了编码问题。 I then return a dictionary containing the img like so:然后我返回一个包含 img 的字典,如下所示:

res = {
   "img": enc_img 
}

return res

After converting it to JSON via json.dumps(res) , I send it via the API to my JavaScript Client.通过json.dumps(res)将其转换为 JSON 后,我通过 API 将其发送到我的 Z686E95AF75A60EDF7D 客户端。

When receiving the JSON, I first parse it to access the dictionary again like so:当收到 JSON 时,我首先解析它以再次访问字典,如下所示:

jsonRes = JSON.parse(xhr.responseText);
img = jsonRes.img;

and finally output it via HTML by using jQuery:最后是 output 通过 HTML 使用 jQuery :

var source = "data:image/jpg;base64,";
source += img;

$(document).ready(function() {
            $('#face_img').attr('src',source).height(100).width(100).show();
});

The

('#face_img') ('#face_img')

is an ID of my HTML, looking like the following:是我的 HTML 的 ID,如下所示:

<img id="face_img" src="" alt="img_face" />

Hope this helps someone.希望这可以帮助某人。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM