This article talks about how to get the background from the outside The picture is encoded into base64 Code sent to js Upload to html Display !
This function was studied in the last semester when the video game was used as an automatic parking system , However, due to the tight time at that time , Add the temporary change plan , After that, I haven't studied it deeply , Until I was doing an embedded job these days , Want to pass esp32-cam As a webcam , utilize opencv Get the picture stream, upload the picture stream to the front end for display, and then open the dust laden problem .
I checked a lot of information , Most methods are : Get pictures ---- Picture coding ---- convert to json Format ---- to js
But I tried many times , Changed many versions , Failed to transmit successfully , Always stuck in base64 Decoding or decoding .
Thought hard for a long time , Came up with the following methods , I hope it can be helpful to friends passing by :
cv2.imwrite(imgpath, img)
with open(imgpath, 'rb') as f: # Read pictures in binary
data = f.read()
encode_str = base64.b64encode(data)
The next step is different from other online solutions
return HttpResponse(encode_str)
Go straight back to base64 code
Come again js part
utilize Timer , Give Way ajax Every time 100 Access the function in milliseconds , In this way, the picture displayed on the front end can be changed every 100 milliseconds , That is the principle of video ,dddd
and ajax The things to do are as follows :
$.ajax({
type: 'GET',
url: 'http://192.168.0.116:9000/App/show/',
data: {
'data': 'ok',
},
success:function(dates) {
$('#pic').attr("src", "data:image/png; base64," + dates);
}
});
success:function(dates)
Get the return value after the access function returns successfully , That's in front of us HttpResponse Of base64 value .
$('#pic').attr("src", "data:image/png; base64," + dates);
This sentence will base64 The code is decoded into pictures and then displayed to the front end <img id="pic">
This place .
Since then , The function has been successfully implemented
Knowledge is shallow , If there is anything wrong, please make comments or private letters !!