Node.js调用本地摄像头拍摄上传

server.js

var express=require('express');
var fs=require('fs'); //文件操作
var bodyParser = require('body-parser');


var app=express(); //创建web应用程序
app.use(bodyParser.urlencoded({extended:false}));
app.use(bodyParser.json());


//获取所有数据
app.post("/uploadPics",function(req,res){
    var bitmap=new Buffer(req.body.imageData,'base64');
    fs.writeFile("./images/"+new Date().getTime()+".jpg",bitmap,function(err){
        if(err){
            res.send("0");
        }else {
            res.send("1");
        }
        res.end();
    });
});


//获取user下面的静态文件
app.get("/*",function(req,res){
    res.sendFile(__dirname+req.url);
});


app.listen(6666);


index.html





调用摄像头










请点击“允许”按钮,授权网页访问您的摄像头!
若您并未看到任何授权提示,则表示您的浏览器不支持Media Capture或您的机器没有连接摄像头设备。







camera.js

function init(t) {
accessLocalWebCam("navy_video");
}


window.URL = window.URL || window.webkitURL || window.msURL || window.oURL;
navigator.getUserMedia = navigator.getUserMedia|| navigator.webkitGetUserMedia || navigator.mozGetUserMedia|| navigator.msGetUserMedia;


function isChromiumVersionLower() {
var ua = navigator.userAgent;
var testChromium = ua
.match(/AppleWebKit\/.* Chrome\/([\d.]+).* Safari\//);
return (testChromium && (parseInt(testChromium[1].split('.')[0]) < 19));
}


function successsCallback(stream) {
document.getElementById('camera_errbox').style.display = 'none';
document.getElementById('navy_video').src = (window.URL && window.URL.createObjectURL) ? window.URL.createObjectURL(stream): stream;


}


function errorCallback(err) {


}


function accessLocalWebCam(id) {
try {
navigator.getUserMedia({
video : true
}, successsCallback, errorCallback);
} catch (err) {
navigator.getUserMedia('video', successsCallback, errorCallback);
}
}




window.addEventListener("DOMContentLoaded", function() {
var canvas = document.getElementById("canvas"), context = canvas
.getContext("2d"), video = document
.getElementById("navy_video"), videoObj = {
"video" : true
}, errBack = function(error) {
console.log("相机调用失败...", error.code);
};


if (navigator.getUserMedia) {
navigator.getUserMedia(videoObj, function(stream) {
video.src = stream;
video.play();
}, errBack);
} else if (navigator.webkitGetUserMedia) {
navigator.webkitGetUserMedia(videoObj, function(stream) {
video.src = window.webkitURL.createObjectURL(stream);
video.play();
}, errBack);
}


document.getElementById("snap").addEventListener("click", function() {
context.drawImage(video, 0, 0,$("#canvas").width(), $("#canvas").height());
});
}, false);




function convertCanvasToImage() {
var pic = document.getElementById("canvas").toDataURL("image/png");
pic = pic.replace(/^data:image\/(png|jpg);base64,/, "")


$.post('uploadPics',{imageData:pic},function(data){
data=parseInt($.trim(data));
if(data==0){
alert("图片上传失败...");
}else{
alert("图片上传成功...");
}
});
}


你可能感兴趣的:(Web前端,js,node.js)