JAVA B/S通過網路攝影機採集圖片資訊解決方案。

來源:互聯網
上載者:User

標籤:

在瀏覽器上調用網路攝影機。有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({        width: 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;}

 

JAVA B/S通過網路攝影機採集圖片資訊解決方案。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.