使用 IRONBARCODE

如何在 .NET MAUI 應用程式中使用文件掃描 SDK

發佈 2024年4月29日
分享:

隨著移動技術的興起,像 Scanbot SDK 和 Native SDK 這樣的文件掃描應用程序已成為個人和企業不可或缺的工具或解決方案專家。在本教程中,我們將探討如何使用最新版本的 .NET 多平台應用 UI 創建文件掃描應用程序。 (MAUI) 和IronOCR,一個強大的OCR (光學字符識別) 適用於 .NET 的庫。.NET MAUI 簡化了跨平台移動應用程式(如 Android)的創建,確保在最終用戶設備上的無縫部署。通過本指南的學習,您將能夠開發自己的文件掃描 SDK 應用程式,輕鬆從圖像和掃描文件中提取文字。

如何在.NET MAUI應用程序中使用文檔掃描 SDK

  1. 安裝 IronOCR C# 庫以使用文檔掃描 SDK。

  2. 設計具有必要控件的 .NET MAUI 表單。

  3. 使用 MediaPicker.CapturePhotoAsync 方法捕獲照片畫面。

  4. 將捕獲的照片轉換為 Stream

  5. 將 Stream 傳遞給 OcrInput 的 LoadImage 方法。

  6. 使用 IronTesseract 的 Read 方法進行 OCR。

  7. 使用 OcrResult 的 Text 屬性顯示文檔文本。

IronOCR - C# OCR 庫

IronOCR 是先進的光學字符識別 (光學字符識別) 由Iron Software, LLC開發的軟體,旨在準確高效地將圖片和掃描文檔轉換為可編輯的文本。OCR(光學字符識別)技術已經革新了企業處理文檔的方式,使從掃描文檔、PDF檔和圖片中提取有價值的信息變得更加容易。

IronOCR在OCR解決方案中脫穎而出,因為它具有先進的功能、強大的性能和易於整合的特性。無論您是希望在應用程序中加入OCR功能的開發者,還是希望簡化數據生成管理流程的企業,IronOCR都能提供全面的解決方案。

IronOCR 的主要功能

以下是 IronOCR 的一些重要功能:

  1. 高精度: IronOCR 使用最先進的算法和機器學習技術,在文字識別方面達到極高的準確性。它可以準確地從複雜文檔中提取文字,包括低解析度和劣質掃描的圖像。

  2. 多語言支持: IronOCR 的一大亮點在於其廣泛的語言支持。它可以識別超過 127 種語言的文字,適合在多語言環境中運營的企業。

  3. 圖像預處理: 為了提高準確性,IronOCR 提供了各種圖像預處理功能,如去噪、對比度調整和去傾斜等。這些預處理技術有助於改善 OCR 結果,特別是在處理變形或不完美的圖像時。

  4. 支持多種文件格式: IronOCR 支持多種文件格式,包括 TIFF、JPEG、PNG 和 PDF。這種靈活性讓用戶能夠從不同來源處理文檔,而不用擔心兼容性問題。

  5. 自定義選項: 開發人員可以根據他們的具體需求自定義 IronOCR 的行為。無論是微調識別參數還是與現有工作流集成,IronOCR 都提供了高度的靈活性和可定制性。

  6. 快速且可擴展: IronOCR 經過性能優化,即使在大量文檔中也能快速提取文字。其可擴展的架構確保了無縫運行,無論是處理少量文檔還是處理大量文檔庫。

  7. 與 .NET 應用程序集成: IronOCR 無縫集成到 .NET 應用程序中,為開發人員提供簡單易用的 API 和庫,以便在他們的軟件項目中集成 OCR 功能。這種緊密集成簡化了開發過程,加快了具備 OCR 功能的應用上線時間。

  8. 文檔分類和數據提取: 除了基本的文字識別,IronOCR 還提供了文檔分類和數據提取的高級功能。它可以識別文檔中的特定數據字段,如姓名、地址或發票號碼,從而實現自動化數據提取和分析。

先決條件

  • 基本的 C# 程式設計知識。
  • 你的系統上已安裝最新版的 Visual Studio 2022 並具有 .NET MAUI 工作負載。
  • 通過 NuGet 套件管理器安裝 IronOCR 套件庫。

1. 設置您的 .NET MAUI 專案

  • 開啟 Visual Studio 2022 並建立一個新的 .NET MAUI 應用專案。

如何在.NET MAUI應用程序中使用文件掃描儀SDK:圖1 - .NET MAUI應用程序項目

  • 選擇合適的專案名稱並配置你的專案設置。

如何在 .NET MAUI 應用程式中使用文件掃描器 SDK:圖 2 - 專案配置

  • 確保您已安裝必要的 Android 和 iOS SDK 用於目標平台設備開發。

2. 安裝 IronOCR 庫

  • 在 Visual Studio 中右鍵點擊您的解決方案。

    • 選擇「為解決方案管理 NuGet 套件」,在「瀏覽」標籤中,搜尋「IronOCR」。

如何在.NET MAUI應用程式中使用文件掃描儀SDK:圖3 - IronOCR NuGet套件

  • 將 IronOCR 庫安裝到您的專案中。

3. 設計 UI

讓我們開始設計 MainPage.xaml 的佈局。我們將創建一個簡單的佈局,其中包含一個圖像控制項來顯示捕獲的照片,一個拍照按鈕來拍攝照片,還有一個標籤來顯示提取的文本。

以下是 MainPage.xaml 的 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"
             xmlns:d="http://schemas.microsoft.com/dotnet/2021/maui/design"
             x:Class="DocumentScanner.MainPage">
    <ScrollView>
        <VerticalStackLayout
            Padding="30,0"
            Spacing="25">
            <Image
                Source="dotnet_bot.png"
                HeightRequest="185"
                Aspect="AspectFit"
                SemanticProperties.Description="dot net bot in a race car number eight" />
            <Label
                Text="Welcome to .NET MAUI Document Scanner SDK"
                Style="{StaticResource Headline}"
                SemanticProperties.HeadingLevel="Level1" />
            <Label
                Text="Using IronOCR"
                Style="{StaticResource SubHeadline}"
                SemanticProperties.HeadingLevel="Level2"
                SemanticProperties.Description="Welcome to .NET MAUI Document Scanner SDK" />
            <!-- Camera preview -->
            <Image x:Name="cameraPreview" />
            <!-- Capture button -->
            <Button Text="Capture" Clicked="OnCaptureClicked" />
            <!-- Text display area -->
            <Label x:Name="textLabel"
                   Text="Recognized Text:"/>
        </VerticalStackLayout>
    </ScrollView>
</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"
             xmlns:d="http://schemas.microsoft.com/dotnet/2021/maui/design"
             x:Class="DocumentScanner.MainPage">
    <ScrollView>
        <VerticalStackLayout
            Padding="30,0"
            Spacing="25">
            <Image
                Source="dotnet_bot.png"
                HeightRequest="185"
                Aspect="AspectFit"
                SemanticProperties.Description="dot net bot in a race car number eight" />
            <Label
                Text="Welcome to .NET MAUI Document Scanner SDK"
                Style="{StaticResource Headline}"
                SemanticProperties.HeadingLevel="Level1" />
            <Label
                Text="Using IronOCR"
                Style="{StaticResource SubHeadline}"
                SemanticProperties.HeadingLevel="Level2"
                SemanticProperties.Description="Welcome to .NET MAUI Document Scanner SDK" />
            <!-- Camera preview -->
            <Image x:Name="cameraPreview" />
            <!-- Capture button -->
            <Button Text="Capture" Clicked="OnCaptureClicked" />
            <!-- Text display area -->
            <Label x:Name="textLabel"
                   Text="Recognized Text:"/>
        </VerticalStackLayout>
    </ScrollView>
</ContentPage>
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'<?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" xmlns:d="http://schemas.microsoft.com/dotnet/2021/maui/design" x:@Class="DocumentScanner.MainPage"> <ScrollView> <VerticalStackLayout Padding="30,0" Spacing="25"> <Image Source="dotnet_bot.png" HeightRequest="185" Aspect="AspectFit" SemanticProperties.Description="dot net bot in a race car number eight" /> <Label Text="Welcome to .NET MAUI Document Scanner SDK" Style="{StaticResource Headline}" SemanticProperties.HeadingLevel="Level1" /> <Label Text="Using IronOCR" Style="{StaticResource SubHeadline}" SemanticProperties.HeadingLevel="Level2" SemanticProperties.Description="Welcome to .NET MAUI Document Scanner SDK" /> <!-- Camera preview -- > <Image x:Name="cameraPreview" /> <!-- Capture button -- > <Button Text="Capture" Clicked="OnCaptureClicked" /> <!-- Text display area -- > <Label x:Name="textLabel" Text="Recognized Text:"/> </VerticalStackLayout> </ScrollView> </ContentPage>
VB   C#

在此佈局中:

  • 我們使用 VerticalStackLayout 垂直堆疊控制項。
  • 名為 capturedImageImage 控制項用於顯示拍攝的照片。
  • Button 控制項在點擊時觸發 OnCaptureClicked 事件處理程序。
  • 名為 textLabelLabel 控制項用於顯示提取的文本。

輸出

如何在 .NET MAUI 應用程式中使用文件掃描器 SDK:圖 4 - MainPage.xaml 輸出

4. 實現文件掃描功能

要將文字提取功能整合到我們的 .NET MAUI 文件掃描應用程式中,我們將遵循以下步驟:

  1. 使用相機 API:首先利用 .NET MAUI 提供的相機 API 在您的應用程式內直接捕獲圖像文件。

  2. 將圖像傳遞給 IronOCR:圖像捕獲後,將其傳遞給 IronOCR,一個強大的 OCR 庫,用於文字提取。IronOCR 提供可靠的功能,能夠高精確度地從圖像中提取文字。

  3. 顯示提取的文字:最後,在應用程式的用戶界面指定區域顯示提取的文字。這使用戶可以輕鬆查看從捕獲圖像或 QR 碼中提取的文字。

以下是實施這些步驟的相應代碼片段:

using IronOcr;
namespace DocumentScanner
{
    public partial class MainPage : ContentPage
    {
        public MainPage()
        {
            InitializeComponent();
        }
        private async void OnCaptureClicked(object sender, EventArgs e)
        {
            License.LicenseKey = "YOUR-LICENSE-KEY-HERE";
            try
            {
                // Request camera permissions
                var status = await Permissions.RequestAsync<Permissions.Camera>();
                if (status == PermissionStatus.Granted)
                {
                    // Take photo
                    var photo = await MediaPicker.CapturePhotoAsync();
                    if (photo != null)
                    {
                        // Display captured photo in Image
                        cameraPreview.Source = ImageSource.FromStream(() => photo.OpenReadAsync().Result);
                        using (var stream = await photo.OpenReadAsync())
                        {
                            // Use a stream from the captured photo for OCR
                            var ocr = new IronTesseract();
                            using var ocrInput = new OcrInput();
                            ocrInput.LoadImage(stream);
                            var ocrResult = ocr.Read(ocrInput);
                            if (string.IsNullOrEmpty(ocrResult.Text))
                            {
                                await DisplayAlert("Error", "No Text Detected!", "OK");
                            }
                            else
                            {
                                await DisplayAlert("Text Detected!", ocrResult.Text, "OK");
                                // Display extracted text
                                textLabel.Text = ocrResult.Text;
                            }
                        }
                    }
                }
                else
                {
                    // Camera permission denied
                    await DisplayAlert("Permission Denied", "Camera permission is required to capture photos.", "OK");
                }
            }
            catch (Exception ex)
            {
                // Handle exception
                await DisplayAlert("Error", ex.Message, "OK");
            }
        }
    }
}
using IronOcr;
namespace DocumentScanner
{
    public partial class MainPage : ContentPage
    {
        public MainPage()
        {
            InitializeComponent();
        }
        private async void OnCaptureClicked(object sender, EventArgs e)
        {
            License.LicenseKey = "YOUR-LICENSE-KEY-HERE";
            try
            {
                // Request camera permissions
                var status = await Permissions.RequestAsync<Permissions.Camera>();
                if (status == PermissionStatus.Granted)
                {
                    // Take photo
                    var photo = await MediaPicker.CapturePhotoAsync();
                    if (photo != null)
                    {
                        // Display captured photo in Image
                        cameraPreview.Source = ImageSource.FromStream(() => photo.OpenReadAsync().Result);
                        using (var stream = await photo.OpenReadAsync())
                        {
                            // Use a stream from the captured photo for OCR
                            var ocr = new IronTesseract();
                            using var ocrInput = new OcrInput();
                            ocrInput.LoadImage(stream);
                            var ocrResult = ocr.Read(ocrInput);
                            if (string.IsNullOrEmpty(ocrResult.Text))
                            {
                                await DisplayAlert("Error", "No Text Detected!", "OK");
                            }
                            else
                            {
                                await DisplayAlert("Text Detected!", ocrResult.Text, "OK");
                                // Display extracted text
                                textLabel.Text = ocrResult.Text;
                            }
                        }
                    }
                }
                else
                {
                    // Camera permission denied
                    await DisplayAlert("Permission Denied", "Camera permission is required to capture photos.", "OK");
                }
            }
            catch (Exception ex)
            {
                // Handle exception
                await DisplayAlert("Error", ex.Message, "OK");
            }
        }
    }
}
Imports IronOcr
Namespace DocumentScanner
	Partial Public Class MainPage
		Inherits ContentPage

		Public Sub New()
			InitializeComponent()
		End Sub
		Private Async Sub OnCaptureClicked(ByVal sender As Object, ByVal e As EventArgs)
			License.LicenseKey = "YOUR-LICENSE-KEY-HERE"
			Try
				' Request camera permissions
				Dim status = Await Permissions.RequestAsync(Of Permissions.Camera)()
				If status = PermissionStatus.Granted Then
					' Take photo
					Dim photo = Await MediaPicker.CapturePhotoAsync()
					If photo IsNot Nothing Then
						' Display captured photo in Image
						cameraPreview.Source = ImageSource.FromStream(Function() photo.OpenReadAsync().Result)
						Using stream = Await photo.OpenReadAsync()
							' Use a stream from the captured photo for OCR
							Dim ocr = New IronTesseract()
							Dim ocrInput As New OcrInput()
							ocrInput.LoadImage(stream)
							Dim ocrResult = ocr.Read(ocrInput)
							If String.IsNullOrEmpty(ocrResult.Text) Then
								Await DisplayAlert("Error", "No Text Detected!", "OK")
							Else
								Await DisplayAlert("Text Detected!", ocrResult.Text, "OK")
								' Display extracted text
								textLabel.Text = ocrResult.Text
							End If
						End Using
					End If
				Else
					' Camera permission denied
					Await DisplayAlert("Permission Denied", "Camera permission is required to capture photos.", "OK")
				End If
			Catch ex As Exception
				' Handle exception
				Await DisplayAlert("Error", ex.Message, "OK")
			End Try
		End Sub
	End Class
End Namespace
VB   C#

代碼解釋

讓我們一步一步地分解代碼:

  • 在 MainPage.xaml.cs 文件中,我們定義了 OnCaptureClicked 方法,當用戶點擊捕捉按鈕時將會觸發。
  • OnCaptureClicked 方法內,我們首先設置 IronOCR 授權密鑰。這是使用 IronOCR 庫所必需的。將 "YOUR-LICENSE-KEY-HERE" 替換為您的實際授權密鑰。
  • 然後,我們使用 Permissions.RequestAsync請求相機許可權。()這將確保應用程式具備存取裝置相機的必要許可。

我們使用 MediaPicker.CapturePhotoAsync()使用設備的相機拍照。如果成功拍攝照片,我們將其顯示在名為cameraPreviewImage控制項中。**

  • 我們從拍攝的照片中打開一個流並將其作為OCR的輸入使用 IronOCR。我們創建一個IronTesseract的實例,將圖像流加載到OcrInput對象中,然後調用Read方法執行OCR。
  • 如果成功提取到文本,我們將其顯示在名為textLabelLabel控制項中。如果未檢測到文本,我們使用DisplayAlert顯示錯誤消息。

如需更全面地使用 IronOCR 和代碼詳情,請訪問此 代碼範例 頁面。

5. 測試文件掃描應用程式

  • 在各種平台上運行應用程式 (Android、iOS 和 Windows) 確保跨平台相容性。
  • 測試不同的情境,例如掃描具有不同字體、大小和方向的文件。
  • 驗證提取的文本是否準確並在UI上正確顯示。

輸出 - 無文字的掃描文件

如何在 .NET MAUI 應用程式中使用文件掃描 SDK:圖 5 - 掃描 PDF 創建輸出

輸出 - 掃描文件帶有文本

如何在 .NET MAUI 應用程式中使用文件掃描SDK:圖 6 - 掃描文件

結論

通過學習本教程,你已經學會了如何在.NET MAUI中使用IronOCR文件掃描器SDK。文件掃描應用程式有許多實踐應用,從數位化紙張文件到從收據和發票中提取存儲的信息。借助IronOCR的強大功能和.NET MAUI的靈活性,你可以構建功能豐富的文件掃描應用程式,以滿足各種使用需求。嘗試不同的功能,探索其他庫,繼續磨練你的技能,以創建更令人印象深刻的應用程式。

有關IronOCR功能的更多詳細信息,請訪問此 文檔 頁面。

IronOCR 提供一個 免費試用 以商業模式測試其完整功能。其永久 Lite 授權 起價 $749。從 下載該庫 下載 頁面並嘗試一下。

< 上一頁
製作網頁應用程式的條碼掃描器 API 的步驟
下一個 >
創建一個Razor條碼生成器的網頁應用程序

準備開始了嗎? 版本: 2024.10 剛剛發布

免費 NuGet 下載 總下載次數: 1,203,227 查看許可證 >