🥷
🥷
文章目录
  1. Other
  2. Resources

使用JavaScript打开Camera并Capture Image

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');

$("#opencamera").click(function () {
var video = document.getElementById('video');
if(navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
navigator.mediaDevices.getUserMedia({ video: true }).then(function(stream) {
video.src = window.URL.createObjectURL(stream);
video.play();
window.stream = stream;
});
}
});

$("snap").click(function() {
$("#VideoCapture").hide();
scale = 1, offset_x = 0, offset_y = 0, fileType = "image/png";
context.drawImage(video, 0, 0, video.width, video.height);
window.stream.getVideoTracks()[0].stop(); //拍到图片后关闭视频流
uploadType='camera';
__post(appId, serviceType, null); //这里是把照片发送给服务器,__post是自己定义的函数
});


$('#localfile').change(function(e){
var _this = $(this)[0], _file = _this.files[0];
fileType = _file.type;
$('#imgType').val(fileType);
if (_this.value==''){
return false;
}
context.clearRect(0,0,canvas.width,canvas.height);
if(/image\/\w+/.test(fileType)) {
var fileReader = new FileReader();
fileReader.readAsDataURL(_file);
fileReader.onload = function (event) {
var result = event.target.result; //返回的dataURL
__drawFromUrl(result);
uploadType='browse';
__post(appId, serviceType, null);
}
}
});


var __post = function(appId, serviceType, url) {
$("#modal").modal({backdrop:"static"});
$("#modal").modal("show");
$("#uploadfaceimg").show();
if (url != null){
var postdata = {url: url, serviceType: serviceType};
}else if (uploadType=='camera'){
var newImageData = document.getElementById('canvas').toDataURL(fileType, 0.8); //利用toDataUrl, 把绘制在Canvas上的图片导出.
var imageBase64 = newImageData.replace("data:"+fileType+";base64,",'');
var postdata = {imgType: fileType, image: imageBase64, serviceType: serviceType};
}else if(uploadType=='browse'){
var formData = new FormData($("#fileform")[0]);
$.ajax({
url: '/me/'+appId+'/detection/detect',
type: 'POST',
data: formData,
async: true,
cache: false,
contentType: false,
processData: false,
success: function(data){
__dealdetect(data);
$('#localfile').val('');
},error: function(){
console.log('imgUploader upload fail, data:' + data);
}
});
return
}else{
console.log('uploadType error');
}

Other

这里面的思路是把拍到的图片绘制到canvas上,然后利用canvas的toDataURL,将其以流的方式发送或者保存。

Resources