如何從 System Drawing 物件讀取條碼

How to Read Barcodes From System.Drawing in C

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

IronBarcode通過自動將System.Drawing限制。

介紹

System.Drawing物件在.NET中廣泛用於圖像處理任務。 然而,Microsoft已經停止支持System.DrawingMacOSLinux上,現在僅支持Windows。 此更改為在非Windows操作系統上使用IronBarcode的開發人員帶來了問題,因為處理條碼通常涉及圖像圖片字體

為了解決此問題,我們介紹了IronDrawing。 這個由Iron Software建立的免費開源程式庫簡化了跨平台支持並提供了無縫的體驗。 當您從NuGet安裝IronBarcode時,IronDrawing會自動包含在您的專案中。

對於條碼閱讀新手,請參閱我們全面的條碼閱讀教程,涵蓋基本概念和基本使用模式。 如果您正在處理各種圖像格式,我們的從圖像讀取條碼指南提供了更多背景和範例。

快速入門:使用AnyBitmap在一行簡單的程式碼中讀取條碼

這段程式碼展示了IronBarcode是如何讀取條碼的,通過建立AnyBitmap。 只用一行程式碼,任何操作系統上的開發者都可以獲得快速結果。

  1. 使用NuGet套件管理器安裝https://www.nuget.org/packages/BarCode

    PM > Install-Package BarCode
  2. 複製並運行這段程式碼片段。

    var results = IronBarCode.BarcodeReader.Read((AnyBitmap)(new System.Drawing.Bitmap("yourImage.png")));
  3. 部署以在您的實時環境中測試

    今天就開始在您的專案中使用IronBarcode,透過免費試用

    arrow pointer

如何將AnyBitmap

AnyBitmapAnyBitmap

除了System.Drawing物件,我們還支持從其他型別轉換:

  • System.Drawing.Bitmap
  • System.Drawing.Image
  • SkiaSharp.SKBitmap
  • SkiaSharp.SKImage
  • SixLabors.ImageSharp

參閱此程式碼範例以轉換上述物件。 以下演示將條碼圖像從IronSoftware.Drawing.AnyBitmap

哪些System.Drawing型別可以轉換?

:path=/static-assets/barcode/content-code-examples/how-to/read-barcodes-from-system-drawing-cast-to-anybitmap.cs
using IronSoftware.Drawing;
using System.Collections.Generic;

List<AnyBitmap> barcodes = new List<AnyBitmap>();

// Instantiate System.Drawing.Bitmap
System.Drawing.Bitmap bitmapFromBitmap = new System.Drawing.Bitmap("test1.jpg");

// Cast from System.Drawing.Bitmap to AnyBitmap
AnyBitmap barcode1 = bitmapFromBitmap;

barcodes.Add(barcode1);

// Instantiate System.Drawing.Bitmap
System.Drawing.Image bitmapFromFile = System.Drawing.Image.FromFile("test2.png");

// Cast from System.Drawing.Image to AnyBitmap
AnyBitmap barcode2 = bitmapFromFile;

barcodes.Add(barcode2);
Imports IronSoftware.Drawing
Imports System.Collections.Generic

Private barcodes As New List(Of AnyBitmap)()

' Instantiate System.Drawing.Bitmap
Private bitmapFromBitmap As New System.Drawing.Bitmap("test1.jpg")

' Cast from System.Drawing.Bitmap to AnyBitmap
Private barcode1 As AnyBitmap = bitmapFromBitmap

barcodes.Add(barcode1)

' Instantiate System.Drawing.Bitmap
Dim bitmapFromFile As System.Drawing.Image = System.Drawing.Image.FromFile("test2.png")

' Cast from System.Drawing.Image to AnyBitmap
Dim barcode2 As AnyBitmap = bitmapFromFile

barcodes.Add(barcode2)
$vbLabelText   $csharpLabel

此程式碼展示了IronDrawing。 這種相容性遍及多種條碼格式,詳細資訊見我們的支持的條碼格式指南,包括QR碼、Code 128、Code 39等多種格式。

為什麼隱式轉換能工作?

在上面的程式碼中,我們載入了兩個條碼圖像作為System.Drawing.Image。 然後我們將它們隱式轉換為AnyBitmap列表中。

AnyBitmap之間的透明轉換。 這種設計模式讓開發者在獲得跨平台相容性的同時維護現有程式碼。 轉換保留了所有圖像屬性,包括解析度、色深和像素資料,確保沒有質量損失。

何時應使用顯式轉換與隱式轉換?

雖然隱式轉換提供了便利,但在某些情況下顯式轉換可能更合適:

// Implicit casting - clean and simple for straightforward conversions
System.Drawing.Bitmap systemBitmap = new System.Drawing.Bitmap("barcode.png");
AnyBitmap anyBitmap = systemBitmap; // Implicit cast

// Explicit casting - useful when type clarity is important
System.Drawing.Image systemImage = System.Drawing.Image.FromFile("qrcode.jpg");
AnyBitmap explicitBitmap = (AnyBitmap)systemImage; // Explicit cast

// When working with nullable types or conditional logic
System.Drawing.Bitmap? nullableBitmap = GetBitmapFromSource();
if (nullableBitmap != null)
{
    AnyBitmap result = (AnyBitmap)nullableBitmap; // Explicit cast for clarity
    // Process the barcode
}
// Implicit casting - clean and simple for straightforward conversions
System.Drawing.Bitmap systemBitmap = new System.Drawing.Bitmap("barcode.png");
AnyBitmap anyBitmap = systemBitmap; // Implicit cast

// Explicit casting - useful when type clarity is important
System.Drawing.Image systemImage = System.Drawing.Image.FromFile("qrcode.jpg");
AnyBitmap explicitBitmap = (AnyBitmap)systemImage; // Explicit cast

// When working with nullable types or conditional logic
System.Drawing.Bitmap? nullableBitmap = GetBitmapFromSource();
if (nullableBitmap != null)
{
    AnyBitmap result = (AnyBitmap)nullableBitmap; // Explicit cast for clarity
    // Process the barcode
}
Imports System.Drawing

' Implicit casting - clean and simple for straightforward conversions
Dim systemBitmap As New Bitmap("barcode.png")
Dim anyBitmap As AnyBitmap = systemBitmap ' Implicit cast

' Explicit casting - useful when type clarity is important
Dim systemImage As Image = Image.FromFile("qrcode.jpg")
Dim explicitBitmap As AnyBitmap = CType(systemImage, AnyBitmap) ' Explicit cast

' When working with nullable types or conditional logic
Dim nullableBitmap As Bitmap = GetBitmapFromSource()
If nullableBitmap IsNot Nothing Then
    Dim result As AnyBitmap = CType(nullableBitmap, AnyBitmap) ' Explicit cast for clarity
    ' Process the barcode
End If
$vbLabelText   $csharpLabel

常見的轉換錯誤有哪些?

當從AnyBitmap時,開發者可能遇到:

  1. 空引用異常: 在轉換之前核實您的System.Drawing物件非空
  2. 格式不支持異常: 有些特殊圖像格式需要預先轉換
  3. 記憶體問題: 大圖像需要適當的處置模式

針對轉換問題疑難排解,我們的疑難排解指南提供了在條碼識別過程中常見問題的解決方案。

如何從AnyBitmap物件中讀取條碼?

IronBarcode在所有方法中接受IronSoftware.Drawing.AnyBitmap物件,無需其他配置。 在非Windows操作系統上使用System.Drawing物件時,這簡化了開發。 下面的程式碼演示了這一點:

哪些方法接受AnyBitmap參數?

:path=/static-assets/barcode/content-code-examples/how-to/read-barcodes-from-system-drawing-read-anybitmap.cs
using IronBarCode;
using IronSoftware.Drawing;
using System;
using System.Collections.Generic;

// Create a list of image file paths to read barcodes from
List<string> barcodeFiles = new List<string>
{
    "test1.jpg",
    "test2.png"
};

foreach (var barcodeFile in barcodeFiles)
{
    // Read the barcode from file path
    var results = BarcodeReader.Read(barcodeFile);
    foreach (var result in results)
    {
        // Output the detected barcode value
        Console.WriteLine(result.Value);
    }
}
Imports IronBarCode
Imports IronSoftware.Drawing
Imports System
Imports System.Collections.Generic

' Create a list of image file paths to read barcodes from
Dim barcodeFiles As New List(Of String) From {
    "test1.jpg",
    "test2.png"
}

For Each barcodeFile In barcodeFiles
    ' Read the barcode from file path
    Dim results = BarcodeReader.Read(barcodeFile)
    For Each result In results
        ' Output the detected barcode value
        Console.WriteLine(result.Value)
    Next
Next
$vbLabelText   $csharpLabel

除了基本的AnyBitmap參數的方法。 對於高級場景,請參閱我們的讀取多條碼指南,演示如何有效地處理單一圖像中的多個條碼:

:path=/static-assets/barcode/content-code-examples/how-to/read-barcodes-from-system-drawing-5.cs
// Advanced barcode reading with options
var readerOptions = new BarcodeReaderOptions
{
    // Specify barcode types to search for
    ExpectBarcodeTypes = BarcodeEncoding.QRCode | BarcodeEncoding.Code128,
    // Set confidence threshold
    ConfidenceThreshold = 0.95
};

// Read with specific options
var advancedResults = BarcodeReader.Read(anyBitmap, readerOptions);
Imports System

' Advanced barcode reading with options
Dim readerOptions As New BarcodeReaderOptions With {
    ' Specify barcode types to search for
    .ExpectBarcodeTypes = BarcodeEncoding.QRCode Or BarcodeEncoding.Code128,
    ' Set confidence threshold
    .ConfidenceThreshold = 0.95
}

' Read with specific options
Dim advancedResults = BarcodeReader.Read(anyBitmap, readerOptions)
$vbLabelText   $csharpLabel

我如何處理多個條碼結果?

上面的程式碼擴展了前面的範例。 在填充IronBarCode.BarcodeResults。 然後我們遍歷結果以將條碼值列印到控制台。

當處理多個條碼時,利用並行處理以獲得更好的性能:

:path=/static-assets/barcode/content-code-examples/how-to/read-barcodes-from-system-drawing-6.cs
// Parallel processing for multiple barcode images
var barcodeFiles = Directory.GetFiles("barcodes/", "*.png");
var allResults = new ConcurrentBag<BarcodeResult>();

Parallel.ForEach(barcodeFiles, file =>
{
    var bitmap = new System.Drawing.Bitmap(file);
    var anyBitmap = (AnyBitmap)bitmap;
    var results = BarcodeReader.Read(anyBitmap);
    
    foreach (var result in results)
    {
        allResults.Add(result);
    }
    
    bitmap.Dispose(); // Clean up resources
});

// Process all results
foreach (var result in allResults)
{
    Console.WriteLine($"Found {result.BarcodeType}: {result.Value}");
}
Imports System.IO
Imports System.Collections.Concurrent
Imports System.Drawing
Imports System.Threading.Tasks

' Parallel processing for multiple barcode images
Dim barcodeFiles = Directory.GetFiles("barcodes/", "*.png")
Dim allResults As New ConcurrentBag(Of BarcodeResult)()

Parallel.ForEach(barcodeFiles, Sub(file)
    Dim bitmap As New Bitmap(file)
    Dim anyBitmap As AnyBitmap = CType(bitmap, AnyBitmap)
    Dim results = BarcodeReader.Read(anyBitmap)

    For Each result In results
        allResults.Add(result)
    Next

    bitmap.Dispose() ' Clean up resources
End Sub)

' Process all results
For Each result In allResults
    Console.WriteLine($"Found {result.BarcodeType}: {result.Value}")
Next
$vbLabelText   $csharpLabel

我還可以使用哪些其他IronDrawing功能?

IronSoftware.Drawing功能不僅限於轉換圖像。 它處理圖像處理方面,如顏色字體,對條碼和QR碼樣式很有用。 探索我們如何利用IronDrawing自訂和新增徽標到QR碼上

IronDrawing提供強大的圖像處理能力,輔佐條碼處理:

:path=/static-assets/barcode/content-code-examples/how-to/read-barcodes-from-system-drawing-7.cs
// Using IronDrawing for image preprocessing
using IronSoftware.Drawing;

// Load and preprocess an image before barcode reading
AnyBitmap preprocessedImage = AnyBitmap.FromFile("noisy-barcode.jpg");

// Apply image filters to improve barcode readability
preprocessedImage = preprocessedImage.ToGrayScale();
preprocessedImage = preprocessedImage.Contrast(1.5); // Increase contrast
preprocessedImage = preprocessedImage.Sharpen(); // Sharpen image

// Read the preprocessed barcode
var improvedResults = BarcodeReader.Read(preprocessedImage);
Imports IronSoftware.Drawing

' Load and preprocess an image before barcode reading
Dim preprocessedImage As AnyBitmap = AnyBitmap.FromFile("noisy-barcode.jpg")

' Apply image filters to improve barcode readability
preprocessedImage = preprocessedImage.ToGrayScale()
preprocessedImage = preprocessedImage.Contrast(1.5) ' Increase contrast
preprocessedImage = preprocessedImage.Sharpen() ' Sharpen image

' Read the preprocessed barcode
Dim improvedResults = BarcodeReader.Read(preprocessedImage)
$vbLabelText   $csharpLabel

對於需要特定圖像校正的場景,我們的圖像校正指南詳細說明使用過濾器增強條碼可讀性。

為什麼要選擇System.Drawing

System.Drawing更具吸引力的優勢:

  1. 跨平台支持: 無縫運行在Windows、Linux和macOS上,而System.Drawing在.NET Core/5+中則僅支持Windows
  2. 現代架構:基於ImageSharp構建,提高了性能和記憶體管理
  3. 簡化的API: 保持熟悉的System.Drawing類似介面,並新增了現代便利功能
  4. 積極開發: 定期更新和改進,而System.Drawing處於維護模式
  5. 更好的整合: 專為Iron Software產品的最佳性能而設計

針對部署考量,特別是針對雲環境的部署,請參閱我們的Azure部署指南AWS部署指南,其中包括使用IronDrawing跨平台相容性的特定註釋。

無論是構建桌面應用程式、網路服務還是雲原生解決方案,IronDrawing能確保您的條碼處理程式碼在所有平台上保持便攜和高效,成為現代.NET開發的不二之選。

常見問題

如何在非 Windows 平台上從 System.Drawing 物件讀取條碼?

IronBarcode 自動通過 IronDrawing 從 System.Drawing 物件中跨平台讀取條碼,將其轉換為 AnyBitmap 格式。這解決了 Microsoft 將 System.Drawing 限制為僅限於 Windows 的問題,使您能夠在 MacOS 和 Linux 系統上無縫讀取條碼。

什麼是 IronDrawing,為什麼它與條碼讀取一起使用?

IronDrawing 是由 Iron Software 建立的免費開源程式庫,提供跨平台支援的圖形操作功能。當您從 NuGet 安裝 IronBarcode 時,它會自動包含,並透過將 System.Drawing 物件轉換成相容的 AnyBitmap 格式,讓所有作業系統上的條碼讀取變得可能。

如何將 System.Drawing.Bitmap 轉換來讀取條碼?

您可以通過簡單的轉型為 AnyBitmap 從 System.Drawing.Bitmap 中讀取條碼:`var results = BarcodeReader.Read((AnyBitmap)(new System.Drawing.Bitmap("yourImage.png")));`。IronBarcode 通過 IronDrawing 的隱式轉型功能自動處理轉換。

可以在 Linux 和 MacOS 上使用 System.Drawing 來讀取條碼嗎?

是的,IronBarcode 讓從 Linux 和 MacOS 上的 System.Drawing 物件讀取條碼成為可能,通過 IronDrawing 自動將 System.Drawing 物件轉換成跨平台的 AnyBitmap 格式。這克服了 Microsoft 對 System.Drawing 對 Windows 獨有支持的限制。

有哪些型別的 System.Drawing 物件可以用於條碼讀取?

IronBarcode 支援從各種 System.Drawing 物件中讀取條碼,包括 System.Drawing.Bitmap 和其他圖像型別。這些都會透過 IronDrawing 的隱式轉型功能自動轉換成 AnyBitmap,啟用跨平台的條碼掃描功能。

是否有簡單的單行解決方案可從 System.Drawing 讀取條碼?

是的,IronBarcode 提供了一個單行解決方案:`var results = BarcodeReader.Read((AnyBitmap)(new System.Drawing.Bitmap("yourImage.png")));`。這一行程式碼建立了一個 System.Drawing.Bitmap,透過 IronDrawing 將其轉型為 AnyBitmap,並讀取圖像中所有條碼。

IronBarcode是否提供自定義條碼外觀的支持?

是的,IronBarcode提供了廣泛的條碼外觀自定義選項,包括顏色、大小和文字註釋,讓您可以根據具體設計需求定制條碼。

IronBarcode如何幫助改善業務流程效率?

IronBarcode通過使條碼生成和讀取快速且準確來提高業務流程效率,減少手動資料輸入錯誤,並改善庫存和資產追蹤。

將IronBarcode實現於專案中需要什麼程式設計技能?

基本的C#程式設計知識足以將IronBarcode實現於專案中,因為它提供了簡單的方法和全面的文件來指導開發者。

IronBarcode適合於小型專案和大型企業應用嗎?

IronBarcode設計為可擴展且多功能,使其適合小型專案和需要強大條碼解決方案的大型企業應用。

Hairil Hasyimi Bin Omar
軟體工程師
和所有偉大的工程師一樣,Hairil是一位充滿熱情的學習者。他正在完善自己對C#、Python和Java的知識,並利用這些知識為Iron Software的團隊成員創造價值。Hairil從馬來西亞的瑪拉工藝大學畢業,擁有化學與流程工程學士學位,後加入Iron Software團隊。
準備好開始了嗎?
Nuget 下載 2,317,217 | 版本: 2026.7 剛剛發布
Still Scrolling Icon

還在滾動嗎?

想快速驗證嗎? PM > Install-Package BarCode
運行範例觀看您的字串成為條碼。