程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Django uploads the webcam image stream to the front end for display --ajax+ image to Base64 image to image

編輯:Python

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 :

  1. The first is to get pictures , This step is different for everyone , As long as you can get a normal picture .
  2. Next I save the pictures in a folder :cv2.imwrite(imgpath, img)
  3. Then read the picture in binary and encode it into base64 form
with open(imgpath, 'rb') as f: # Read pictures in binary 
data = f.read()
encode_str = base64.b64encode(data)
  • Why save it before coding it ?
    I tried , Direct error , Because the picture is not in binary form

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 !!


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved