JAVA B/S通过摄像头采集图片信息解决方案。

在浏览器上调用摄像头。有ACTIVX,FLASH,HTML5,JAVA的。其中ACTIVEX只支持IE不去考虑,HTML5低版本浏览器不支持同样放弃,剩下只有FLASH了。JAVA要重新开发,没时间。网上找了很久,终于找到一个JQUERY的插件可以实现调动视频。上代码:

 1.官网下载相关文件

 http://www.xarg.org/project/jquery-webcam-plugin/

 2.前端脚步:

  

<script>
$(function() {
    var swfpah="${pageContext.request.contextPath}/resources/plugins/jQuery-webcam-master/jscam_canvas_only.swf";//FLASH连接
    var pos = 0, ctx = null, saveCB, image = [];
     var w=320;
     var h=240;
    var canvas = document.createElement("canvas");
    canvas.setAttribute('width', w);
    canvas.setAttribute('height', h);
    
    if (1==0&&canvas.toDataURL) {//支持HTML5时候用
debugger;
        ctx = canvas.getContext("2d");
        image = ctx.getImageData(0, 0, w, h);
        saveCB = function(data) {//会循环调用该方法直到读完每行,data是一行的坐标。
            var col = data.split(";");
            var img = image;
            for(var i = 0; i < 320; i++) {                var tmp = parseInt(col[i]);
                img.data[pos + 0] = (tmp >> 16) & 0xff;
                img.data[pos + 1] = (tmp >> 8) & 0xff;
                img.data[pos + 2] = tmp & 0xff;
                img.data[pos + 3] = 0xff;
                pos+= 4;
            }
            if (pos >= 4 * w * h) {
                ctx.putImageData(img, 0, 0);
                $.ajax({
                    url : "../test2/video",
                    dataType : "json",
                    type : 'post',
                    data:{
                        type: "data", 
                        image: canvas.toDataURL("image/png")
                    },
                    error:function(e)
                    {
                    },
                    beforeSend:function(){
                        layer.load();
                    },
                    complete:function(){
                        layer.closeAll('loading');
                    },
                    success : function(url) {
                        $('#myImg').attr('src',url);
                    }
                })
            //    $.post("../test2/video?tmp=" + Math.random(), {type: "data", image: canvas.toDataURL("image/png")},function(url)
            //            {
            //        $('#myImg').attr('src',url);
            //        },"json");
                pos = 0;
            }
        };

    } else {
        saveCB = function(data) {//循环调用该方法
            image.push(data);
            pos+= 4 * w;    
            if (pos >= 4 * w * h) {
                $.ajax({
                    url : "../test2/video",
                    dataType : "json",
                    type : 'post',
                    data:{
                        type: "pixel",
                        image: image.join('|'),
                        w:w,
                        h:h
                    },
                    error:function(c)
                    {
                    },
                    beforeSend:function(){
                        layer.load();
                    },
                    complete:function(){
                        layer.closeAll('loading');
                    },
                    success : function(url) {
                        $('#myImg').attr('src',url);
                    }
                })
            //    $.post("../test2/video", {type: "pixel", image: image.join('|'),w:w,h:h},function(url)
            //            {
            //        alert(url);
            //        $('#myImg').attr('src',url);
            //            },"json");
                pos = 0;
            }
        };
    }
  
    $("#webcam").webcam({
         w,
        height: h,
        mode: "callback",
        swffile: swfpah,
        onSave: saveCB,
        onCapture: function () {
            webcam.save();
        },
        debug: function (type, string) {
            console.log(type + ": " + string);
        },
        onLoad: function() {
            $('#test').bind('click',function(){
                webcam.capture();
            });
        }
    });
});

 </script> 

  HTML代码:

 1 <div id="webcam">       
 2    </div>
 3    <a href="javascript:webcam.capture();void(0);">Take a picture instantly</a>
 4    <input id="test" type="button" value="test" />
 5    <img id="myImg" alt="" src="">
 6 
 7 //webcam 加载成功后会有一个全局对象webcam。该对象内在方法:
 8 capture([delay])
 9 Captures an image internally.
10 save([file])
11 Saves the captured image accordingly to the storage mode.
12 getCameraList()
13 Get's an array of available cameras. If no camera is installed, an error is thrown and an empty array is returned.
14 setCamera([index])
15 Switches to a different camera. The parameter is the index of the element in the resulting array of getCameraList()

JAVA后台代码:

@RequestMapping(value = "/video", method = RequestMethod.POST)
        public @ResponseBody String video2(HttpServletRequest request, HttpServletResponse response) throws  IOException, DocumentException {
            String lx = request.getParameter("type");
            String image = request.getParameter("image");

             if(StringUtils.isEmpty(lx))
               return "";
        String image = request.getParameter("image");
        if(StringUtils.isEmpty(image))
          return "";

boolean r=false;
            String uuid= UUID.randomUUID().toString();
            String url = request.getContextPath() + "\resources\PDF\tmp\" + uuid + ".png";
         String outpath =  request.getRealPath("/") + "\resources\PDF\tmp\" + uuid + ".png";
            if(lx.equals("data"))
            {
                r=base64ToImg(image, outpath);
            }
            if(lx.equals("pixel"))
            {
                String w = request.getParameter("w");
                String h= request.getParameter("h");
                r=base32ToImg(w,h,image,outpath);
            }
            if(r)
            return url;
            else
            return "";
     }

@SuppressWarnings("restriction")//解析64位格式的
public boolean base64ToImg(String imgStr, String imgFilePath) {
        if (imgStr == null) {
            return false;
        }
        imgStr=imgStr.replace("data:image/png;base64,", "").trim();
        BASE64Decoder decoder = new BASE64Decoder();
        try {
            byte[] bytes = decoder.decodeBuffer(imgStr);
            for (int i = 0; i < bytes.length; ++i) {
                if (bytes[i] < 0) {// 调整异常数据
                    bytes[i] += 256;
                }
            }
            OutputStream out = new FileOutputStream(imgFilePath);
            out.write(bytes);
            out.flush();
            out.close();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
}
//解析普通坐标数组的
public boolean base32ToImg(String width,String height,String imgStr,String imgFilePath) {
     if (imgStr == null) {
         return false;
     }
    int w = Integer.parseInt(width);
    int h = Integer.parseInt(height);
    try {
        BufferedImage bf = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
        String[] rows = imgStr.split("\|");
        for (int i = 0; i < rows.length; i++) {
            String[] col = rows[i].split(";");
            for (int j = 0; j < col.length; j++) {
                int data = Integer.parseInt(col[j], 10);
                bf.setRGB(j, i, data);
            }
        }
     File outfile=   new File(imgFilePath);
     if (outfile.exists()) {
         outfile.delete();
     }
        ImageIO.write(bf, "png", outfile);
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }
    return true;
}
原文地址:https://www.cnblogs.com/localwz/p/JOE.html