最近想在网站上添加扫码找书功能,查了下资料,选择了使用HTML5调用摄像头拍摄图片上传到服务器解析的功能,这篇文章只有HTML5调用摄像头的部分代码,并没有解析ISBN与Qr的代码,会在另一篇文章中进行总结。

话不多说,直接上代码

布局代码:

 <input type="button" title="开启摄像头" value="开启摄像头" onclick="getMedia();" /><br />@* 启动摄像头按钮 *@

 <video height="120px" autoplay="autoplay"></video><hr />@* 摄像头显示 *@

 <input type="button" title="开始传递图片" value="开始传递图片" onclick="setTimeout('ajaxISBN()', 3000);" /><br />@* 每三秒提交一次图片 *@

 <input type="button" title="拍照" value="拍照" onclick="getPhoto();" /><br />@* 保存图像到canvas *@

 <canvas id="canvas1" height="512" width="910"></canvas><hr />

JS代码:

        var video = document.querySelector('video');//获取视频显示组件

        var canvas1 = document.getElementById('canvas1');

        var context1 = canvas1.getContext('2d');


        navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;

        window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;

        var exArray = []; //存储设备源ID

        //获取设备ID

        navigator.mediaDevices.enumerateDevices()

            .then(function (devices) {

                devices.forEach(function (device) {

                    console.log(device.kind + ": " + device.label +

                        " id = " + device.deviceId);

                    exArray.push(device.deviceId);

                });

            })

            .catch(function (err) {

                console.log(err.name + ": " + err.message);

            });

        //开启摄像头

        function getMedia() {

            if (navigator.getUserMedia) {

                navigator.getUserMedia({

                    'video': {

                             mandatory: {

                             minAspectRatio: 1.40,

                             maxAspectRatio: 1.78,

                             minFrameRate: 15,

                             maxFrameRate: 25,

                             minWidth: 1280,

                             minHeight: 720

                       },

                        'optional': [{

                            'sourceId': exArray[1] //0为前置摄像头,1为后置

                        }]

                    },

                    'audio': true

                }, successFunc, errorFunc);    //success是获取成功的回调函数

            }

            else {

                alert('Native device media streaming (getUserMedia) not supported in this browser.');

            }

        }

        //开启成功回调函数

        function successFunc(stream) {

            //alert('Succeed to get media!');

            video = document.querySelector('video');//获取视频显示组件

            if (video.mozSrcObject !== undefined) {

                //Firefox中,video.mozSrcObject最初为null,而不是未定义的,我们可以靠这个来检测Firefox的支持

                video.mozSrcObject = stream;

            }

            else {

                video.src = window.URL && window.URL.createObjectURL(stream) || stream;

            }

        }

        //开启失败回调函数

        function errorFunc(e) {

            alert('Error!' + e);

        }


        //拍照

        function getPhoto() {

            context1.drawImage(video, 0, 0, 90, 120); //将video对象内指定的区域捕捉绘制到画布上指定的区域,实现拍照。

        }

        //将生成图像并上传

        function ajaxISBN() {

            var canvas1 = document.getElementById('canvas1');

            var context1 = canvas1.getContext('2d');

            // Generate the image data

            context1.drawImage(video, 0, 0, 910, 512); //将video对象内指定的区域捕捉绘制到画布上指定的区域,实现拍照。

            var Pic = canvas1.toDataURL("image/png");

            Pic = Pic.replace(/^data:image\/(png|jpg);base64,/, "")

            // Sending the image data to Server

            $.ajax({

                type: 'POST',

                url: '/Media/CameraImage',

                data: '{ "imageData" : "' + Pic + '" }',

                //contentType: 'application/json; charset=utf-8',

                contentType: 'application/json; charset=utf-8',

                dataType: 'text',

                success: function (msg) {

                    console.log("完成");

                    setTimeout("ajaxISBN()", 3000);

                }

            });

        }

ASPNET MVC接收代码:

  public ActionResult CameraImage(string imageData)

        {

            string Pic_Path = Server.MapPath(@"~/ContentQrBar/" + DateTime.Now.ToString("yyyyMMddHHffffff") + ".png");

            if (!Directory.Exists(Server.MapPath(@"~/Content/QrBar/")))

            {

                Directory.CreateDirectory(Server.MapPath(@"~/Content/QrBar/"));

            }

            byte[] data = Convert.FromBase64String(imageData);

            using (MemoryStream memoryStream = new MemoryStream(data, 0, data.Length))

            {

                Image bitmap = Image.FromStream(memoryStream);

                Bitmap bit = new Bitmap(bitmap);

                bit.Save(Pic_Path);

                return Content("");

            }

        }

    }

文章信息

创建时间
2023-12-11
作者
郭铭心
是否所有人可见
所有人可见
最后修改日期
2023-12-11
点击数
150
标签