HTML 调用后置摄像头

2 篇文章 0 订阅

HTML 调用后置摄像头

<html>


<script type="text/javascript">

    var CameraInit = (function (window, document, undefined) {
        function MyCamera(videoDom, canvasDom) {
            this.mediaOpts = {
                audio: false,

                video: { facingMode: "environment" } // 或者 "user"  environment 后置摄像头 没有则调用前置
                // video: { width: 1280, height: 720 }
                // video: { facingMode: { exact: "environment" } }// 或者 "user"  
            }
            this.video = videoDom;
            this.canvas1 = canvasDom;
            this.context1 = this.canvas1.getContext('2d');
            this.mediaStreamTrack = null;
            this.checkEnvironment();
        }

        MyCamera.prototype = {
            checkEnvironment: function () {
                window.URL = (window.URL || window.webkitURL || window.mozURL || window.msURL);
                if (navigator.mediaDevices === undefined) {
                    navigator.mediaDevices = {};
                }
                if (navigator.mediaDevices.getUserMedia === undefined) {
                    navigator.mediaDevices.getUserMedia = function (constraints) {
                        var getUserMedia = navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
                        if (!getUserMedia) {
                            return Promise.reject(new Error('getUserMedia is not implemented in this browser'));
                        }
                        return new Promise(function (resolve, reject) {
                            alert('1')
                            getUserMedia.call(navigator, constraints, resolve, reject);
                        });
                    }
                }
            },
            // 回调
            successFunc: function (stream) {
                this.mediaStreamTrack = stream;
                this.video = document.querySelector('video');
                if ("srcObject" in this.video) {
                    this.video.srcObject = stream
                } else {
                    this.video.src = window.URL && window.URL.createObjectURL(stream) || stream
                }
                this.video.play();
            },
            errorFunc: function (err) {
                alert(err.name);
            },

            // 正式启动摄像头
            openMedia: function () {
                navigator.mediaDevices.getUserMedia(this.mediaOpts).then(this.successFunc.bind(this)).catch(this.errorFunc.bind(this));
            },

            //关闭摄像头
            closeMedia: function () {
                var that = this;
                that.mediaStreamTrack.getVideoTracks().forEach(function (track) {
                    track.stop();
                    that.context1.clearRect(0, 0, that.context1.width, that.context1.height);//清除画布
                });
            },

            //截取视频并转为图片
            drawMediaAndToImg: function () {
                this.canvas1.setAttribute("width", this.video.videoWidth);
                this.canvas1.setAttribute("height", this.video.videoHeight);
                this.context1.drawImage(this.video, 0, 0, this.video.videoWidth, this.video.videoHeight);//显示在canvas中
                inseterImg(this.canvas1.toDataURL('image/png'))

            },
        };
        return MyCamera;
    })(window, document)



</script>
<script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
<script type="text/javascript">

    /*
    * 点击放大图片
    * */

    Blod_base64 = function (blod, callback) {//blod文件转base60
        var a = new FileReader();
        a.readAsDataURL(blod);//读取文件保存在result中
        a.onload = function (e) {
            inseterImg(e.target.result);
        }

    }

    getImgdata = function (url) {//获取网络图片
        var xhr = new XMLHttpRequest();
        xhr.open('GET', url, true);
        xhr.responseType = 'blob';
        xhr.onload = function (ev) {
            if (xhr.status === 200) {
                Blod_base64(xhr.response)
            }
        };
        xhr.send();
    }
    showimg = function (event) {
        var obj = event.srcElement;
        var _this = obj;//将当前的pimg元素作为_this传入函数
        imgShow("#outerdiv", "#innerdiv", "#bigimg", _this);
    }

    function imgShow(outerdiv, innerdiv, bigimg, _this) {
        var src = _this.currentSrc;//获取当前点击的pimg元素中的src属性
        $(bigimg).attr("src", src);//设置#bigimg元素的src属性
        /*获取当前点击图片的真实大小,并显示弹出层及大图*/
        $("<img/>").attr("src", src).on('load',function () {
            var windowW = $(window).width();//获取当前窗口宽度
            var windowH = $(window).height();//获取当前窗口高度
            var realWidth = this.width;//获取图片真实宽度
            var realHeight = this.height;//获取图片真实高度
            var imgWidth, imgHeight;
            var scale = 0.8;//缩放尺寸,当图片真实宽度和高度大于窗口宽度和高度时进行缩放
            if (realHeight > windowH * scale) {//判断图片高度
                imgHeight = windowH * scale;//如大于窗口高度,图片高度进行缩放
                imgWidth = imgHeight / realHeight * realWidth;//等比例缩放宽度
                if (imgWidth > windowW * scale) {//如宽度扔大于窗口宽度
                    imgWidth = windowW * scale;//再对宽度进行缩放
                }
            } else if (realWidth > windowW * scale) {//如图片高度合适,判断图片宽度
                imgWidth = windowW * scale;//如大于窗口宽度,图片宽度进行缩放
                imgHeight = imgWidth / realWidth * realHeight;//等比例缩放高度
            } else {//如果图片真实高度和宽度都符合要求,高宽不变
                imgWidth = realWidth;
                imgHeight = realHeight;
            }
            $(bigimg).css("width", imgWidth);//以最终的宽度对图片缩放
            var w = (windowW - imgWidth) / 2;//计算图片与窗口左边距
            var h = (windowH - imgHeight) / 2;//计算图片与窗口上边距
            $(innerdiv).css({ "top": h, "left": w });//设置#innerdiv的top和left属性
            $(outerdiv).fadeIn("fast");//淡入显示#outerdiv及.pimg
        });
        $(outerdiv).click(function () {//再次点击淡出消失弹出层
            $(this).fadeOut("fast");
        });
    }
 

    function openVideo() {//打开摄像机
        if ($("#loapload").children().length > 6) {
          alert('最多支持6个文件!')
            return
        }


        window.MyCamera = new CameraInit(document.getElementById("video"), document.getElementById("qrCanvas"));
        $('.video_photo').css('display', 'block')
        $('.ajax_form_box').css('display', 'none')
        window.MyCamera.openMedia()
    }

    function saveimg() {
        window.MyCamera.drawMediaAndToImg()
        window.MyCamera.closeMedia()
        $('.ajax_form_box').css('display', 'block')
        $('.video_photo').css('display', 'none')

    }

    function deletePA(e) {
        //删除图片
        e.parentNode.remove(e);
    }
    function imgChange(obj) {//文件转流
        closeChouse()
        var image = obj.files[0]; //获取文件域中选中的图片
        if (image.type != 'image/png' && image.type != 'image/jpeg') {
            myDialog({
                ype: "confirm",
                title: "文件类型错误",
                content: "请选择.jpg/.png格式的文件",
                onConfirm: function (obj) {
                }
            });
            return
        }
        var reader = new FileReader(); //实例化文件读取对象
        reader.readAsDataURL(image); //将文件读取为 DataURL,也就是base64编码
        reader.onload = function (ev) { //文件读取成功完成时触发
            var dataURL = ev.target.result; //获得文件读取成功后的DataURL,也就是base64编码
            inseterImg(dataURL);
            window.MyCamera.closeMedia()
            $('.ajax_form_box').css('display', 'block')
            $('.video_photo').css('display', 'none')
            closeChouse()
        }
    }

    function Chouse() {
        $('#filesP').click();
    }

    function showChouse() {
        $('#chousefiles').css('display', 'block')
    }

    function closeChouse() {
        $('#chousefiles').css('display', 'none')
    }

    function inseterImg(src) {//form表单插入图片
        var div = document.createElement('div');
        var img = document.createElement('img');
        var input = document.createElement('input')
        var cls = document.createElement('div')
        input.style.display = 'none'
        cls.style.display = 'none'
        input.name = "uploadImg"//form表单提交的name
        input.setAttribute('value', src)
        img.setAttribute('onclick', 'showimg(event)')
        cls.setAttribute('onclick', 'deletePA(this)')
        cls.innerText = 'x'
        cls.className = 'del_img'
        img.src = src
        div.className = 'image-upload'
        div.appendChild(img)
        div.appendChild(input)
        div.appendChild(cls)
        var parentDIV = document.getElementById('loapload')
        parentDIV.insertBefore(div, document.getElementById('photo-video'))

    }
</script>

<style>
    .image-upload {
        width: 200px;
        height: 200px;
        border: 1px dotted;
        border-radius: 10px;
        float: left;
        margin: 5px;
        cursor: pointer;
        position: relative;
    }

    .del_img {
        position: absolute;
        text-align: center;
        top: 2px;
        right: 2px;
        width: 20px;
        height: 20px;
        background-color: #fff3f3;
        border-radius: 50%;
        box-shadow: 0 0 2px #0a9ac2;
        color: #999999;
        user-select: none;

    }

    .more_btn {
        cursor: pointer;
        position: absolute;
        top: 20px;
        right: 30px;
        background: #fff;
        height: 16px;
        color: #999;
        line-height: 0px;
        font-size: 24px;
        user-select: none;
        width: 30px;
        border-radius: 16px;
        text-align: center;
        z-index: 99999;
    }

    #chousefiles {
        cursor: pointer;
        width: 120px;
        display: none;
        user-select: none;
        background-color: #fff;
        position: absolute;
        height: 30px;
        text-align: center;
        top: 40px;
        right: 30px;
        z-index: 99999;
        line-height: 26px;
        color: #717171;
        border: 2px #fff solid;
        border-radius: 2px;
    }

    #chousefiles:hover {
        background-color: #e3e2e2;
    }

    .image-upload:hover .del_img {
        display: block !important;
    }

    .ajax_form_box {
        padding: 0 100px 100px 100px;

    }

    .image-upload img {
        width: 100%;
        height: 100%;
        object-fit: cover;
        border-radius: 8px;
    }

    #loapload {
        padding-left: 142px;
    }

    .file {
        position: relative;
        display: inline-block;
        background: #7e807e;
        border: 1px solid #99D3F5;
        border-radius: 4px;
        padding: 4px 12px;
        overflow: hidden;
        color: #0f0e0f;
        text-decoration: none;
        text-indent: 0;
        line-height: 20px;
    }

    .file input {
        position: absolute;
        font-size: 100px;
        right: 0;
        top: 0;
        opacity: 0;
    }

    .file:hover {
        background: #AADFFD;
        border-color: #78C3F3;
        color: #004974;
        text-decoration: none;
    }

    .cls {
        display: -webkit-flex;
        display: flex;
        -webkit-justify-content: space-around;
        justify-content: space-around;
        padding: 0px 60px 0px 0px
    }

    .video_photo {
        display: none;
        background: #000;
        box-shadow: 0 0 5px;
        width: 100vw;
        height: 100vh;
        left: 0;
        top: 0;
    }

    .video-bg {
        width: 100%;
        height: 100%;
        background: #000;
    }

 

    .shotPhotos {
        position: absolute;
        top: 85vh;
        left: calc(50% - 40px);
        width: 80px;
        height: 80px;
     
        background: #fff;
        border: 5px #ca0c00 solid;
        border-radius: 50%;
        cursor: pointer;
    }

    .shotPhotos_round {
        width: 60px;
        height: 60px;
        background: #ca0c00;
        border-radius: 50%;
        margin: 9px;
    }
</style>

<body>

    <div class="video_photo">
        <div onclick="showChouse()" class="more_btn">...</div>
        <div id="chousefiles" onclick="Chouse()">
            选择本地文件
        </div>
        <input type="file" style="display: none" id="filesP" onchange="imgChange(this)">
        <video id="video" class="video-bg" onclick="closeChouse()"></video>
        <canvas id="qrCanvas" class="qr-canvas" style="display: none;"></canvas>

        <div onclick="saveimg()" class='shotPhotos'>
            <div class="shotPhotos_round"> </div>
        </div>
    </div>
    <div class="ajax_form_box">
        <form id="ajax_form" method="post" action="/" data-ajax="true" data-ajax-method="Post"
            data-ajax-mode="" data-ajax-update="" data-ajax-begin="" data-ajax-success="" data-ajax-complete=""
            data-ajax-failure="">
            <div>
                <div style="padding-top: 15px;margin-left:-40px">
                    <label class="mr-sm-2" style="width: 100px;margin-left: 34px; text-align: right">图片:</label>
                    <div id="loapload" style=" margin-top: -28px;">
                        <div class="image-upload" id="photo-video" onclick="openVideo()">
                            <svg t="1607338307020" class="icon" viewBox="0 0 1024 1024" version="1.1"
                                xmlns="http://www.w3.org/2000/svg" p-id="3379" style="margin: 35px" width="120"
                                height="120">
                                <path
                                    d="M121.6 856c-32 0-57.6-25.6-57.6-57.6V340.8c0-32 25.6-60.8 59.2-60.8H256c8 0 16-3.2 20.8-11.2l52.8-83.2c14.4-20.8 38.4-33.6 64-33.6h235.2c25.6 0 48 11.2 60.8 32l59.2 86.4c4.8 6.4 11.2 9.6 19.2 9.6h131.2c33.6 1.6 60.8 28.8 60.8 62.4v456c0 16-6.4 30.4-17.6 41.6-11.2 11.2-25.6 17.6-41.6 17.6v-16 16H121.6c1.6-1.6 1.6-1.6 0-1.6z m134.4-544H123.2c-14.4 0-27.2 12.8-27.2 28.8v456c0 16 12.8 27.2 27.2 27.2h777.6c8 0 14.4-3.2 19.2-8s8-11.2 8-19.2V340.8c0-16-12.8-28.8-28.8-30.4h-129.6c-17.6 1.6-35.2-8-46.4-22.4l-59.2-88c-8-11.2-20.8-17.6-35.2-17.6H392c-14.4 0-28.8 6.4-36.8 19.2L304 286.4c-11.2 16-28.8 25.6-48 25.6z"
                                    fill="#636363" p-id="3380"></path>
                                <path
                                    d="M507.2 766.4c-126.4 0-228.8-102.4-228.8-228.8s102.4-228.8 228.8-228.8S736 411.2 736 537.6s-102.4 228.8-228.8 228.8z m0-425.6c-108.8 0-196.8 88-196.8 196.8S400 734.4 507.2 734.4 704 646.4 704 537.6s-88-196.8-196.8-196.8z"
                                    fill="#636363" p-id="3381"></path>
                                <path
                                    d="M507.2 696c-88 0-158.4-72-158.4-158.4s72-158.4 158.4-158.4c88 0 158.4 72 158.4 158.4s-70.4 158.4-158.4 158.4z m0-284.8c-70.4 0-126.4 57.6-126.4 126.4 0 70.4 57.6 126.4 126.4 126.4s126.4-57.6 126.4-126.4c1.6-70.4-56-126.4-126.4-126.4z"
                                    fill="#636363" p-id="3382"></path>
                            </svg>
                        </div>
                    </div>
                    <div style="clear: both"></div>
                    <div id="outerdiv"   style="position:fixed;top:0;left:0;background:rgba(0,0,0,0.7);z-index:999;width:100%;height:100%;display:none;">
                    <div id="innerdiv" style="position:absolute;">
                        <img id="bigimg" style="border:5px solid #fff;" src="" />
                    </div>
                    </div>
                </div>
            </div>
        </form>
    </div>
    </div>
</body>

</html>
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要在Winform C#应用程序中调用后置摄像头,可以使用Windows API函数来实现。具体步骤如下: 1. 在代码中引用Windows API函数,包括kernel32.dll和user32.dll。 2. 使用user32.dll中的SendMessage函数来发送一个消息给摄像头设备,以控制其行为。通过SendMessage函数,可以向摄像头发送不同的消息,以便控制其工作模式。 3. 在SendMessage函数中,设置不同的消息参数以控制摄像头的工作模式。例如,要锁定后置摄像头,可以使用消息参数“WM_CAP_SET_VIDEOFORMAT”。 4. 通过使用这些Win API函数,可以在Winform C#应用程序中调用后置摄像头并控制其行为。 下面是一些代码示例,以演示如何使用Windows API函数在Winform C#应用程序中调用后置摄像头: ```csharp // 引用相应的Windows API函数 [DllImport("user32.dll")] public static extern int SendMessage(int hwnd, int wMsg, int wParam, int lParam); [DllImport("kernel32.dll")] public static extern int GetTickCount(); // 设置消息参数 const int WM_CAP_SET_VIDEOFORMAT = 0x41e; const int WM_CAP_DRIVER_CONNECT = 0x40a; const int WM_CAP_DRIVER_DISCONNECT = 0x40b; const int WM_CAP_EDIT_COPY = 0x41e; const int WM_CAP_SET_PREVIEW = 0x432; const int WM_CAP_SET_PREVIEWRATE = 0x434; const int WM_CAP_SET_SCALE = 0x435; const int WS_CHILD = 0x40000000; const int WS_VISIBLE = 0x10000000; const short SWP_NOMOVE = 0x2; const short SWP_NOSIZE = 1; const short SWP_NOZORDER = 0x4; const short HWND_BOTTOM = 1; // 代码示例 private void Form1_Load(object sender, EventArgs e) { // 连接摄像头设备 SendMessage(0, WM_CAP_DRIVER_CONNECT, 0, 0); // 设置后置摄像头 SendMessage(0, WM_CAP_SET_VIDEOFORMAT, 0, "back camera"); // 锁定后置摄像头 SendMessage(0, WM_CAP_SET_PREVIEWRATE, 30, 0); SendMessage(0, WM_CAP_SET_PREVIEW, 1, 0); } private void Form1_FormClosing(object sender, FormClosingEventArgs e) { // 断开摄像头设备连接 SendMessage(0, WM_CAP_DRIVER_DISCONNECT, 0, 0); } ``` 上述代码示例中,我们使用了SendMessage函数发送不同的消息来控制摄像头的行为。通过设置消息参数,我们可以控制摄像头的工作模式,例如设置后置摄像头、锁定后置摄像头等。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值