在 ASP.NET MVC 5 应用程序中通过摄像头读取条码

Read barcode via camera in an ASP.NET MVC 5 Application

我使用 ASP.NET MVC 5 创建了一个网站。该网站也可以在移动设备上作为 Web 应用程序使用。但现在我想增加用户在手机上使用应用程序时使用手机摄像头扫描条形码的可能性。当然有像 phonegap 这样的工具可以读取条形码,但关键是我想在我的 ASP.NET MVC 5 项目中添加这个功能。
那么有没有办法在 ASP.NET MVC 5 中通过移动摄像头读取条形码?

我已经解决了这个问题,解决方法如下: 在视图中(Index.chtml):

     <form>
            <input type="file" class="upload" size="45" name="file" id="file">
    </form>

form 标签中写 <input type="file"...> 很重要。 接下来我使用javascript。我使用它是因为我想在单击 Browse 按钮后立即调用控制器。您也可以使用提交按钮。
Javascript:

       $('#file').on("change", function () {
        for (i = 0; i < $('form').length; i++) {
            if ($('form').get(i)[0].value != "") /* get the file tag, you have to customize this code */
            {
                var formdata = new FormData($('form').get(i));
                CallService(formdata);
                break;
            }
        }
    });
    function CallService(file) {
        $.ajax({
            url: '@Url.Action("Scan", "Home")',
            type: 'POST',
            data: file,
            cache: false,
            processData: false,
            contentType: false,
            success: function (barcode) {
                alert(barcode);
            },
            error: function () {
                alert("ERROR");
            }
        });
    }

接下来我们对服务器中的图片进行分析,读取条码。我正在使用 Aspose.BarCode 库:
HomeController.cs

        public JsonResult Scan(HttpPostedFileBase file)
    {
        string barcode = "";
        try
        {
            string path = "";
            if (file.ContentLength > 0)
            {
                var fileName = Path.GetFileName(file.FileName);
                path = Path.Combine(Server.MapPath("~/App_Data"), fileName);
                file.SaveAs(path);
            }

            // Now we try to read the barcode
            // Instantiate BarCodeReader object
            BarCodeReader reader = new BarCodeReader(path, BarCodeReadType.Code39Standard);
            System.Drawing.Image img = System.Drawing.Image.FromFile(path);
            System.Diagnostics.Debug.WriteLine("Width:" + img.Width + " - Height:" + img.Height);

            try
            {
                // read Code39 bar code
                while (reader.Read())
                {

                    // detect bar code orientation
                    ViewBag.Title = reader.GetCodeText();
                    barcode = reader.GetCodeText();
                }
                reader.Close();
            }

            catch (Exception exp)
            {

                System.Console.Write(exp.Message);
            }


        }
        catch (Exception ex)
        {
            ViewBag.Title = ex.Message;
        }
        return Json(barcode);


    }
}

现在解码的条形码返回到视图。