调取摄像头拍照示例

页面:

<%@ 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">
    <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();
    }  

  <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>

后台方法:

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字符串转换成图片
     */
    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;
        }
    }
}

需要的jar包:

fastjson-1.2.7.jar

示例:

链接:https://pan.baidu.com/s/1e2tMqtklWz30-4y-ZvHQ_w
提取码:nc4w

原文地址:https://www.cnblogs.com/whatarewords/p/10986289.html

时间: 2024-08-30 14:29:28

调取摄像头拍照示例的相关文章

调取摄像头拍照

<div class="item" style="border:none;"> <span class="session-span">拍摄照片:</span> <div class="photo"> <video id="video" width="200" height="150"></video&g

React Native学习-调取摄像头第三方组件:react-native-image-picker

近期做的软件中图片处理是重点,那么自然也就用到了相机照相或者相册选取照片的功能. react-native中有image-picker这个第三方组件,但是0.18.10这个版本还不是太支持iPad. 这个组件同时支持photo和video,也就是照片和视频都可以用这个组件实现. 安装 npm install --save react-native-image-picker 安装过之后要执行rnpm link命令 用法  import ImagePickerManager from 'Native

android调用摄像头拍照

调用手机摄像头拍照,获取拍照后的图片数据.以下代码是在activity中:     // 调用摄像头         Button b = (Button) findViewById(R.id.btn1);     b.setOnClickListener(new View.OnClickListener() {         @Override         public void onClick(View v) {             // Here we fire the inte

win8 metro 自己写摄像头拍照项目

这个项目不是用的系统自带的CameraCaptureUI,是自己写的摄像头的调用,界面做的不好所以,不放了,但是可以实现拍照功能: 下面是using 程序命名空间: using Windows.Media.Capture; using Windows.Media.MediaProperties; using Windows.UI.Xaml.Media.Imaging; using Windows.Storage; using Windows.Storage.Pickers; using Wind

VS2010开发MFC ActiveX,摄像头拍照上传Webservice(2)

继续记录,第二步开发摄像头拍照功能. 使用vfw.h开发摄像头拍照功能,关于vfw网上有很多文章,很多代码可以参考 参考:http://blog.163.com/huangqiao_8/blog/static/33900492008017111847364/ Vedio for Windows 是WIN32 SDK 中多媒体编程SDK 的视频开发工具.在微软的Visual C ++中提供了Vedio for Windows 的头文件vfw.h 和库文件vfw32.lib. 在ActiveX中显示

C# 使用摄像头拍照 支持Win7 64位

原文:C# 使用摄像头拍照 支持Win7 64位 So, how do we capture an image from a WebCam? Once you download the source code that is attached to the article you should have the following three projects: Demo – simple Windows Forms project that demonstrates how a WebCam

在WPF中使用AForge.net控制摄像头拍照

原文:在WPF中使用AForge.net控制摄像头拍照 利用AForge.net控制摄像头拍照最方便的方法就是利用PictureBox显示摄像头画面,但在WPF中不能直接使用PictureBox.必须通过<WindowsFormsHost></WindowsFormsHost>来提供交换功能.其解决方法如下: 1.按照常规方法新建一个WPF应用程序: 2.添加引用 WindowsFormsIntegration  (与WinForm交互的支持) System.Windows.For

利用html5调用本地摄像头拍照上传图片[转]

利用html5调用本地摄像头拍照上传图片 html5概念啥的就不废话了,不知道的 百度, 谷歌一堆..今天学了学html5中的Canvas结合新增的<video>标签来获取本地摄像头,在html5之前,要在浏览器获取本地摄像头只有通过插件(ActiveX,但是这种只有IE支持)或者是flash来获取(或许你没学过flash那就很坑爹了),在之后微软的silvertlight中也可以获取,但这些都比较麻烦,在html5的世界里,要获取本地摄像头,只要配合js就可以轻松获取.. 目前支持html5

Ionic系列——调用摄像头拍照和选择图库照片功能的实现

1.需求描述 最近要做一个功能就是调用摄像头拍照,然后上传照片的功能,或者直接打开图库选择照片然后上传. 2.准备 ①.添加插件$cordovaCamera cordova plugin add cordova-plugin-camera ②.在controller中添加依赖 3.代码实现 $scope.takePhoto=function(){     var options = {