用html5获取摄像头拍照,录视频

3 篇文章 0 订阅
1 篇文章 0 订阅
<!DOCTYPE html>
<html>
<head>
    <title>HTML5 GetUserMedia Demo</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0" />
    <script type="text/javascript" src="jquery-1.11.1.min.js"></script>
</head>
<body>

    <input type="button" title="开启摄像头" value="开启摄像头" οnclick="getMedia();" /><br />
    <video height="120px" autoplay="autoplay"></video><hr />
    <input type="button" title="拍照" value="拍照" οnclick="getPhoto();" /><br />
    <canvas id="canvas1" height="120px" ></canvas><hr />
    <input type="button" title="视频" value="视频" οnclick="getVedio();" /><br />
    <canvas id="canvas2" height="120px"></canvas>
   
<script type="text/javascript">

    var video = document.querySelector('video');
    var audio;
   var audioType;

    var canvas1 = document.getElementById('canvas1');
    var context1 = canvas1.getContext('2d');

  var canvas2 = document.getElementById('canvas2');
  var context2 = canvas2.getContext('2d');

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

    var exArray = []; //存储设备源ID
    MediaStreamTrack.getSources(function (sourceInfos) {
        for (var i = 0; i != sourceInfos.length; ++i) {
            var sourceInfo = sourceInfos[i];
            //这里会遍历audio,video,所以要加以区分
            if (sourceInfo.kind === 'video') {
                exArray.push(sourceInfo.id);
            }
        }
    });

    function getMedia() {
        if (navigator.getUserMedia) {
            navigator.getUserMedia({
                'video': {
                    'optional': [{
                        'sourceId': exArray[1] //0为前置摄像头,1为后置
                    }]
                }
//                'audio':true
            }, successFunc, errorFunc);    //success是获取成功的回调函数
        }
        else {
            alert('Native device media streaming (getUserMedia) not supported in this browser.');
        }
    }

    function successFunc(stream) {
//        alert('Succeed to get media!');
        console.log(stream);
        if (video.mozSrcObject !== undefined) {
            //Firefox中,video.mozSrcObject最初为null,而不是未定义的,我们可以靠这个来检测Firefox的支持
            video.mozSrcObject = stream;
        }
        else {
            video.src = window.URL && window.URL.createObjectURL(stream) || stream;
        }

        //video.play();

        // 音频
//        audio = new Audio();
//        audioType = getAudioType(audio);
//        if (audioType) {
//            audio.src = 'polaroid.' + audioType;
//            audio.play();
//        }
    }
    function errorFunc(e) {
        alert('Error'+e);
    }
    //拍照
    function getPhoto() {
        context1.drawImage(video, 0, 0,90,120); //video对象内指定的区域捕捉绘制到画布上指定的区域,实现拍照。
        uploadPic();
    }
    //上传图片到后台
    function uploadPic() {
        // Generate the image data(将Canvas的内容保存为图片借助toDataURL来实现) 方法返回一个包含图片展示的 data URI         var Pic = document.getElementById("canvas1").toDataURL("image/jpg");
        //对其进行base64编 之后的字符串
        Pic = Pic.replace(/^data:image\/(png|jpg);base64,/,"");
        // Sending the image data to Server
        $.ajax({
            type: 'POST',
            url:  "/webcam/uploadPic.do?type=0",
            data: { "imageData" : Pic},
            success: function (msg) {
                // alert("Done, Picture Uploaded.");
            }
        });
    }

    // 将视频帧绘制到Canvas对象上,Canvas60ms切换帧,形成肉眼视频效果
//    function drawVideoAtCanvas(video,context) {
//        window.setInterval(function () {
//            context.drawImage(video, 0, 0,90,120);
//        }, 60);
//    }

    //获取音频格式
//    function getAudioType(element) {
//        if (element.canPlayType) {
//            if (element.canPlayType('audio/mp4; codecs="mp4a.40.5"') !== '') {
//                return ('aac');
//            } else if (element.canPlayType('audio/ogg; codecs="vorbis"') !== '') {
//                return ("ogg");
//            }
//        }
//        return false;
//    }

    // vedio播放时触发,绘制vedio帧图像到canvas
    //        video.addEventListener('play', function () {
    //            drawVideoAtCanvas(video, context2);
    //        }, false);

    //视频
//    function getVedio() {
//        drawVideoAtCanvas(video, context2);
//    }

</script>
</body>
</html>
 


/**
 * 上传现成拍摄的人脸照片
 */
@Action("/webcam/uploadPic")
public void uploadPic(){
   request = super.getRequest();
   response = super.getResponse();
   response.setContentType("application/json");
   response.setCharacterEncoding("utf-8");
   PrintWriter out = null;
   JSONObject json = new JSONObject();

   userID = request.getParameter("userID");
   user = userManager.getUser(Integer.parseInt(userID));
   try {
      out = response.getWriter();
      //接收经过base64编 之后的字符串
      String imgStr = request.getParameter("imageData");
      // 图像数据为空
      if (imgStr != null){

         BASE64Decoder decoder = new BASE64Decoder();
         // Base64解码
         byte[] b = decoder.decodeBuffer(imgStr);
         for (int i = 0; i < b.length; ++i) {
            // 调整异常数据
            if (b[i] < 0) {
               b[i] += 256;
            }
         }
         // 生成jpeg图片
         String photoName = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date())+ ".jpg";
         // 新生成的图片
         String imgFilePath = storePath + user.getAspID() + File.separator + "compareImage"+File.separator+ photoName;
         File file =new File(imgFilePath);
         //如果文件夹不存在则创建
         File parentFile = file.getParentFile();
         if (!parentFile.exists()) {
            parentFile.mkdirs();
         }
         //表示人脸识别日志
         log.setType(2);
         log.setUserID(userID);
         log.setUserIP(StringUtil.getIpAddr(request));
         log.setCreatetime(new Date());
         log.setUrl("asp/user/"+user.getAspID()+"/compareImage/"+photoName);
         OutputStream outputStream = null;
         try {
            outputStream = new FileOutputStream(imgFilePath);
         } catch (FileNotFoundException e) {
            json.put("success",false);
            json.put("msg","上传头像失败");
            e.printStackTrace();
         }
         outputStream.write(b);
         outputStream.flush();
         outputStream.close();
         File userHead =new File(Config.getUploadPhysicalPath()+File.separator+user.getRemark12()) ;
         String userHeadStr = userHead.getName();
         System.out.println("photoName:"+photoName+"file:"+file.exists() +";========= userHeadStr:"+userHeadStr+"userHead:"+userHead.exists());
         Map<String,Object> map = IdCardDectedAction.faceFaceCompare(photoName,userHeadStr,file,userHead);
         log.setCode(Integer.parseInt(map.get("code").toString()));
         if("0".equals(map.get(ClientConfig.CODE).toString())){
            if(Double.valueOf(map.get(ClientConfig.SIMILARITY).toString()).compareTo(new Double(75.0))>0){
               log.setContent(FaceBodyException.imageCompareException(log.getCode()));
            }else {
               log.setContent("用户"+user.getName()+"在学习过程中定时获取图像与本人头像相似度为:"+map.get(ClientConfig.SIMILARITY).toString());
            }
            json.put("success",true);
            json.put("msg",log.getContent());
         }else {
            log.setContent(FaceBodyException.imageCompareException(log.getCode()));
            json.put("success",false);
            json.put("msg",FaceBodyException.imageCompareException(log.getCode()));
         }
         sysLogManager.save(log);
      }else{
         json.put("success",false);
         json.put("msg","图像为空");
      }
      out.write(json.toString());
      out.flush();
      out.close();
   } catch (IOException e) {
      e.printStackTrace();
   }
}
注:java增加了人脸识别和日志信息。
  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值