天天看点

JQuery WebCam 网页拍照配置 保存服务端

网页头部引入 

<script src="jquery.min.js" type="text/javascript"></script>
    <script src="jquery.webcam.min.js" type="text/javascript"></script>
           

初始化摄像头

var pos = 0, ctx = null, saveCB, image = [];
        var pos = 0;
        var w = 320;
        var h = 240;
        $(function () {
            var canvas = document.createElement("canvas");
            canvas.setAttribute('width', 320);
            canvas.setAttribute('height', 240);

            if (canvas.toDataURL) {

                ctx = canvas.getContext("2d");

                image = ctx.getImageData(0, 0, 320, 240);

                saveCB = function (data) {

                    var col = data.split(";");
                    var img = image;

                    for (var i = 0; i < 320; 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 * 320 * 240) {
                        ctx.putImageData(img, 0, 0);
                        $.post("UploadImage.ashx", { type: "data", image: canvas.toDataURL("image/png") }, function (msg) {
                            var msgjson = JSON.parse(msg);
                            flashcam(msgjson.code, msgjson.picUrl);
                        });
                        pos = 0;
                    }
                };

            } else {

                saveCB = function (data) {
                    image.push(data);

                    pos += 4 * 320;

                    if (pos >= 4 * 320 * 240) {
                        $.post("UploadImage.ashx", { type: "pixel", image: image.join('|') }, function (msg) {
                            var msgjson = JSON.parse(msg);
                            flashcam(msgjson.code, msgjson.picUrl);
                        });
                        pos = 0;
                    }
                };
            }
<span style="white-space:pre">	</span>  //延时加载flash
            setTimeout(callFlash, 500);
        });
        function callFlash() {
            $("#Camera").webcam({
                width: 320,
                height: 240,
                mode: "callback",
                swffile: "jscam.swf?" + Math.random(),
                onTick: function () { },
                onSave: saveCB,
                onCapture: function () {
                    webcam.save();
                },
                debug: function () { },
                onLoad: function () { }
            });
        }
           

调用webcam.capture();进行拍照

<div id="Camera"></div><div id="avatar_priview" style="width: 320px"></div><input type="button" οnclick=" webcam.capture();" value="拍照"/>
           

服务器端解析

/// <summary>
    /// UploadImage 的摘要说明
    /// </summary>
    public class UploadImage : IHttpHandler
    {

        #region 静态字段
        static JavaScriptSerializer jss = new JavaScriptSerializer();
        UpFileResponseModel fail1 = new UpFileResponseModel() { code = -1, msg = "", picUrl = "" };
        UpFileResponseModel fail2 = new UpFileResponseModel() { code = -2, msg = "", picUrl = "" };
        #endregion

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/html";

            var imageStr = context.Request["image"].Replace("data:image/png;base64,", "").Trim();

            string fileName = DateTime.Now.Ticks.ToString();

            var path = "~/upload/" + fileName;//上传至upload文件夹

            Base64StringToImage(path, imageStr);

            UpFileResponseModel model = new UpFileResponseModel() { code = 1, msg = "\u6210\u529f", picUrl = "/upload/" + fileName + ".jpg" };

            context.Response.Write( jss.Serialize(model));

        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }

        private byte[] String_To_Bytes2(string strInput)
        {
            int numBytes = (strInput.Length) / 2;
            byte[] bytes = new byte[numBytes];

            for (int x = 0; x < numBytes; ++x)
            {
                bytes[x] = Convert.ToByte(strInput.Substring(x * 2, 2), 16);
            }

            return bytes;
        }

        /// <summary>
        /// base64编码的文本 转为    图片
        /// </summary>
        /// <param name="txtFilePath">文件相对路径</param>
        /// <param name="str">图片字符串</param>
        private void Base64StringToImage(string txtFilePath, string str)
        {
            try
            {
                String inputStr = str;
                byte[] arr = Convert.FromBase64String(inputStr);
                MemoryStream ms = new MemoryStream(arr);
                Bitmap bmp = new Bitmap(ms);

                bmp.Save(System.Web.HttpContext.Current.Server.MapPath(txtFilePath) + ".jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
                //bmp.Save(txtFileName + ".bmp", ImageFormat.Bmp);
                //bmp.Save(txtFileName + ".gif", ImageFormat.Gif);
                //bmp.Save(txtFileName + ".png", ImageFormat.Png);
                ms.Close();
                //imgPhoto.ImageUrl = txtFilePath + ".jpg";
                //MessageBox.Show("转换成功!");
            }
            catch (Exception ex)
            {

            }
        }
}}
           
//上传图片返回模型
public class UpFileResponseModel
{
        
        public int code { get; set; }
        public string msg { get; set; }
        public string picUrl { get; set; }
}
           
上一篇: C++ 遍历设备
下一篇: c#转义字符