Cómo Usar un Escáner de Códigos de Barras en Blazor | IronBarcode

Using IronBarcode With Blazor

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

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;

// 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);
    }
}
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
$vbLabelText   $csharpLabel

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 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);
}
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 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
$vbLabelText   $csharpLabel

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
$vbLabelText   $csharpLabel

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
$vbLabelText   $csharpLabel

You can find the sample project here.

Preguntas Frecuentes

¿Cómo puedo integrar una biblioteca de códigos de barras en un proyecto Blazor?

Para integrar una biblioteca de códigos de barras en un proyecto Blazor, instale el paquete NuGet apropiado, configure un proyecto de servidor Blazor, habilite el soporte de cámara web con JavaScript, capture imágenes y decódelas usando los métodos de lectura de códigos de barras de la biblioteca.

¿Cómo habilito el soporte de cámara web en una aplicación Blazor?

Habilite el soporte de cámara web agregando un archivo JavaScript a su proyecto Blazor. El archivo debe contener funciones para acceder y transmitir el video de la cámara web, que se puede invocar desde Blazor usando la interoperabilidad de JS.

¿Qué JavaScript se necesita para acceder a la cámara web?

El JavaScript debe incluir una función como initializeCamera() que use navigator.mediaDevices.getUserMedia para solicitar acceso a la cámara y transmitir el video a un elemento de video HTML.

¿Cómo capturo y proceso un marco de la cámara web en Blazor?

Escriba una función JavaScript para capturar el marco de video actual, conviértalo en una imagen codificada en base64 y envíelo a un método C# usando la interoperabilidad de JS de Blazor. El método C# puede entonces procesar la imagen para leer códigos de barras.

¿Cómo puedo leer códigos de barras en un proyecto Blazor?

Puede leer códigos de barras decodificando una cadena de imagen base64 en un método API del lado del servidor usando la clase de lector de una biblioteca de códigos de barras, que extrae el valor del código de barras de la imagen.

¿Cuáles son los requisitos previos para usar una biblioteca de códigos de barras en Blazor?

Asegúrese de tener un proyecto de servidor Blazor configurado, el paquete NuGet necesario instalado y JavaScript configurado para manejar la entrada de la cámara web. También necesita una clave de licencia válida para la biblioteca de códigos de barras.

¿Cómo envío imágenes capturadas al servidor en Blazor?

Envíe imágenes capturadas al servidor invocando un método C# con los datos de la imagen usando DotNetObjectReference en JavaScript, que llama al método con la cadena de imagen en base64.

¿Esta biblioteca maneja códigos QR?

Sí, la biblioteca de códigos de barras puede crear, leer y gestionar tanto códigos de barras como códigos QR dentro de aplicaciones .NET, incluyendo aquellas construidas con Blazor.

¿Dónde puedo encontrar un proyecto de ejemplo Blazor usando una biblioteca de códigos de barras?

Un proyecto de ejemplo Blazor usando la biblioteca de códigos de barras está disponible para descargar desde el enlace proporcionado en la sección de conclusión del artículo.

Curtis Chau
Escritor Técnico

Curtis Chau tiene una licenciatura en Ciencias de la Computación (Carleton University) y se especializa en el desarrollo front-end con experiencia en Node.js, TypeScript, JavaScript y React. Apasionado por crear interfaces de usuario intuitivas y estéticamente agradables, disfruta trabajando con frameworks modernos y creando manuales bien ...

Leer más
¿Listo para empezar?
Nuget Descargas 1,935,276 | Versión: 2025.11 recién lanzado