Java 调用摄像头
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
开发工具与关键技术:servlet+jsp+jdbc
作者:LYG
撰写时间:
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
从网上搜索出来的调用摄像头都很模糊,然后根据自己想要的功能摸索出来了调用摄像头的功能:
关键代码:
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setCharacterEncoding("utf-8");
String fun=request.getParameter("fun");
//保存摄像头拍下的图片
String basePath = "upload/img/";
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;
}
response.getWriter().print(JSON.toJSON(result));
}
然后就是保存你所获取到的拍照图片:
/**
* 解码生成图片
* @param request
* @param response
*/
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;
}
}
运行结果: