參考博客: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;
}
}