Using IronBarcode With Blazor

This how-to article contains detailed instructions on how to integrate IronBarcode within a Blazor project. As an example, we will use IronBarcode in a Blazor app to scan barcodes/QRs captured from a user's webcam.

Create Blazor Project

Open Visual Studio => Create New Project => Blazor Server App:

CreateBlazorProject related to Create Blazor Project

Set a project name and location:

ProjectName related to Create Blazor Project

Select the .NET 6 framework (or any other modern Standard .NET version):

SelectFramework related to Create Blazor Project

And we are ready:

MainScreen related to Create Blazor Project

To add webcam support, add a new Razor component:

NewRazorComponent related to Create Blazor Project

Give it a name, then click Add:

NewRazorComponentName related to Create Blazor Project

Enable Webcam Functionality With JavaScript

Since this app is working with a user's webcam, it should perform the handling on the client-side for privacy. Add a JavaScript file to the project to handle webcam functionality and name it webcam.js:

JavascriptFileLocation related to Enable Webcam Functionality With JavaScript

Don't forget to include a reference to webcam.js in index.html:

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

Add the following code to 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

We need to open the user's webcam. Go ahead and do this when the page loads by overriding the OnInitializedAsync() method of Index.razor. Invoke the JavaScript initializeCamera() function you previously wrote.

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#

Now add HTML tags that will run the webcam video stream:

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

Capture the Image

To capture a frame from the webcam video feed, let's write another JavaScript function in webcam.js. This function will draw the current frame from the source video to the canvas destination.

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

This function will capture a frame, encode it to base64, then send the encoded image to a method in C# called ProcessImage(). The ProcessImage() method is the following: which sends the encoded image to server Side API to process it.

[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#

It handles sending the encoded image from getFrame() in JavaScript to a server-side API for processing.

Next, we need to call this JavaScript function when the Capture Frame button is clicked. Remember, our button is looking for a handler function called 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 Extracting Captured Image

Add the IronBarcode NuGet package to the server project:

Install-Package BarCode

Now, in the server project, add an API method to process the encoded image and extract the Barcode/QR value. The code below adds barcode reading functionality to the Blazor project. From the scanned image, we perform image pre-processing and feed it into the FromStream method. Pass the Image object into a method in the BarcodeReader class to scan the barcode in Blazor. The resulting barcode value is then accessible from Value property of the BarcodeResult object.

[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 OrElse 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#

You can find the sample project here.