java实现调用摄像头拍照
花了两个小时实现了javaWeb调用摄像投拍照功能。
javaWeb调用摄像头拍照,有两种解决方案:一种是使用ActiveX控件调用摄像头实现拍照上传功能,这种方式只能在ie浏览器下有效,限制非常大;另一种是调用flash实现拍照功能,这篇博客就主要介绍下如果通过调用flash插件实现调用本地摄像头拍照的功能。
运行后的页面效果如下图:
html页面源码如下
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'index.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
<script src="http://libs.baidu.com/jquery/1.6.4/jquery.min.js"></script>
<script type="text/javascript" src="/sxt/js/jquery.webcam.min.js"></script>
<script type="text/javascript">
$(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("servlet/CatD", {type: "data", image: canvas.toDataURL("image/png")}, function(msg){
console.log("===="+eval(msg));
pos = 0;
$("#img").attr("src", msg+"");
}); */
$.ajax({
type: "post",
url: "servlet/CatD?t="+new Date().getTime(),
data: {type: "pixel", image: canvas.toDataURL("image/png")},
dataType: "html",
success: function(data){
console.log("===="+data);
pos = 0;
$("#img").attr("src", "");
$("#img").attr("src", data);
}
});
}
};
} else {
saveCB = function(data) {
image.push(data);
pos+= 4 * w;
if (pos >= 4 * w * h) {
/* $.post("servlet/CatD", {type: "pixel", image: image.join('|')}, function(msg){
console.log("+++++"+eval(msg));
pos = 0;
$("#img").attr("src", msg+"");
}); */
$.ajax({
type: "post",
url: "servlet/CatD",
data: {type: "pixel", image: image.join('|')},
dataType: "json",
success: function(data){
console.log("+++++"+eval(msg));
pos = 0;
$("#img").attr("src", msg+"");
}
});
}
};
}
$("#webcam").webcam({
width: w,
height: h,
mode: "callback",
swffile: "js/jscam_canvas_only.swf",
onSave: saveCB,
onCapture: function () {
webcam.save();
},
debug: function (type, string) {
console.log(type + ": " + string);
}
});
});
//拍照
function savePhoto(){
webcam.capture();
}
/*$(function () {
var image = new Array();
var w = 320, h = 240;
var pos = 0;
$("#webcam").webcam({
width: w,
height: h,
mode: "callback",
swffile: "${ctxStatic }/jquery-plugin/jscam_canvas_only.swf", // canvas only doesn't implement a jpeg encoder, so the file is much smaller
onTick: function (remain) {
if (0 == remain) {
jQuery("#status").text("Cheese!");
} else {
jQuery("#status").text(remain + " seconds remaining...");
}
},
onSave: function (data) {
// Work with the picture. Picture-data is encoded as an array of arrays... Not really nice, though =/
image.push(data);
pos += 4 * w;
if (pos == 4 * w * h) {
$.post("${ctx}/common/webcam/uploadPhoto", {w: w, h: h, image: image.join('|')}, function (msg) {
pos = 0;
image = new Array();
$("#img").attr("src", "${ctx}/"+msg);
});
}
},
onCapture: function () {
webcam.save();
// Show a flash for example
},
debug: function (type, string) {
// Write debug information to console.log() or a div, ...
},
onLoad: function () {
// Page load
var cams = webcam.getCameraList();
for (var i in cams) {
jQuery("#cams").append("<li>" + cams[i] + "</li>");
}
}
});
});*/
</script>
<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>
</head>
<body>
<div id="webcam"></div>
<div class="btn">
<input type="button" value="删除" id="delBtn" onclick="delPhoto();"/>
<input type="button" value="拍照" id="saveBtn" onclick="savePhoto();"/>
</div>
<div id="photos">
<img src="" id="img">
</div>
</body>
</html>
servlet页面源码如下
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.alibaba.fastjson.JSON;
import sun.misc.BASE64Decoder;
public class CatD extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String basePath = "upload/";
String filePath = request.getSession().getServletContext().getRealPath("/") + basePath;
// String fileName = DateUtils.getDate("yyyyMMddHHmmss") + ".png";
String fileName = (new Date()).getTime()+".png";
//默认传入的参数带类型等参数:data:image/png;base64,
String imgStr = request.getParameter("image");
if (null != imgStr) {
imgStr = imgStr.substring(imgStr.indexOf(",") + 1);
}
Boolean flag = GenerateImage(imgStr, filePath, fileName);
String result = "";
if (flag) {
result = basePath + fileName;
}
// this.writeJson(result, resp);
response.getWriter().print(JSON.toJSON(result));
}
/**
* 功能描述:base64字符串转换成图片
*
* @since 2016/5/24
*/
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);
//如果目录不存在,则创建
File file = new File(filePath);
if (!file.exists()) {
file.mkdirs();
}
//生成图片
OutputStream out = new FileOutputStream(filePath + fileName);
out.write(b);
out.flush();
out.close();
return true;
} catch (Exception e) {
return false;
}
}
}
项目源码下载:链接: http://pan.baidu.com/s/1o7MM7Iq 密码: 8qeg