SpringBoot项目用 jQuery webcam plugin实现调用摄像头拍照并保存图片

姬飞昂
2023-12-01

参考博客:http://www.voidcn.com/article/p-oigngyvb-kv.html
//自定义样式

<style type="text/css">
    #webcam { border: 1px solid #666666; width: 320px; height: 240px; }
    #photos { border: 1px solid #666666; width: 320px; height: 240px; }
    .btn { width: 320px; height: auto; margin: 5px 0px; }
    .btn input[type=button] { width: 150px; height: 50px; line-height: 50px; margin: 3px; }
</style>
 
//展示内容
<div id="webcam"></div>
<div class="btn">
    <input type="button" value="拍照" id="saveBtn" onclick="savePhoto();"/>
</div>
<div id="photos">
    <img src="" id="img">
</div>

js部分:

<script src="assets/js/jquery.webcam.min.js" th:src="@{/assets/js/jquery.webcam.min.js}"></script>
	<script th:inline="javascript" type="text/javascript">
	/*<![CDATA[*/  
	$(function () {
		
		
        var w = 320, h = 240;
        var pos = 0, ctx = null, saveCB, image = [];
 
        var canvas = document.createElement("canvas");
        canvas.setAttribute('width', w);
        canvas.setAttribute('height', h);
 
        console.log(canvas.toDataURL);
        if (canvas.toDataURL) {
 
            ctx = canvas.getContext("2d");
 
            image = ctx.getImageData(0, 0, w, h);
 
            saveCB = function(data) {
 
                var col = data.split(";");
                var img = image;
 
                for(var i = 0; i < w; 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);
                    $.post(
                    		"/warehouseRecords/saveImg", 
                    		{type: "data", image: canvas.toDataURL("image/png")}, 
                    		function(data){
		                        //console.log(msg);
		                        //alert(JSON.stringify(data));
		                        //showSubmitResult(data);这个方法是拍照后的,可以不用管
		                        pos = 0;    //这个如果不设置就会一直循环
		                    }
                    );
                }
            };
 
        } else {
 
            saveCB = function(data) {
                image.push(data);
 
                pos+= 4 * w;
 
                if (pos >= 4 * w * h) {
                	//var id = $('[name="packageid_tab2"]').val();
                	//var batch = [[${batch}]];
                    $.post("/warehouseRecords/saveImg", 
                    		{type: "pixel", image: image.join('|')}, 
                    		function(data){
		                        //console.log(msg);
		                        //showSubmitResult(data);
		                        pos = 0;
                    		}
                   );
                }
            };
        }
 
        $("#webcam").webcam({
            width: w,
            height: h,
            mode: "callback",
            swffile: "/assets/js/jscam_canvas_only.swf",
 
            onSave: saveCB,
 
            onCapture: function () {
                webcam.save();
            },
 
            debug: function (type, string) {
                console.log(type + ": " + string);
            }
        });
    });
 
    //拍照
    function savePhoto(){
        webcam.capture();
    }
    
  
    
    /*]]>*/
	</script>

上面这块就能打开摄像头了;下面进行拍摄并保存图片到后台

/**
	 * 保存图片
	 * @author Caron
	 * @time 2018年12月27日下午3:12:52
	 */
	@RequestMapping("/saveImg")
	@ResponseBody
	public Object saveImg(HttpServletRequest request, HttpServletResponse response) {
		Map<String, Object> map = new HashMap<>();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
		Date date = new Date();
		String day = sdf.format(date);
		String basePath = "/var/project/java/img_drs/"+day +"/";
		//项目根目录
	    String path = request.getScheme() + ":"+File.separator+File.separator + request.getServerName() + ":" + request.getServerPort() + File.separator;
	    String packageId = request.getParameter("packageId");
	    String fileName = packageId + ".png";
	    //默认传入的参数带类型等参数:data:image/png;base64,
	    String imgStr = request.getParameter("image");
	    if (null != imgStr) {
	        imgStr = imgStr.substring(imgStr.indexOf(",") + 1);
	    }
	    Boolean flag = GenerateImage(imgStr, basePath, fileName);
	    if (flag) {//这里为true就表示图片保存成功了  后面的代码可以不用管
	    	String filePath = "img_drs"+ File.separator + day + File.separator + fileName;
	    	WarehouseRecords warehouseRecords = new WarehouseRecords();
	    	warehouseRecords.setPackageid(packageId);
	    	warehouseRecords.setBatchNo(request.getParameter("batchNo"));
	    	warehouseRecords.setStandby2(filePath);
	    	map = warehouseRecordsService.editWeight(warehouseRecords);
	    	
	    	map.put("packageId", packageId);
	    	map.put("projectPath", path);
	    	map.put("filePath", filePath);
	    }
	    return map;
	}
 
	public boolean GenerateImage(String imgStr, String filePath, String fileName) {
	    try {
	        if (imgStr == null) {
	            return false;
	        }
	        BASE64Decoder decoder = new BASE64Decoder();
	        //Base64解码
	        byte[] b = decoder.decodeBuffer(imgStr);
	        //如果目录不存在,则创建
	        String url = filePath + fileName;
	        File file = new File(url);//文件路径(路径+文件名)
            if (!file.exists()) {   //文件不存在则创建文件,先创建目录
                File dir = new File(file.getParent());
                dir.mkdirs();
                file.createNewFile();
            }
	        //生成图片
	        OutputStream out = new FileOutputStream(url);
	        out.write(b);
	        out.flush();
	        out.close();
	        return true;
	    } catch (Exception e) {
	        e.printStackTrace();
	        return false;
	    }
	}

jscam_canvas_only.swf 资源路径

 类似资料: