跳過到頁腳內容
使用IRONBARCODE

如何在ASP.NET應用程式中掃描條碼

條碼掃描已成為現代 Web 應用程序中不可或缺的功能,從庫存管理系統到文檔處理工作流程都依賴它。 無論您是在倉庫中跟踪產品、在活動中處理票務,還是將紙質文檔數字化,在您的 ASP.NET Web 應用程序中實現可靠的條碼掃描都可以顯著提高效率並減少錯誤。

IronBarcode emerges as the premier C# barcode reader library for ASP.NET and web developers, offering a powerful yet straightforward solution for both reading and generating barcodes. 與其他要求複雜配置或在處理真實圖像時苦苦掙扎的 ASP .NET 條碼掃描庫不同,IronBarcode 提供準確的條碼掃描結果,可靠而自信。 它的跨平台兼容性確保您的 Web 應用程序無縫運行,無論是部署在 Windows、Linux 還是雲容器中,其機器學習驅動的條碼檢測功能都可以通過將其轉換為機器可讀格式來有信心地處理最具挑戰性的條碼圖像。

如何在 ASP.NET 中將 IronBarcode 設置為條碼閱讀器?

在您的 .NET 項目中使用 IronBarcode 只需幾分鐘即可開始。 該庫支持 ASP.NET Core 和傳統 ASP.NET MVC 應用程序,適合各種類型的項目。

首先,使用 NuGet 包管理器控制台安裝 IronBarcode:

Install-Package BarCode

或者,您可以通過 Visual Studio 的 NuGet 包管理器界面安裝,搜索"IronBarCode"並點擊安裝。 該包會自動管理所有依賴項,確保順利集成。 有關詳細的安裝指南,請查看 IronBarcode 安裝指南

安裝完成後,將必要的 using 聲明添加到您的 C# 條碼閱讀文件中:

using IronBarCode;
using IronBarCode;
Imports IronBarCode
$vbLabelText   $csharpLabel

這個簡單的導入為您提供了訪問 IronBarcode 的全面條碼閱讀和生成功能的權限。 該庫支持超過 30 種條碼格式,包括 QR Code 生成、Code 128、Code 39、Data Matrix 和 PDF417,幾乎涵蓋了您在生產環境中會遇到的所有條碼類型。 根據 Microsoft 關於 ASP.NET 的文檔,正確的包管理對於維護安全和高效的 Web 應用程序至關重要。

如何實現文件上傳條碼掃描?

ASP.NET Web 應用中最常見的條碼掃描場景包括用戶在 Web 瀏覽器中上傳包含條碼的圖像文件。 此實現非常適合處理發票、運單或任何帶有內嵌條碼的文檔。

在 ASP.NET 視圖中使用div元素創建一個簡單的 HTML 表單:

<form method="post" enctype="multipart/form-data">
    <div class="form-group">
        <label for="barcodeFile">Select Barcode Image:</label>
        <input type="file" name="barcodeFile" id="barcodeFile" 
               accept="image/*,.pdf" class="form-control" />
    </div>
    <button type="submit" class="btn btn-primary">Scan Barcode</button>
</form>
<div id="results">
    @ViewBag.BarcodeResult
</div>
<form method="post" enctype="multipart/form-data">
    <div class="form-group">
        <label for="barcodeFile">Select Barcode Image:</label>
        <input type="file" name="barcodeFile" id="barcodeFile" 
               accept="image/*,.pdf" class="form-control" />
    </div>
    <button type="submit" class="btn btn-primary">Scan Barcode</button>
</form>
<div id="results">
    @ViewBag.BarcodeResult
</div>
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

現在實施後端控制器以使用您的 ASP.NET 條碼閱讀器處理上傳的文件:

[HttpPost]
public async Task<IActionResult> ScanBarcode(IFormFile barcodeFile)
{
    if (barcodeFile != null && barcodeFile.Length > 0)
    {
        using (var stream = new MemoryStream())
        {
            await barcodeFile.CopyToAsync(stream);
            stream.Position = 0;
            // Read barcode from the uploaded image
            var results = BarcodeReader.Read(stream);
            if (results.Any())
            {
                ViewBag.BarcodeResult = string.Join(", ", 
                    results.Select(r => $"{r.BarcodeType}: {r.Text}"));
            }
            else
            {
                ViewBag.BarcodeResult = "No barcodes found in the image.";
            }
        }
    }
    return View();
}
[HttpPost]
public async Task<IActionResult> ScanBarcode(IFormFile barcodeFile)
{
    if (barcodeFile != null && barcodeFile.Length > 0)
    {
        using (var stream = new MemoryStream())
        {
            await barcodeFile.CopyToAsync(stream);
            stream.Position = 0;
            // Read barcode from the uploaded image
            var results = BarcodeReader.Read(stream);
            if (results.Any())
            {
                ViewBag.BarcodeResult = string.Join(", ", 
                    results.Select(r => $"{r.BarcodeType}: {r.Text}"));
            }
            else
            {
                ViewBag.BarcodeResult = "No barcodes found in the image.";
            }
        }
    }
    return View();
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

此實現處理上傳的文件,將其複製到內存流,然後使用 IronBarcode 的 BarcodeReader.Read 方法從圖像中提取所有條碼。 該方法自動檢測條碼格式,並返回詳細結果,包括條碼類型和解碼文本。 IronBarcode processes various image formats, including JPEG, PNG, GIF, TIFF, BMP, and even PDF documents, eliminating the need for format-specific handling code. 這種多功能性使其非常適合在 Stack Overflow 的條碼實現討論帖子中探討的文檔處理場景。

示例圖像

如何在 ASP.NET 應用程序中掃描條碼:圖8-準備掃描的 Code128 條碼

輸出

如何在 ASP.NET 應用程序中掃描條碼:圖5-包含條碼類型和文本的代碼輸出

如何構建條碼或 QR Code 掃描的 REST API?

現代 ASP.NET 網頁應用程序通常需要通過 REST API 暴露條碼掃描功能,從而實現與移動應用程序、SPAs 或第三方服務的集成。 以下是如何使用 ASP.NET Core 創建一個強大的條碼掃描器 API:

[ApiController]
[Route("api/[controller]")]
public class BarcodeController : ControllerBase
{
    [HttpPost("scan")]
    public IActionResult ScanBarcode([FromBody] BarcodeRequest request)
    {
        try
        {
            // Convert base64 string to byte array
            byte[] imageBytes = Convert.FromBase64String(request.ImageBase64);
            // Read barcodes from the image
            var results = BarcodeReader.Read(imageBytes);
            var response = results.Select(r => new 
            {
                type = r.BarcodeType.ToString(),
                value = r.Text,
                position = new { x = r.Points.Select(b => b.X).Min(), y= r.Points.Select(b => b.Y).Min(), r.Width, r.Height }
            }).ToList();
            return Ok(new { success = true, barcodes = response });
        }
        catch (Exception ex)
        {
            return BadRequest(new { success = false, error = ex.Message });
        }
    }
}
public class BarcodeRequest
{
    public string ImageBase64 { get; set; }
}
[ApiController]
[Route("api/[controller]")]
public class BarcodeController : ControllerBase
{
    [HttpPost("scan")]
    public IActionResult ScanBarcode([FromBody] BarcodeRequest request)
    {
        try
        {
            // Convert base64 string to byte array
            byte[] imageBytes = Convert.FromBase64String(request.ImageBase64);
            // Read barcodes from the image
            var results = BarcodeReader.Read(imageBytes);
            var response = results.Select(r => new 
            {
                type = r.BarcodeType.ToString(),
                value = r.Text,
                position = new { x = r.Points.Select(b => b.X).Min(), y= r.Points.Select(b => b.Y).Min(), r.Width, r.Height }
            }).ToList();
            return Ok(new { success = true, barcodes = response });
        }
        catch (Exception ex)
        {
            return BadRequest(new { success = false, error = ex.Message });
        }
    }
}
public class BarcodeRequest
{
    public string ImageBase64 { get; set; }
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

此條碼讀取器 API 端點接受 base64 編碼圖像,這是通過 HTTP 傳輸圖像的標準格式。響應包括條碼值及其類型。 實施遵循 RESTful 最佳實踐,確保與任何前端框架的無縫集成。

以下 JavaScript 代碼用於從 JavaScript 客戶端調用此 API:

async function scanBarcode(imageFile) {
    const base64 = await convertToBase64(imageFile);
    const response = await fetch('/api/barcode/scan', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ imageBase64: base64 })
    });
    const result = await response.json();
    console.log('Scanned barcodes:', result.barcodes);
}
 async function convertToBase64(file) {
    return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.onload = () => {
            // Remove the data URL prefix to get only the base64 string
            const base64 = reader.result.split(',')[1];
            resolve(base64);
        };
        reader.onerror = error => reject(error);
        reader.readAsDataURL(file);
    });
}
async function scanBarcode(imageFile) {
    const base64 = await convertToBase64(imageFile);
    const response = await fetch('/api/barcode/scan', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ imageBase64: base64 })
    });
    const result = await response.json();
    console.log('Scanned barcodes:', result.barcodes);
}
 async function convertToBase64(file) {
    return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.onload = () => {
            // Remove the data URL prefix to get only the base64 string
            const base64 = reader.result.split(',')[1];
            resolve(base64);
        };
        reader.onerror = error => reject(error);
        reader.readAsDataURL(file);
    });
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

此 API 方法實現了與現代 JavaScript 框架、移動應用程序的無縫集成,並支持需要異步或批量操作進行條碼掃描的場景。

示例輸入

如何在 ASP.NET 應用程序中掃描條碼:圖6-多個條碼

輸出

如何在 ASP.NET 應用程序中掃描條碼:圖7-API 響應

如何處理複雜的條碼圖像?

在 ASP.NET 網頁應用程序中進行實際環境條碼掃描時,經常會遇到不太完美的圖像:角度拍攝的照片、光線條件差、或部分受損的條碼。 IronBarcode 在這些場景中表現優異,具備其高級圖像處理能力:

var options = new BarcodeReaderOptions
{
    // Balance speed vs accuracy
    Speed = ReadingSpeed.Balanced,
    // Specify expected barcode types for better performance
    ExpectBarcodeTypes = BarcodeEncoding.QRCode | BarcodeEncoding.Code128,
    // Enable automatic rotation correction
    AutoRotate = true,
    // Apply image filters for clarity
    ImageFilters = new ImageFilterCollection
    {
        new SharpenFilter(),
        new ContrastFilter(1.5f)
    },
    // Use multiple threads for faster processing
    Multithreaded = true
};
var results = BarcodeReader.Read("challenging-image.jpg", options);
var options = new BarcodeReaderOptions
{
    // Balance speed vs accuracy
    Speed = ReadingSpeed.Balanced,
    // Specify expected barcode types for better performance
    ExpectBarcodeTypes = BarcodeEncoding.QRCode | BarcodeEncoding.Code128,
    // Enable automatic rotation correction
    AutoRotate = true,
    // Apply image filters for clarity
    ImageFilters = new ImageFilterCollection
    {
        new SharpenFilter(),
        new ContrastFilter(1.5f)
    },
    // Use multiple threads for faster processing
    Multithreaded = true
};
var results = BarcodeReader.Read("challenging-image.jpg", options);
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

BarcodeReaderOptions 類提供對條碼掃描過程的細粒度控制。 設置 AutoRotate 為 true 可以處理以任意角度捕獲的圖像,而圖像濾鏡則可以增強模糊或低對比度條碼的清晰度。 Speed 屬性可以根據您的特定 ASP.NET 應用要求在處理速度和準確性之間取得平衡。 對於高容量處理,啟用多線程可以通過利用所有可用 CPU 核心顯著提高性能。 此方法符合.NET 應用程序中的圖像處理行業最佳實踐

結論和最佳實踐

使用 IronBarcode 在 ASP.NET 網頁應用程序中實現條碼掃描將一個潛在複雜的任務轉變為簡明易維護的代碼。 該庫能夠處理多種格式、處理不完美的圖像、解碼條碼,並在跨平台上提供一致的結果,這使其對於企業應用程序來說是一個非常有價值的工具。

對於生產部署,請記住要實施正確的錯誤處理、驗證上傳的文件以確保安全,以及考慮緩存經常掃描的條碼。 IronBarcode 的跨平台支持確保您的條碼掃描方案能夠在 Docker 容器和雲環境中無縫運行,提供現代應用程序所需的靈活性。 Explore the complete API documentation to discover advanced features like batch processing and PDF barcode extraction.

準備好通過專業條碼掃描來改變您的 ASP.NET 應用程序嗎? 開始您的免費試用以充分發掘 IronBarcode 在您的生產環境中的全部潛力。

常見問題解答

條碼掃描在 ASP.NET 應用程式中的主要用途是什麼?

條碼掃描在 ASP.NET 應用程式中的主要用於增強庫存管理系統、在活動中處理門票和數字化紙質文件,從而提高效率並減少錯誤。

IronBarcode 如何促進 ASP.NET 中的條碼掃描?

IronBarcode 通過提供可以輕鬆集成到網頁應用程式中的可靠且高效的組件,簡化了 ASP.NET 中的條碼掃描過程,允許開發者快速實現掃描功能。

IronBarcode 可以掃描哪些類型的條碼?

IronBarcode 支持掃描多種條碼格式,包括傳統的線性條碼和現代的二維條碼,確保與多樣化的應用程序兼容。

IronBarcode 能否處理文件處理的條碼掃描?

是的,IronBarcode 非常適合文件處理工作流程,可以用來掃描嵌入的條碼以數字化和組織紙質文件。

IronBarcode 是否適合庫存管理系統?

IronBarcode 是庫存管理系統的極佳選擇,因為它可以通過掃描條碼來高效跟踪產品,從而簡化操作並減少錯誤。

集成 IronBarcode 如何改善活動門票處理?

通過集成 IronBarcode,活動門票處理變得無縫,因為它允許快速掃描門票條碼,從而促進事件中快速準確的入場管理。

在 ASP.NET 專案中使用 IronBarcode 有哪些優勢?

在 ASP.NET 專案中使用 IronBarcode 提供了多種優勢,包括易於集成、多條碼格式支持,以及增強的應用程式性能,從而為條碼掃描需求提供了強大的解決方案。

實施 IronBarcode 是否需要廣泛的編碼知識?

不,IronBarcode 的設計以開發者為導向,使得在 ASP.NET 應用程式中實現條碼掃描功能變得簡單,僅需最低限度的編碼知識。

IronBarcode 能否用於移動網頁應用程式?

是的,IronBarcode 可以集成到移動網頁應用程式中,允許隨時隨地的條碼掃描,提升了 ASP.NET 專案的多功能性。

Jordi Bardia
軟體工程師
Jordi 在 Python、C# 和 C++ 上最得心應手,當他不在 Iron Software 展現技術時,便在做遊戲編程。在分担产品测测试,产品开发和研究的责任时,Jordi 为持续的产品改进增值。他说这种多样化的经验使他受到挑战并保持参与, 而这也是他与 Iron Software 中工作一大乐趣。Jordi 在佛罗里达州迈阿密长大,曾在佛罗里达大学学习计算机科学和统计学。