html+JavaScript调取摄像头实现拍照+ajax异步请求+Base64编码转图片保存

html+JavaScript调取摄像头拍照+ajax异步请求+Base64编码转图片保存

html调用JavaScript打开本地摄像头拍照,并使用ajax获取拍照内容异步请求后端;后端接收Base64编码数据,并将其转换为图片保存本地。
html代码示例



js调取摄像头代码示例

var mediaStreamTrack;
    document.getElementById("start").addEventListener("click", function () {
        navigator.getUserMedia = navigator.getUserMedia ||
            navigator.webkitGetUserMedia ||
            navigator.mozGetUserMedia;
        if (navigator.getUserMedia) {
            navigator.getUserMedia({audio: true, video: {width: 320, height: 320}},
                function (stream) {
                    mediaStreamTrack = typeof stream.stop === 'function' ? stream : stream.getTracks()[1];
                    video.src = (window.URL || window.webkitURL).createObjectURL(stream);
                    video.play();
                    $("#exPara2").show();
                },
                function (err) {
                    alert("发生错误无法使用摄像头");
                }
            );
        } else {
            alert("发生错误无法使用摄像头");
        }
    });
    document.getElementById("picture").addEventListener("click", function () {
        var context = document.getElementById("canvas").getContext("2d");
        context.drawImage(video, 0, 0, 320, 320);
        $("#exPara").show();
    });
    document.getElementById("stop").addEventListener("click", function () {
        mediaStreamTrack && mediaStreamTrack.stop();
    });

ajax异步上传代码示例

document.getElementById("sc").addEventListener("click", function () {
        var imgData = document.getElementById("canvas").toDataURL("image/png");
        var photo = imgData.substr(22);
        $.ajax({
            url: "url",
            type: "post",
            data: {photo: photo},
            success: function (data) {
                    alert("上传成功");
            }, error: function () {
                alert("发送错误,上传失败")
            }
        });
    });

java后端接收ajax传递数据

String uploadPath = this.getServletContext().getRealPath("/upload/");//保存路径(本地项目路径)
String filename=”文件名"+".png";
String photo=request.getParameter(“photo”);
boolean po=ImageBase64Utils.GenerateImage(photo,uploadPath,filename);

Base64编码转图片保存代码示例

public static boolean GenerateImage(String imgStr, String filePath, String fileName) {
        try {
            if (imgStr == null) {
                return false;
            }
            BASE64Decoder decoder = new BASE64Decoder();
            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;
        }
    }

注:如果通过远程服务器打开则必须是https协议, http协议也无法使用; 有些浏览器可能不支持此功能

你可能感兴趣的:(html+JavaScript调取摄像头实现拍照+ajax异步请求+Base64编码转图片保存)