在 Blazor 中使用 IronBarcode

This article was translated from English: Does it need improvement?
Translated
View the article in English

這篇操作指南文章包含有關如何在 Blazor 專案中整合 IronBarcode 的詳細說明。 作為示例,我們將在 Blazor 應用中使用 IronBarcode 掃描從用戶網絡攝影機捕獲的條碼/QR 碼。

創建 Blazor 專案

打開 Visual Studio => 建立新專案 => Blazor 伺服器應用程式:

CreateBlazorProject related to 創建 Blazor 專案

設置專案名稱和位置:

ProjectName related to 創建 Blazor 專案

選擇 .NET 6 框架(或任何其他現代標準 .NET 版本):

SelectFramework related to 創建 Blazor 專案

準備就緒:

MainScreen related to 創建 Blazor 專案

要添加網絡攝像頭支持,新增一個新的 Razor 組件:

NewRazorComponent related to 創建 Blazor 專案

取一個名稱,然後點擊新增

NewRazorComponentName related to 創建 Blazor 專案

使用 JavaScript 啟用網路攝影機功能

由於此應用程式與使用者的網路攝影機一起運作,為了隱私考量,它應在客戶端執行處理。 將一個 JavaScript 文件添加到專案中以處理攝像頭功能,並將其命名為 webcam.js

JavascriptFileLocation related to 使用 JavaScript 啟用網路攝影機功能

別忘了在 index.html 中包含對 webcam.js 的引用:

    <script src="webcam.js"></script>
    <script src="webcam.js"></script>
HTML

將以下代碼添加到 webcam.js

// current video stream
let videoStream;
async function initializeCamera() 
{
    const canvas = document.querySelector("#canvas");
    const video = document.querySelector("#video");
    if (
        !"mediaDevices" in navigator 

        !"getUserMedia" in navigator.mediaDevices
        )
        {
            alert("Camera API is not available in your browser");
            return;
        }

    // video constraints
    const constraints = {
        video: {
            width: {
                min: 180
            },
            height: {
                min: 120
            },
        },
    };

    constraints.video.facingMode = useFrontCamera ? "user" : "environment";

    try
    {
        videoStream = await navigator.mediaDevices.getUserMedia (constraints);    
        video.srcObject = videoStream;
    } 
    catch (err) 
    {
        alert("Could not access the camera" + err);
    }
}
JAVASCRIPT

我們需要開啟使用者的網路攝影機。 在頁面載入時透過覆寫 OnInitializedAsync 來執行此操作()Index.razor的方法。 調用 JavaScript initializeCamera()函數你之前寫的。

protected override async Task OnInitializedAsync()
{
    await JSRuntime.InvokeVoidAsync("initializeCamera");
}
protected override async Task OnInitializedAsync()
{
    await JSRuntime.InvokeVoidAsync("initializeCamera");
}
Protected Overrides Async Function OnInitializedAsync() As Task
	Await JSRuntime.InvokeVoidAsync("initializeCamera")
End Function
VB   C#

現在添加可運行網絡攝像頭視頻流的 HTML 標籤:

<section class="section">
    <video autoplay id="video" width="320"></video>
</section>
<section class="section">
    <video autoplay id="video" width="320"></video>
</section>
HTML

捕捉圖像

要從網路攝影機的視頻鏡頭中捕捉畫面,我們來在 webcam.js 中編寫另一個 JavaScript 函數。 此功能將會將來源影片的當前幀繪製到畫布目的地。

function getFrame(dotNetHelper) 
{
    canvas.width = video.videoWidth;
    canvas.height = video.videoHeight;
    canvas.getContext('2d').drawImage(video, 0, 0);
    let dataUrl = canvas.toDataURL("image/png");
    //Invoke ProcessImage Function and send DataUrl as a parameter to it 
    dotNetHelper.invokeMethodAsync('ProcessImage', dataUrl);
}
JAVASCRIPT

此函數將捕獲一個幀,將其編碼為base64,然後將編碼后的圖像發送到名為ProcessImage的C#方法。().ProcessImage()方法如下:將編碼圖像發送到伺服器端API進行處理。

[JSInvokable]
public async void ProcessImage(string imageString)
{

    var imageObject = new CamImage();
    imageObject.imageDataBase64 = imageString;
    var jsonObj = System.Text.Json.JsonSerializer.Serialize(imageObject);
    //Do image processing here
    var barcodeeResult = await Http.PostAsJsonAsync($"Ironsoftware/ReadBarCode", imageObject);
    if (barcodeeResult.StatusCode == System.Net.HttpStatusCode.OK)
    {
        QRCodeResult = barcodeeResult.Content.ReadAsStringAsync().Result;
        StateHasChanged();
    }
}
[JSInvokable]
public async void ProcessImage(string imageString)
{

    var imageObject = new CamImage();
    imageObject.imageDataBase64 = imageString;
    var jsonObj = System.Text.Json.JsonSerializer.Serialize(imageObject);
    //Do image processing here
    var barcodeeResult = await Http.PostAsJsonAsync($"Ironsoftware/ReadBarCode", imageObject);
    if (barcodeeResult.StatusCode == System.Net.HttpStatusCode.OK)
    {
        QRCodeResult = barcodeeResult.Content.ReadAsStringAsync().Result;
        StateHasChanged();
    }
}
<JSInvokable>
Public Async Sub ProcessImage(ByVal imageString As String)

	Dim imageObject = New CamImage()
	imageObject.imageDataBase64 = imageString
	Dim jsonObj = System.Text.Json.JsonSerializer.Serialize(imageObject)
	'Do image processing here
	Dim barcodeeResult = Await Http.PostAsJsonAsync($"Ironsoftware/ReadBarCode", imageObject)
	If barcodeeResult.StatusCode = System.Net.HttpStatusCode.OK Then
		QRCodeResult = barcodeeResult.Content.ReadAsStringAsync().Result
		StateHasChanged()
	End If
End Sub
VB   C#

它負責從 getFrame 發送編碼圖像()` 在 JavaScript 中傳送至伺服器端 API 進行處理。

接下來,我們需要在點擊 Capture Frame 按鈕時調用這個 JavaScript 函數。 請記住,我們的按鈕正在尋找一個名為 CaptureFrame 的處理函數。

private async Task CaptureFrame()
{
    await JSRuntime.InvokeAsync<String>("getFrame", DotNetObjectReference.Create(this));
}
private async Task CaptureFrame()
{
    await JSRuntime.InvokeAsync<String>("getFrame", DotNetObjectReference.Create(this));
}
Private Async Function CaptureFrame() As Task
	Await JSRuntime.InvokeAsync(Of String)("getFrame", DotNetObjectReference.Create(Me))
End Function
VB   C#

IronBarcode 提取捕獲的圖像

將 IronBarcode NuGet 套件新增到伺服器專案:

Install-Package BarCode

現在,在伺服器專案中,新增一個 API 方法來處理編碼的圖像並提取條碼/QR 值。 以下程式碼為 Blazor 專案新增條碼識別功能。 從掃描的圖像中,我們進行圖像預處理,然後將其輸入 FromStream 方法。 將 Image 對象傳入 BarcodeReader 類中的方法以掃描 Blazor 中的條形碼。 生成的條碼值可以從 BarcodeResult 物件的 Value 屬性中訪問。

[HttpPost]
[Route("ReadBarCode")]
public string ReadBarCode(CamImage imageData)
{
    try
        {
            var splitObject = imageData.imageDataBase64.Split(',');
            byte [] imagebyteData = Convert.FromBase64String((splitObject.Length > 1) ? splitObject [1] : splitObject [0]);
            IronBarCode.License.LicenseKey = "Key";

            using (var ms = new MemoryStream(imagebyteData))
            {
                Image barcodeImage = Image.FromStream(ms);
                var result = BarcodeReader.Read(barcodeImage);
                if (result == null 
 result.Value == null)
                {
                    return $"{DateTime.Now} : Barcode is Not Detetced";
                }

                return $"{DateTime.Now} : Barcode is ({result.Value})";
            }

        }
    catch (Exception ex)
        {
            return $"Exception is {ex.Message}";
        }
}

//Post Object 
public class CamImage
{
    public string imageDataBase64 { get; set; }
}
[HttpPost]
[Route("ReadBarCode")]
public string ReadBarCode(CamImage imageData)
{
    try
        {
            var splitObject = imageData.imageDataBase64.Split(',');
            byte [] imagebyteData = Convert.FromBase64String((splitObject.Length > 1) ? splitObject [1] : splitObject [0]);
            IronBarCode.License.LicenseKey = "Key";

            using (var ms = new MemoryStream(imagebyteData))
            {
                Image barcodeImage = Image.FromStream(ms);
                var result = BarcodeReader.Read(barcodeImage);
                if (result == null 
 result.Value == null)
                {
                    return $"{DateTime.Now} : Barcode is Not Detetced";
                }

                return $"{DateTime.Now} : Barcode is ({result.Value})";
            }

        }
    catch (Exception ex)
        {
            return $"Exception is {ex.Message}";
        }
}

//Post Object 
public class CamImage
{
    public string imageDataBase64 { get; set; }
}
<HttpPost>
<Route("ReadBarCode")>
Public Function ReadBarCode(ByVal imageData As CamImage) As String
	Try
			Dim splitObject = imageData.imageDataBase64.Split(","c)
			Dim imagebyteData() As Byte = Convert.FromBase64String(If(splitObject.Length > 1, splitObject (1), splitObject (0)))
			IronBarCode.License.LicenseKey = "Key"

			Using ms = New MemoryStream(imagebyteData)
				Dim barcodeImage As Image = Image.FromStream(ms)
				Dim result = BarcodeReader.Read(barcodeImage)
				If result Is Nothing result.Value Is Nothing Then
					Return $"{DateTime.Now} : Barcode is Not Detetced"
				End If

				Return $"{DateTime.Now} : Barcode is ({result.Value})"
			End Using

	Catch ex As Exception
			Return $"Exception is {ex.Message}"
	End Try
End Function

'Post Object 
Public Class CamImage
	Public Property imageDataBase64() As String
End Class
VB   C#

您可以找到範例專案這裡.