Reconocer códigos de barras en imágenes en la aplicación MAUI para Android
Categoría del blog: Barcode ; .NET ; Android
08.05.2024
						
						
					
						
						
<ItemGroup>
    <TrimmerRootAssembly Include="Vintasoft.Barcode" RootMode="library" />
    <TrimmerRootAssembly Include="Vintasoft.Shared" RootMode="library" />
    <TrimmerRootAssembly Include="Mono.Android" RootMode="library" />
</ItemGroup>
					
						
<?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="MauiApp1.MainPage">
    <ScrollView>
        <VerticalStackLayout Padding="30,0" Spacing="25">
            <Image x:Name="barcodeImage" HeightRequest="500" Aspect="AspectFit"/>
            <HorizontalStackLayout>
                <Button x:Name="openBarcodeButton" Text="Open Image..." Clicked="openBarcodeButton_Clicked" Margin="2"/>
                <Button x:Name="recognizeBarcodeButton" Text="Recognize Barcode" Clicked="recognizeBarcodeButton_Clicked" Margin="2"/>
            </HorizontalStackLayout>
        </VerticalStackLayout>
    </ScrollView>
</ContentPage>
					
						
// get the application name
string applicationName = Vintasoft.Barcode.BarcodeGlobalSettings.ApplicationName;
// if MAUI application is using in Android
if (applicationName.StartsWith("Android"))
{
    // register the evaluation license for VintaSoft Barcode .NET SDK
    Vintasoft.Barcode.BarcodeGlobalSettings.Register("LINUX_EVAL_USER", "LINUX_EVAL_USER_EMAIL", "LINUX_EVAL_END_DATE", "LINUX_EVAL_REG_CODE");
}
					
						
using Vintasoft.Barcode;
namespace MauiApp1
{
    public partial class MainPage : ContentPage
    {
        /// <summary>
        /// The current image stream.
        /// </summary>
        Stream _currentImageStream;
        public MainPage()
        {
            InitializeComponent();
        }
        private async void openBarcodeButton_Clicked(object sender, EventArgs e)
        {
            PickOptions options = new PickOptions();
            options.FileTypes = FilePickerFileType.Images;
            var result = await FilePicker.Default.PickAsync(options);
            if (result != null)
            {
                LoadImage(File.OpenRead(result.FullPath));
            }
        }
        private async void recognizeBarcodeButton_Clicked(object sender, EventArgs e)
        {
            try
            {
                recognizeBarcodeButton.IsEnabled = false;
                if (_currentImageStream == null)
                    throw new Exception("Barcode image is not loaded.");
                using (BarcodeReader reader = new BarcodeReader())
                {
                    reader.Settings.ScanBarcodeTypes = BarcodeType.DataMatrix;
                    reader.Settings.BarcodeCharacteristics = BarcodeCharacteristics.NormalSizeBarcodes;
                    _currentImageStream.Position = 0;
                    IBarcodeInfo[] infos = reader.ReadBarcodes(_currentImageStream);
                    if (infos.Length > 0)
                    {
                        IBarcodeInfo info = infos[0];
                        await DisplayAlert("Barcode Reader", $"Recognized '{info.BarcodeType}' barcode ({reader.RecognizeTime.TotalMilliseconds} ms):\n{info.Value}", "OK");
                    }
                    else
                    {
                        throw new Exception($"No barcodes found ({reader.RecognizeTime.TotalMilliseconds} ms).");
                    }
                }
            }
            catch (Exception ex)
            {
                await DisplayAlert("Barcode Reader Error", ex.Message, "OK");
            }
            finally
            {
                recognizeBarcodeButton.IsEnabled = true;
            }
        }
        /// <summary>
        /// Loads the image.
        /// </summary>
        /// <param name="stream">The image stream.</param>
        private async void LoadImage(Stream stream)
        {
            if (_currentImageStream != null)
                _currentImageStream.Dispose();
            _currentImageStream = stream;
            try
            {
                barcodeImage.Source = ImageSource.FromStream(() => CreateMemoryStream(_currentImageStream));
            }
            catch (Exception ex)
            {
                await DisplayAlert("Load Image Error", ex.Message, "OK");
            }
        }
        /// <summary>
        /// Creates the memory stream from specified stream.
        /// </summary>
        /// <param name="stream">The stream.</param>
        /// <returns></returns>
        private static MemoryStream CreateMemoryStream(Stream stream)
        {
            MemoryStream result = new MemoryStream((int)stream.Length);
            CopyStream(stream, result);
            result.Position = 0;
            return result;
        }
        /// <summary>
        /// Copies the stream.
        /// </summary>
        /// <param name="sourceStream">The source stream.</param>
        /// <param name="destStream">The dest stream.</param>
        private static void CopyStream(Stream sourceStream, Stream destStream)
        {
            int bufferLength = 32 * 1024;
            try
            {
                if (sourceStream.Length > 0 && sourceStream.Length < bufferLength)
                    bufferLength = (int)sourceStream.Length;
            }
            catch
            {
            }
            byte[] buffer = new byte[bufferLength];
            int bytesRead;
            while ((bytesRead = sourceStream.Read(buffer, 0, buffer.Length)) > 0)
            {
                destStream.Write(buffer, 0, bytesRead);
            }
        }
    }
}