Saltar al pie de página
USO DE IRONBARCODE

Cómo Crear un Escáner de Códigos de Barras MAUI Usando IronBarcode

Modern mobile applications increasingly rely on barcode scanning for inventory management, point-of-sale systems, and product tracking. Building a MAUI barcode scanner allows you to integrate barcode detection directly into your .NET MAUI application, combining a camera feed with image file processing to detect QR codes, Data Matrix, and other barcode formats. While many libraries focus on camera preview, IronBarcode excels at accurately reading barcodes and scanning them even under challenging conditions.

In this guide, I'll be showing you how to implement barcode scanning functionality in a .NET MAUI project using IronBarcode. By the end of it, you'll be able to scan multiple barcodes in one image file or from a device's camera, read data from any given barcode, and use IronBarcode in your own MAUI projects confidently.

What are the prerequisites for building an MAUI barcode scanner?

Before starting, ensure you have Visual Studio Code or Visual Studio 2022 installed, along with the .NET MAUI workload, and possess basic knowledge of C#. You’ll also need the .NET 8 SDK for optimal performance and support for cross-platform applications.

How do I set up a MAUI barcode scanning project?

Create a new .NET MAUI App project in Visual Studio 2022. Name it "BarcodeScannerApp" and select .NET 8 as the target framework.

Install IronBarcode through the NuGet Package Manager Console:

Install-Package BarCode

This installs a .NET library with support for multiple barcode formats, including QR code, Code 128, and Data Matrix. IronBarcode works offline and handles natively unsupported inverted barcodes, ensuring continuous scanning and better scanning consistency.

To activate IronBarcode, obtain a free trial license and add it to your code:

License.LicenseKey = "YOUR-LICENSE-KEY";
License.LicenseKey = "YOUR-LICENSE-KEY";
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

How do I configure camera permissions for Android and iOS?

Platform-specific camera permissions are essential for barcode scanning functionality. Each platform requires specific configuration in its manifest files.

For Android, edit Platforms/Android/AndroidManifest.xml:

<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

These permissions enable camera access and declare the usage of camera hardware, ensuring your app can capture barcode images on Android devices.

For iOS, modify Platforms/iOS/Info.plist:

<key>NSCameraUsageDescription</key>
<string>This app requires camera access to scan barcodes</string>
<key>NSCameraUsageDescription</key>
<string>This app requires camera access to scan barcodes</string>
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

This configuration provides the required privacy description that iOS displays when requesting camera permission from users.

How do I create the barcode scanner interface?

Design a simple, user-friendly interface in MainPage.xaml:

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="BarcodeScannerApp.MainPage">
    <VerticalStackLayout Padding="20" Spacing="20">
        <Label Text="Barcode Scanner" 
               FontSize="24" 
               HorizontalOptions="Center" />
        <Image x:Name="CapturedImage" 
               HeightRequest="300"
               Aspect="AspectFit" />
        <Label x:Name="ResultLabel" 
               Text="Tap button to scan"
               HorizontalOptions="Center" />
        <Button Text="Scan Barcode" 
                Clicked="OnScanClicked"
                BackgroundColor="#007ACC"
                TextColor="White" />
    </VerticalStackLayout>
</ContentPage>
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="BarcodeScannerApp.MainPage">
    <VerticalStackLayout Padding="20" Spacing="20">
        <Label Text="Barcode Scanner" 
               FontSize="24" 
               HorizontalOptions="Center" />
        <Image x:Name="CapturedImage" 
               HeightRequest="300"
               Aspect="AspectFit" />
        <Label x:Name="ResultLabel" 
               Text="Tap button to scan"
               HorizontalOptions="Center" />
        <Button Text="Scan Barcode" 
                Clicked="OnScanClicked"
                BackgroundColor="#007ACC"
                TextColor="White" />
    </VerticalStackLayout>
</ContentPage>
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

This layout creates a clean interface featuring an image preview area, a result display label, and a scan button. The VerticalStackLayout provides consistent spacing and padding for a professional appearance.

How do I implement the barcode reader functionality?

Implement the scanning logic in MainPage.xaml.cs using IronBarcode's image processing capabilities:

using IronBarCode;
using IronSoftware.Drawing;
namespace BarcodeScannerApp;
public partial class MainPage : ContentPage
{
    public MainPage()
    {
        InitializeComponent();
        License.LicenseKey = "YOUR-LICENSE-KEY";
    }
    private async void OnScanClicked(object sender, EventArgs e)
    {
        try
        {
            // Capture photo using device camera
            var photo = await MediaPicker.Default.CapturePhotoAsync();
            if (photo == null) return;
            // Convert photo to byte array
            using var stream = await photo.OpenReadAsync();
            using var memoryStream = new MemoryStream();
            await stream.CopyToAsync(memoryStream);
            var imageBytes = memoryStream.ToArray();
            // Display captured image
            CapturedImage.Source = ImageSource.FromStream(() => 
                new MemoryStream(imageBytes));
            // Process with IronBarcode
            var bitmap = AnyBitmap.FromBytes(imageBytes);
            var results = await BarcodeReader.ReadAsync(bitmap);
            // Display results
            if (results.Any())
            {
                var barcodeValue = results.First().Value;
                ResultLabel.Text = $"Scanned: {barcodeValue}";
            }
            else
            {
                ResultLabel.Text = "No barcode detected";
            }
        }
        catch (Exception ex)
        {
            await DisplayAlert("Error", 
                $"Scanning failed: {ex.Message}", "OK");
        }
    }
}
using IronBarCode;
using IronSoftware.Drawing;
namespace BarcodeScannerApp;
public partial class MainPage : ContentPage
{
    public MainPage()
    {
        InitializeComponent();
        License.LicenseKey = "YOUR-LICENSE-KEY";
    }
    private async void OnScanClicked(object sender, EventArgs e)
    {
        try
        {
            // Capture photo using device camera
            var photo = await MediaPicker.Default.CapturePhotoAsync();
            if (photo == null) return;
            // Convert photo to byte array
            using var stream = await photo.OpenReadAsync();
            using var memoryStream = new MemoryStream();
            await stream.CopyToAsync(memoryStream);
            var imageBytes = memoryStream.ToArray();
            // Display captured image
            CapturedImage.Source = ImageSource.FromStream(() => 
                new MemoryStream(imageBytes));
            // Process with IronBarcode
            var bitmap = AnyBitmap.FromBytes(imageBytes);
            var results = await BarcodeReader.ReadAsync(bitmap);
            // Display results
            if (results.Any())
            {
                var barcodeValue = results.First().Value;
                ResultLabel.Text = $"Scanned: {barcodeValue}";
            }
            else
            {
                ResultLabel.Text = "No barcode detected";
            }
        }
        catch (Exception ex)
        {
            await DisplayAlert("Error", 
                $"Scanning failed: {ex.Message}", "OK");
        }
    }
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

This implementation captures an image through MediaPicker, converts it to a byte array for processing, and uses IronBarcode's BarcodeReader.ReadAsync method for detection. The AnyBitmap.FromBytes method handles various image formats automatically. Error handling ensures graceful failure recovery with user-friendly messages.

With this code, we can scan this barcode:

How to Create a MAUI Barcode Scanner Using IronBarcode: Figure 2 - Input test barcode

And you should be able to see the barcode's data displayed on the screen:

How to Create a MAUI Barcode Scanner Using IronBarcode: Figure 3 - Scanned Barcode Value

What advanced features does IronBarcode offer?

IronBarcode provides several advanced features that enhance scanning reliability. The library's machine learning algorithms automatically adjust confidence thresholds, improving accuracy with challenging barcodes. Image correction filters handle rotated, skewed, or poorly lit barcodes without additional configuration.

For specific scanning requirements, customize the reader options:

var options = new BarcodeReaderOptions
{
    Speed = ReadingSpeed.Balanced,
    ExpectMultipleBarcodes = true,
    ExpectBarcodeTypes = BarcodeEncoding.QRCode | BarcodeEncoding.Code128
};
var results = await BarcodeReader.ReadAsync(bitmap, opcanbvations);
var options = new BarcodeReaderOptions
{
    Speed = ReadingSpeed.Balanced,
    ExpectMultipleBarcodes = true,
    ExpectBarcodeTypes = BarcodeEncoding.QRCode | BarcodeEncoding.Code128
};
var results = await BarcodeReader.ReadAsync(bitmap, opcanbvations);
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

This configuration optimizes scanning for specific barcode types and enables multiple barcode detection in a single image, reducing processing time while maintaining accuracy.

How to Create a MAUI Barcode Scanner Using IronBarcode: Figure 4 - Multiple codes scanned from same image

Common Troubleshooting Tips

Even with a robust MAUI barcode scanner setup, issues can occasionally arise due to device settings, image quality, or platform-specific constraints. The following tips address the most common problems encountered when implementing barcode scanning functionality in a .NET MAUI application:

  • Camera not opening: Ensure the following permissions are correctly set in the manifest node and redeploy the app. Also, check for supported multi-camera setups if you are testing on devices with multiple cameras or custom camera configurations.
  • Poor scan results: Adjust image resolution or lighting, or apply transformations to the barcode. Additionally, enabling continuous scanning and increasing the Speed option in BarcodeReaderOptions can improve scanning consistency.
  • Memory issues: Dispose of image streams properly using using statements. This ensures your barcode scanning functionality remains responsive and prevents unexpected crashes or slowdowns on Android devices or Microsoft Windows machines.
  • iOS issues: Confirm Info.plist includes proper QR code bindable properties. Testing on both iPhone and iPad devices is recommended to ensure consistent barcode scanning functionality across iOS devices.

Conclusion

IronBarcode transforms MAUI barcode scanning with its robust image processing engine and machine learning capabilities. Unlike real-time camera preview libraries, IronBarcode's approach ensures reliable scanning even in challenging conditions. The library's offline functionality and extensive format support make it ideal for enterprise applications. Now, you will be able to confidently take what we taught you today to create your own .NET MAUI barcode scanner. Looking to learn more? Be sure to read IronBarcodes' extensive documentation.

Start developing with a free trial for production deployment. IronBarcode's combination of accuracy, ease of implementation, and comprehensive features makes it the optimal choice for MAUI barcode scanning applications.

Preguntas Frecuentes

¿Cuál es la ventaja de usar IronBarcode para un escáner de códigos de barras MAUI?

IronBarcode se destaca en la lectura precisa de códigos de barras y su escaneo incluso en condiciones desafiantes, lo que lo hace ideal para la integración en aplicaciones MAUI.

¿Puede IronBarcode procesar múltiples formatos de códigos de barras en una aplicación MAUI?

Sí, IronBarcode puede detectar varios formatos de códigos de barras, incluidos los códigos QR y Data Matrix, lo que lo hace versátil para diferentes necesidades de aplicaciones.

¿Cómo se integra IronBarcode con el flujo de cámara en un escáner de códigos de barras MAUI?

IronBarcode permite una integración perfecta con el flujo de cámara, habilitando la detección y procesamiento de códigos de barras en tiempo real directamente dentro de aplicaciones MAUI.

¿IronBarcode soporta el escaneo de códigos de barras sin conexión en aplicaciones MAUI?

Sí, IronBarcode soporta el escaneo de códigos de barras sin conexión, permitiendo que funcione sin conexión a Internet, lo cual es beneficioso para aplicaciones móviles.

¿Cuáles son las características clave de IronBarcode para el escaneo de códigos de barras en MAUI?

Las características clave incluyen detección precisa de códigos de barras, soporte para varios formatos de códigos de barras y un rendimiento robusto incluso en condiciones desafiantes.

¿Cómo maneja IronBarcode las condiciones de escaneo desafiantes?

IronBarcode está diseñado para leer con precisión códigos de barras bajo condiciones desafiantes, como poca iluminación o ángulos inclinados, asegurando un rendimiento confiable.

¿Es fácil configurar los permisos de escaneo de códigos de barras con IronBarcode en MAUI?

Sí, IronBarcode proporciona una guía clara para configurar los permisos necesarios para el escaneo de códigos de barras, lo que lo hace sencillo de implementar en MAUI.

¿Puede usarse IronBarcode para aplicaciones de gestión de inventario en MAUI?

Absolutamente, IronBarcode es ideal para la gestión de inventario, ofreciendo capacidades eficientes de escaneo de códigos de barras que pueden integrarse en aplicaciones MAUI.

Jordi Bardia
Ingeniero de Software
Jordi es más competente en Python, C# y C++. Cuando no está aprovechando sus habilidades en Iron Software, está programando juegos. Compartiendo responsabilidades para pruebas de productos, desarrollo de productos e investigación, Jordi agrega un valor inmenso a la mejora continua del producto. La experiencia variada lo mantiene ...
Leer más