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.
How to Use Barcode Scanner in Blazor
- Install C# library to scan barcodes in Blazor
- Create a Blazor server project and add a new Razor component
- Enable webcam using JavaScript
- Configure the image capturing method to send images to the server
- Decode barcodes utilizing the BarcodeReader.Read method
Create Blazor Project
Open Visual Studio => Create New Project => Blazor Server App:
Set a project name and location:
Select the .NET 6 framework (or any other modern Standard .NET version):
And we are ready:
To add webcam support, add a new Razor component:
Give it a name, then click Add:
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
:
Don't forget to include a reference to webcam.js
in index.html
:
<script src="webcam.js"></script>
<script src="webcam.js"></script>
Add the following code to webcam.js
:
// Current video stream
let videoStream;
// Function to initialize camera access and stream it to a video element
async function initializeCamera() {
const canvas = document.querySelector("#canvas");
const video = document.querySelector("#video");
// Check if navigator supports media devices
if (!("mediaDevices" in navigator) || !("getUserMedia" in navigator.mediaDevices)) {
alert("Camera API is not available in your browser");
return;
}
// Define video constraints
const constraints = {
video: {
width: { min: 180 },
height: { min: 120 }
},
};
// Set camera facing mode: "user" for front camera, "environment" for back camera
constraints.video.facingMode = useFrontCamera ? "user" : "environment";
try {
// Request camera access
videoStream = await navigator.mediaDevices.getUserMedia(constraints);
video.srcObject = videoStream;
} catch (err) {
alert("Could not access the camera: " + err);
}
}
// Current video stream
let videoStream;
// Function to initialize camera access and stream it to a video element
async function initializeCamera() {
const canvas = document.querySelector("#canvas");
const video = document.querySelector("#video");
// Check if navigator supports media devices
if (!("mediaDevices" in navigator) || !("getUserMedia" in navigator.mediaDevices)) {
alert("Camera API is not available in your browser");
return;
}
// Define video constraints
const constraints = {
video: {
width: { min: 180 },
height: { min: 120 }
},
};
// Set camera facing mode: "user" for front camera, "environment" for back camera
constraints.video.facingMode = useFrontCamera ? "user" : "environment";
try {
// Request camera access
videoStream = await navigator.mediaDevices.getUserMedia(constraints);
video.srcObject = videoStream;
} catch (err) {
alert("Could not access the camera: " + err);
}
}
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
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>
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 to capture a frame from the video and send it to the server via Blazor
function getFrame(dotNetHelper) {
// Set canvas dimensions to match video
canvas.width = video.videoWidth;
canvas.height = video.videoHeight;
// Draw the current video frame onto the canvas
canvas.getContext('2d').drawImage(video, 0, 0);
// Convert the canvas content to a base64 encoded PNG image
let dataUrl = canvas.toDataURL("image/png");
// Send the image data to the C# method `ProcessImage`
dotNetHelper.invokeMethodAsync('ProcessImage', dataUrl);
}
// Function to capture a frame from the video and send it to the server via Blazor
function getFrame(dotNetHelper) {
// Set canvas dimensions to match video
canvas.width = video.videoWidth;
canvas.height = video.videoHeight;
// Draw the current video frame onto the canvas
canvas.getContext('2d').drawImage(video, 0, 0);
// Convert the canvas content to a base64 encoded PNG image
let dataUrl = canvas.toDataURL("image/png");
// Send the image data to the C# method `ProcessImage`
dotNetHelper.invokeMethodAsync('ProcessImage', dataUrl);
}
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 a server-side API to process it.
[JSInvokable]
public async Task ProcessImage(string imageString)
{
// Create an image object containing the base64 data
var imageObject = new CamImage();
imageObject.imageDataBase64 = imageString;
// Serialize image object to JSON
var jsonObj = System.Text.Json.JsonSerializer.Serialize(imageObject);
// Send image data to server-side API for processing
var barcodeeResult = await Http.PostAsJsonAsync("Ironsoftware/ReadBarCode", imageObject);
if (barcodeeResult.StatusCode == System.Net.HttpStatusCode.OK)
{
QRCodeResult = await barcodeeResult.Content.ReadAsStringAsync();
StateHasChanged();
}
}
[JSInvokable]
public async Task ProcessImage(string imageString)
{
// Create an image object containing the base64 data
var imageObject = new CamImage();
imageObject.imageDataBase64 = imageString;
// Serialize image object to JSON
var jsonObj = System.Text.Json.JsonSerializer.Serialize(imageObject);
// Send image data to server-side API for processing
var barcodeeResult = await Http.PostAsJsonAsync("Ironsoftware/ReadBarCode", imageObject);
if (barcodeeResult.StatusCode == System.Net.HttpStatusCode.OK)
{
QRCodeResult = await barcodeeResult.Content.ReadAsStringAsync();
StateHasChanged();
}
}
<JSInvokable>
Public Async Function ProcessImage(ByVal imageString As String) As Task
' Create an image object containing the base64 data
Dim imageObject = New CamImage()
imageObject.imageDataBase64 = imageString
' Serialize image object to JSON
Dim jsonObj = System.Text.Json.JsonSerializer.Serialize(imageObject)
' Send image data to server-side API for processing
Dim barcodeeResult = Await Http.PostAsJsonAsync("Ironsoftware/ReadBarCode", imageObject)
If barcodeeResult.StatusCode = System.Net.HttpStatusCode.OK Then
QRCodeResult = Await barcodeeResult.Content.ReadAsStringAsync()
StateHasChanged()
End If
End Function
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
IronBarcode Extracting Captured Image
Add the IronBarcode NuGet package to the server project:
dotnet add package IronBarCode
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 the Value property of the BarcodeResult object.
[HttpPost]
[Route("ReadBarCode")]
public string ReadBarCode(CamImage imageData)
{
try
{
// Decode the base64 image data
var splitObject = imageData.imageDataBase64.Split(',');
byte[] imagebyteData = Convert.FromBase64String((splitObject.Length > 1) ? splitObject[1] : splitObject[0]);
// Set IronBarcode license key (replace 'Key' with actual key)
IronBarCode.License.LicenseKey = "Key";
using (var ms = new MemoryStream(imagebyteData))
{
// Convert byte array to Image
Image barcodeImage = Image.FromStream(ms);
// Read barcode from Image
var result = BarcodeReader.Read(barcodeImage);
if (result == null || result.Value == null)
{
return $"{DateTime.Now}: Barcode is Not Detected";
}
return $"{DateTime.Now}: Barcode is ({result.Value})";
}
}
catch (Exception ex)
{
return $"Exception: {ex.Message}";
}
}
// Model to encapsulate the base64 image data
public class CamImage
{
public string imageDataBase64 { get; set; }
}
[HttpPost]
[Route("ReadBarCode")]
public string ReadBarCode(CamImage imageData)
{
try
{
// Decode the base64 image data
var splitObject = imageData.imageDataBase64.Split(',');
byte[] imagebyteData = Convert.FromBase64String((splitObject.Length > 1) ? splitObject[1] : splitObject[0]);
// Set IronBarcode license key (replace 'Key' with actual key)
IronBarCode.License.LicenseKey = "Key";
using (var ms = new MemoryStream(imagebyteData))
{
// Convert byte array to Image
Image barcodeImage = Image.FromStream(ms);
// Read barcode from Image
var result = BarcodeReader.Read(barcodeImage);
if (result == null || result.Value == null)
{
return $"{DateTime.Now}: Barcode is Not Detected";
}
return $"{DateTime.Now}: Barcode is ({result.Value})";
}
}
catch (Exception ex)
{
return $"Exception: {ex.Message}";
}
}
// Model to encapsulate the base64 image data
public class CamImage
{
public string imageDataBase64 { get; set; }
}
<HttpPost>
<Route("ReadBarCode")>
Public Function ReadBarCode(ByVal imageData As CamImage) As String
Try
' Decode the base64 image data
Dim splitObject = imageData.imageDataBase64.Split(","c)
Dim imagebyteData() As Byte = Convert.FromBase64String(If(splitObject.Length > 1, splitObject(1), splitObject(0)))
' Set IronBarcode license key (replace 'Key' with actual key)
IronBarCode.License.LicenseKey = "Key"
Using ms = New MemoryStream(imagebyteData)
' Convert byte array to Image
Dim barcodeImage As Image = Image.FromStream(ms)
' Read barcode from Image
Dim result = BarcodeReader.Read(barcodeImage)
If result Is Nothing OrElse result.Value Is Nothing Then
Return $"{DateTime.Now}: Barcode is Not Detected"
End If
Return $"{DateTime.Now}: Barcode is ({result.Value})"
End Using
Catch ex As Exception
Return $"Exception: {ex.Message}"
End Try
End Function
' Model to encapsulate the base64 image data
Public Class CamImage
Public Property imageDataBase64() As String
End Class
You can find the sample project here.
Frequently Asked Questions
What is IronBarcode?
IronBarcode is a C# library that allows developers to create, read, and manage barcodes and QR codes in .NET applications, including Blazor projects.
How can I integrate IronBarcode in a Blazor project?
To integrate IronBarcode in a Blazor project, install the IronBarcode NuGet package, set up a Blazor server project, enable webcam support with JavaScript, capture images, and decode them using IronBarcode's BarcodeReader.Read method.
How do I enable webcam support in a Blazor app?
Enable webcam support by adding a JavaScript file to your Blazor project. The file should contain functions to access and stream the webcam video, which can be invoked from Blazor using JS interop.
What JavaScript is needed to access the webcam?
The JavaScript should include a function like initializeCamera() that uses navigator.mediaDevices.getUserMedia to request camera access and stream the video to an HTML video element.
How do I capture and process a frame from the webcam in Blazor?
Write a JavaScript function to capture the current video frame, convert it to a base64 encoded image, and send it to a C# method using Blazor's JS interop. The C# method can then process the image for barcode reading.
How can I read barcodes in a Blazor project?
You can read barcodes by decoding a base64 image string in a server-side API method using IronBarcode's BarcodeReader class, which extracts the barcode value from the image.
What are the prerequisites for using IronBarcode in Blazor?
Ensure you have a Blazor server project set up, the IronBarcode NuGet package installed, and JavaScript configured to handle webcam input. You also need a license key for IronBarcode.
How do I send captured images to the server in Blazor?
Send captured images to the server by invoking a C# method with the image data using DotNetObjectReference in JavaScript, which calls the method with the base64 image string.
Can IronBarcode handle QR codes?
Yes, IronBarcode can create, read, and manage both barcodes and QR codes within .NET applications, including those built with Blazor.
Where can I find a sample Blazor project using IronBarcode?
A sample Blazor project using IronBarcode is available for download from the provided link in the article's conclusion section.