Showing posts with label ZXing. Show all posts

Introduction .NET MAUI .NET MAUI, a cross-platform framework, empowers developers to build native mobile and desktop applicatio...

.NET MAUI Barcode Scanner using IRONBARCODE .NET MAUI Barcode Scanner using IRONBARCODE

A blog about android developement

ZXing

Introduction

.NET MAUI

.NET MAUI, a cross-platform framework, empowers developers to build native mobile and desktop applications using C# and XAML. It enables the creation of apps that seamlessly operate on Android, iOS, macOS, and Windows, all from a unified codebase. This open-source platform is an advancement of Xamarin Forms, expanding its reach to desktop scenarios while enhancing UI controls for improved performance and extensibility.


Using .NET MAUI, you have the capability to develop applications that can run on multiple platforms such as Android, iOS, MacOS, and Windows, all from a single codebase.


.NET MAUI allows for efficient cross-platform development, reducing the need for separate codebases for each platform and simplifying the maintenance and updates of your application.


.NET MAUI saves time and effort and makes it easier to maintain your apps. Visual Studio 2022 is avail with dotnet 7 with .Net Maui app development


In this article, we will see how we can implement a QR code or barcode scanner in the .NET MAUI project using IronBarcode Library.


IronBarcode: C# Barcode Library

The IronBarcode library simplifies barcode detection in .NET applications with its intuitive APIs and eliminates the need for intricate barcode object creation. It offers a wide range of QR code and barcode formats such as Code 39, Code 128, and PDF417.


As a versatile .NET library, it can also function as a QR code reader, decoding input data into readable text from various sources like images and streams. This article explores how to leverage the IronBarcode library for QR code scanning in .NET MAUI applications, providing a comprehensive guide.


Quick Links:


Project Setup:

  • Launch Visual Studio 2022, and in the start window click Create a new project to create a new project.
  • In the Create a new project window, select MAUI in the All project types drop-down, select the .NET MAUI App template, and click the Next button:
  • In the configure your new project window, name your project, choose a suitable location for it, and click the Next button:
  • In the Additional information window, click the Create button:
  • Once the project is created, we can able to see the Android, iOS, Windows and other running options in the toolbar. Press the emulator or run button to build and run the app

Install IronBarcode Library

To install the IronBarcode library via the NuGet Packages Console, simply execute the following command or visit the Nuget package website or search in the Nuget package Manager to download the latest version of the library.

Install-Package BarCode

Implementation of File Picker functionality

Ironbarcode library will read the barcode from the selected image and provide the result. For File Picker functionality, visit the official .NET MAUI essentials link and set up all the mentioned steps in the link.

Designing the screen

In this tutorial, we are using Image, Button, and Editor controls. You can change the design as per your preferences.

<?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="MAUI_Barcode.MainPage">

    <ScrollView>
        <VerticalStackLayout
            Spacing="25"
            Padding="30,0"
            VerticalOptions="Center">

            <Button
                x:Name="ImageSelect"
                Text="Select Barcode"
                SemanticProperties.Hint="Select Image"
                Clicked="SelectBarcode"
                HorizontalOptions="Center" />
            <Image
                x:Name="barcodeImage"
                SemanticProperties.Description="Selected Barcode"
                HeightRequest="200"
                HorizontalOptions="Center" />
            <Editor x:Name="outputText"
                Placeholder="Output text"
                HeightRequest="100"
                WidthRequest="500"
                    />
        </VerticalStackLayout>
    </ScrollView>

</ContentPage>

Here,

  • Button - used to select barcode images that need to be read.
  • Image - used to display the selected barcode image.
  • Editor - used to display the scanned result from Iron Barcode Library.

Functionality of the screen

  • Add a click event for the button to select the image like below. This event will allow the app to select the barcode image.
    private async void SelectBarcode(object sender, EventArgs e)
    {
    	var images = await FilePicker.Default.PickAsync(new PickOptions
    	{
    		PickerTitle = "Pick Barcode/QR Code Image",
    		FileTypes = FilePickerFileType.Images
    	});
    	var imageSource = images.FullPath.ToString();
    	barcodeImage.Source = imageSource;
    	var result = BarcodeReader.Read(imageSource).First().Text;
    	outputText.Text = result;	
    }
  • Once the barcode image is selected, the File Picker will return the full path of the file.
  • We will assign the file path to the image control to preview the selected image.
  • As well as the selected image's file path will be sent as input to the barcode read library.
  • Once the input is processed, the library will return the scanned output as a result of the barcode read function. This output will be assigned to the editor control for displaying the result in human-readable text.

Full Code

using IronBarCode;

namespace MAUI_Barcode;

public partial class MainPage : ContentPage
{

	public MainPage()
	{
		InitializeComponent();
	}

	private async void SelectBarcode(object sender, EventArgs e)
	{
		var images = await FilePicker.Default.PickAsync(new PickOptions
		{
            PickerTitle = "Pick Barcode/QR Code Image",
            FileTypes = FilePickerFileType.Images
		});
		var imageSource = images.FullPath.ToString();
		barcodeImage.Source = imageSource;
		var result = BarcodeReader.Read(imageSource).First().Text;
		outputText.Text = result;
		
    }
}

Output

Upon selecting the barcode, the editor will display a screenshot similar to the one below, with the output text of the QR Code visible.

Before selecting the barcode, similar to other platforms as well:

After selecting the barcode:

Download Code:

You can download the code from GitHub. If you have any doubts, feel free to post a comment. If you liked this article, and it is useful to you, do like, share the article & star the repository on GitHub.

Conclusion

This article detailed the process of barcode reading in a .NET MAUI application using IronBarcode. IronBarcode proves to be a comprehensive solution equipped with essential tools for barcode operations. Functioning as a QR code reader, IronBarcode delivers accurate and expected output, even when dealing with intricate barcodes. Furthermore, it offers the flexibility to create and customize barcodes using a variety of fonts.


IronBarcode is available for free for development purposes, but a license must be purchased for commercial use. To obtain information about the licensing options, please refer to the following link: https://ironsoftware.com/csharp/barcode/licensing

.NET MAUI is a powerful platform for building cross-platform mobile applications, and with the right tools and resources, it'...

.Net MAUI - Zxing Barcode Scanner .Net MAUI - Zxing Barcode Scanner

A blog about android developement

ZXing

.NET MAUI is a powerful platform for building cross-platform mobile applications, and with the right tools and resources, it's easy to add barcode scanning functionality to your app. In this tutorial, we'll walk you through the steps of implementing a barcode scanner in .NET MAUI using the ZXing.Net.MAUI plugin.

Quick Links:


Project Setup:

  • Launch Visual Studio 2022, and in the start window click Create a new project to create a new project.
  • In the Create a new project window, select MAUI in the All project types drop-down, select the .NET MAUI App template, and click the Next button:
  • In the configure your new project window, name your project, choose a suitable location for it, and click the Next button:
  • In the Additional information window, click the Create button:
  • Once the project is created, we can able to see the Android, iOS, Windows and other running options in the toolbar. Press the emulator or run button to build and run the app

Implementation:

The successor to ZXing.Net.Mobile: barcode scanning and generation for .NET MAUI applications. First, we need to add the ZXing.Net.MAUI library to our project as a dependency. To do this, open the NuGet Package Manager and search for "ZXing.Net.MAUI". Install the package in your .NET MAUI project.

Install ZXing.Net.MAUI

Install ZXing.Net.MAUI NuGet package on your .NET MAUI application. Make sure to initialize the plugin first in your MauiProgram.cs, see below

// Add the using to the top
using ZXing.Net.Maui;

// ... other code 

public static MauiApp Create()
{
    var builder = MauiApp.CreateBuilder();
    builder
    .UseMauiApp&lt;App&gt;()
    .UseBarcodeReader(); // Make sure to add this line

return builder.Build();
}

Now we just need to add the right permissions to our app metadata. Find below how to do that for each platform.

Android

For Android go to your "AndroidManifest.xml" file (under the Platforms\Android folder) and add the following permissions inside of the "manifest" node.

<uses-permission android:name="android.permission.CAMERA" />

iOS

For iOS go to your "info.plist" file (under the Platforms\iOS folder) and add the following permissions inside of the "dict" node:

<key>NSCameraUsageDescription</key>
<string>This app uses barcode scanning to...</string>

Make sure that you enter a clear and valid reason for your app to access the camera. This description will be shown to the user.

Windows

Windows is not supported at this time for barcode scanning. You can however use the barcode generation. No extra permissions are required for that. For more information on permissions, see the Microsoft Docs.

Using ZXing.Net.Maui

If you're using the controls from XAML, make sure to add the right XML namespace in the root of your file, e.g:

xmlns:zxing="clr-namespace:ZXing.Net.Maui.Controls;assembly=ZXing.Net.MAUI"
<zxing:CameraBarcodeReaderView
  x:Name="cameraBarcodeReaderView"
  BarcodesDetected="BarcodesDetected" />
Full Code of MainPage.xaml:

Configure Reader options

cameraBarcodeReaderView.Options = new BarcodeReaderOptions
{
  Formats = BarcodeFormats.OneDimensional,
  AutoRotate = true,
  Multiple = true
};

Toggle Torch

cameraBarcodeReaderView.IsTorchOn = !cameraBarcodeReaderView.IsTorchOn;

Flip between Rear/Front cameras

cameraBarcodeReaderView.CameraLocation
  = cameraBarcodeReaderView.CameraLocation == CameraLocation.Rear ? CameraLocation.Front : CameraLocation.Rear;

Handle detected barcode(s)

protected void BarcodesDetected(object sender, BarcodeDetectionEventArgs e)
{
  foreach (var barcode in e.Results)
    Console.WriteLine($"Barcodes: {barcode.Format} -> {barcode.Value}");
}
Full code of MainPage.xaml.cs

Demo

Full Code:

Download Code:

You can download the code from GitHub. If you have any doubts, feel free to post a comment. If you liked this article, and it is useful to you, do like, share the article & star the repository on GitHub.

Introduction:  In this article, we will see how to use Zxing Intent Integrator in Xamarin Android Applications. We have seen a lot o...

How to use Zxing Intent Integrator in Xamarin.Android How to use Zxing Intent Integrator in Xamarin.Android

A blog about android developement

ZXing

tite-banner

Introduction: 

In this article, we will see how to use Zxing Intent Integrator in Xamarin Android Applications. We have seen a lot of articles about how to integrate Zxing Plugin in Android & iOS Applications. But integration of Zxing Intent Integrator is available for Java Android Apps only. So, I have created a Xamarin Library for Xamarin.Android to Zxing Intent Integrator. 

Zxing Intent Integrator: 

This plugin is a port of official Zxing Intent Integrator and it is not just a binding project. I have converted the library code from java to C#. We will see, how to use the same in Coding Part. 

Coding Part: 

Steps: 

I have split this article into 3 steps as in the following. 
Step 1: Creating new Xamarin.Android Projects. 
Step 2: Setting up the plugin for Xamarin.Android Application. 
Step 3: Implementing Zxing Intent Integrator in Xamarin.Android Application.

Step 1: Creating new Xamarin.Android Projects

Create New Project by Selecting New -> Project -> Select Android App and Click OK.

new project

Step 2: Setting up the plugin for Xamarin.Android Application

In this step, we will include the Zxing plugin for Xamarin.Android Project. 
  1. You can download the plugin by clicking here.
  2. Right click on the reference and click add reference.
  3. Then click browse and go to the folder to choose the plugin you downloaded.
add reference 1

add reference 2

Step 3: Implementing Zxing Intent Integrator in Xamarin.Android Application 

  1. I have created a button and added click event.
  2. Then added OnActivityResult Override method as shown below. 
    protected override void OnActivityResult(int requestCode, [GeneratedEnum] Result resultCode, Intent data)
    {
    
     IntentResult result = IntentIntegrator.ParseActivityResult(requestCode, (int)resultCode, data);
     if (result != null)
     {
      if (result.Contents == null)
      {
       Log.Debug("MainActivity", "Cancelled scan");
       Toast.MakeText(this, "Cancelled", ToastLength.Long).Show();
      }
      else
      {
       Log.Debug("MainActivity", "Scanned");
       Toast.MakeText(this, "Scanned: " + result.Contents, ToastLength.Long).Show();
      }
     }
     else
     {
      base.OnActivityResult(requestCode, resultCode, data);
     }
    }
  3. Here we can handle the results returned from Zxing Scanner App.
  4. Then add the following lines in click event, which is help us to call the Zxing app to scan the barcodes.
    button.Click += (s, e) =>
    {
     IntentIntegrator intentIntegrator = new IntentIntegrator(this);
     intentIntegrator.InitiateScan();
    };
  5. The working principle is similar to the official Zxing Java Library.

Full Code

You can find full code here.
namespace ZxingSample
{
    [Activity(Label = "@string/app_name", Theme = "@style/AppTheme", MainLauncher = true)]
    public class MainActivity : AppCompatActivity
    {
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            LinearLayout ll = new LinearLayout(this);
            Button button = new Button(this);
            button.Text = "Click to Scan using Zxing";
            button.Click += (s, e) =>
            {
                IntentIntegrator intentIntegrator = new IntentIntegrator(this);
                intentIntegrator.InitiateScan();
            };
            LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(Android.Views.ViewGroup.LayoutParams.MatchParent,
                Android.Views.ViewGroup.LayoutParams.WrapContent);
            ll.AddView(button, lp);
            SetContentView(ll);
        }

        protected override void OnActivityResult(int requestCode, [GeneratedEnum] Result resultCode, Intent data)
        {

            IntentResult result = IntentIntegrator.ParseActivityResult(requestCode, (int)resultCode, data);
            if (result != null)
            {
                if (result.Contents == null)
                {
                    Log.Debug("MainActivity", "Cancelled scan");
                    Toast.MakeText(this, "Cancelled", ToastLength.Long).Show();
                }
                else
                {
                    Log.Debug("MainActivity", "Scanned");
                    Toast.MakeText(this, "Scanned: " + result.Contents, ToastLength.Long).Show();
                }
            }
            else
            {
                base.OnActivityResult(requestCode, resultCode, data);
            }
        }
    }
}

Demo

zxing app 1

zxing app 2

zxing app 3

zxing app 4

Download Code

You can download the full source code from GitHub. If you like the post, do like and share the article and star the repo on GitHub.