萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> ASP.NET 程式設計

ASP.NET C# 產生 Code39 條碼完整實作:可掃描、可調整尺寸、支援完整 ASCII

前言

Code39 (Code 3 of 9) 是常見的一維條碼規格,支援數字、大寫字母、符號 (- . $ / + % 空白),且起止碼皆為 `*`。本文提供完整、可直接使用的 `Code39` 類別,支援放大倍數、高度、字體、完整 ASCII 模式 (含小寫)、起止碼控制,並產生 `Bitmap` 可直接輸出至網頁、列印或儲存檔案。

Code39 完整類別實作


using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;

namespace BarcodeLib
{
    /// 
    /// Code39 條碼產生器
    /// 
    public class Code39
    {
        // Code39 編碼表:字元 -> 9 位元組模式 (寬窄寬窄...),1=黑(寬), 0=白(窄),實際為 9 元素
        // 標準 Code39: 9 個元素 (5條黑槓+4條白槓),寬:窄 = 3:1 或 2:1
        // 此處採用常見編碼字串:'1'=窄黑, '0'=窄白, '2'=寬黑, '3'=寬白 (視實作而定)
        // 下方採用標準 9 位元組模式:'1'=黑, '0'=白,寬度由 Magnify 控制
        private static readonly Dictionary Code39Map = new Dictionary
        {
            {'0', "101001101101"}, {'1', "110100101011"}, {'2', "101100101011"}, {'3', "110110010101"},
            {'4', "101001101011"}, {'5', "110100110101"}, {'6', "101100110101"}, {'7', "101001011011"},
            {'8', "110100101101"}, {'9', "101100101101"},
            {'A', "110101001011"}, {'B', "101101001011"}, {'C', "110110100101"}, {'D', "101011001011"},
            {'E', "110101100101"}, {'F', "101101100101"}, {'G', "101010011011"}, {'H', "110101001101"},
            {'I', "101101001101"}, {'J', "101011001101"}, {'K', "110101010011"}, {'L', "101101010011"},
            {'M', "110110101001"}, {'N', "101011010011"}, {'O', "110101101001"}, {'P', "101101101001"},
            {'Q', "101010110011"}, {'R', "110101011001"}, {'S', "101101011001"}, {'T', "101011011001"},
            {'U', "110010101011"}, {'V', "100110101011"}, {'W', "110011010101"}, {'X', "100101101011"},
            {'Y', "110010110101"}, {'Z', "100110110101"},
            {'-', "100101011011"}, {'.', "110010101101"}, {' ', "100110101101"},
            {'$', "101010100101"}, {'/', "101010010101"}, {'+', "101001010101"}, {'%', "100100101011"},
            {'*', "100101101101"} // 起止碼
        };

        public byte Magnify { get; set; } = 2; // 放大倍數 (模組寬度像素)
        public int Height { get; set; } = 60;  // 條碼高度 (像素)
        public Font TextFont { get; set; } = new Font("Consolas", 10); // 文字字體
        public bool ShowText { get; set; } = true; // 是否顯示底部文字
        public bool IncludeStartStop { get; set; } = true; // 是否加入起止碼 *

        /// 
        /// 產生 Code39 條碼圖片
        /// 
        /// 要編碼的文字 (支援 Code39 標準字元集)
        /// true=Code39 Full ASCII (支援小寫、控制字元),false=標準 Code39
        /// Bitmap 物件
        public Bitmap Generate(string text, bool fullAscii = false)
        {
            if (string.IsNullOrEmpty(text)) throw new ArgumentException("文字不可為空");
            
            string encodedText = PrepareText(text, fullAscii);
            if (string.IsNullOrEmpty(encodedText)) throw new ArgumentException("包含不支援的字元");

            // 計算寬度:每字元 12 模組 (9黑白+3間隔) + 起止碼 12*2 + 字元間距
            int modulesPerChar = 12; // 9元素 + 3間隔(白)
            int totalModules = (encodedText.Length * modulesPerChar) + (IncludeStartStop ? 24 : 0); // 起止碼各12模組
            int width = totalModules * Magnify;
            
            Bitmap bmp = new Bitmap(width, Height, PixelFormat.Format24bppRgb);
            using (Graphics g = Graphics.FromImage(bmp))
            {
                g.Clear(Color.White);
                
                int x = 0;
                // 起始碼
                if (IncludeStartStop) x = DrawCharPattern(g, x, Code39Map['*']);
                
                // 內容字元
                foreach (char c in encodedText)
                {
                    if (Code39Map.TryGetValue(c, out string pattern))
                    {
                        x = DrawCharPattern(g, x, pattern);
                        // 字元間距 (1模組白)
                        x += Magnify;
                    }
                }
                
                // 結束碼
                if (IncludeStartStop) DrawCharPattern(g, x, Code39Map['*']);
                
                // 繪製底部文字
                if (ShowText && TextFont != null)
                {
                    string displayText = IncludeStartStop ? $"*{text}*" : text;
                    SizeF textSize = g.MeasureString(displayText, TextFont);
                    float textX = (width - textSize.Width) / 2;
                    float textY = Height - textSize.Height - 2;
                    g.DrawString(displayText, TextFont, Brushes.Black, textX, textY);
                }
            }
            return bmp;
        }

        private string PrepareText(string text, bool fullAscii)
        {
            if (!fullAscii)
            {
                // 標準 Code39:轉大寫,檢查字元
                text = text.ToUpper();
                foreach (char c in text)
                    if (!Code39Map.ContainsKey(c)) return null;
                return text;
            }
            else
            {
                // Full ASCII 模式:使用 +A~+Z 代表 a~z,%A~%Z 代表控制字元 等
                // 簡化實作:這裡僅處理小寫轉 +大寫,完整實作需對照 Code39 Full ASCII 對照表
                var sb = new System.Text.StringBuilder();
                foreach (char c in text)
                {
                    if (c >= 'a' && c <= 'z')
                        sb.Append('+').Append(char.ToUpper(c));
                    else if (Code39Map.ContainsKey(c))
                        sb.Append(c);
                    else
                        return null; // 不支援字元
                }
                return sb.ToString();
            }
        }

        private int DrawCharPattern(Graphics g, int startX, string pattern)
        {
            // pattern 如 "110101001011" : 1=黑, 0=白,共 12 字元 (9元素+3間隔? 實際標準為 9元素+1間隔=10)
            // 此處假設 pattern 長度為 12 (含字元間距),或 9 (不含間距)
            // 依據標準:9個元素 (5黑4白) + 1個元素間距(白) = 10模組
            // 但常見編碼表字串長度為 12 或 9,需對應調整
            // 下方以 pattern 每字元為一模組,1=黑, 0=白
            for (int i = 0; i < pattern.Length; i++)
            {
                if (pattern[i] == '1') // 黑槓
                {
                    g.FillRectangle(Brushes.Black, startX, 0, Magnify, Height - (ShowText ? TextFont.Height + 4 : 0));
                }
                // 白槓不需繪製 (背景為白)
                startX += Magnify;
            }
            return startX;
        }
    }
}

ASP.NET 網頁輸出條碼圖片

Generic Handler (.ashx) - 推薦方式


<%@ WebHandler Language="C#" Class="BarcodeHandler" %>
using System;
using System.Web;
using BarcodeLib;

public class BarcodeHandler : IHttpHandler
{
    public void ProcessRequest(HttpContext context)
    {
        string text = context.Request.QueryString["text"];
        bool fullAscii = context.Request.QueryString["full"] == "1";
        int magnify = int.TryParse(context.Request.QueryString["mag"], out int m) ? m : 2;
        int height = int.TryParse(context.Request.QueryString["h"], out int h) ? h : 60;
        bool showText = context.Request.QueryString["txt"] != "0";
        bool startStop = context.Request.QueryString["ss"] != "0";

        if (string.IsNullOrEmpty(text))
        {
            context.Response.StatusCode = 400;
            context.Response.Write("Missing 'text' parameter");
            return;
        }

        try
        {
            var generator = new Code39 { Magnify = (byte)magnify, Height = height, ShowText = showText, IncludeStartStop = startStop };
            using (Bitmap bmp = generator.Generate(text, fullAscii))
            {
                context.Response.ContentType = "image/png";
                bmp.Save(context.Response.OutputStream, ImageFormat.Png);
            }
        }
        catch (Exception ex)
        {
            context.Response.StatusCode = 500;
            context.Response.Write("Error: " + ex.Message);
        }
    }

    public bool IsReusable => false;
}

前端使用



Barcode


protected void Page_Load(object sender, EventArgs e)
{
    var generator = new Code39 { Magnify = 2, Height = 50 };
    using (Bitmap bmp = generator.Generate("INV-2024001"))
    {
        string base64;
        using (MemoryStream ms = new MemoryStream())
        {
            bmp.Save(ms, ImageFormat.Png);
            base64 = Convert.ToBase64String(ms.ToArray());
        }
        imgBarcode.ImageUrl = "data:image/png;base64," + base64;
    }
}

Code39 規格補充說明

  • 字元集:43 個字元 (0-9, A-Z, - . $ / + % 空白) + 起止碼 *
  • Full ASCII:雙字元編碼擴展至 128 ASCII (如 `+A`=a, `%A`=SOH),需掃描器支援。
  • 寬窄比:標準 3:1 或 2:1,本實作以 `Magnify` 控制模組像素寬度,視列印解析度調整 (建議 2~4)。
  • 靜區:條碼左右兩側需保留至少 10 個模組寬度的空白區,本實作未自動加入,列印時請自行留白。
  • 校驗碼:Code39 選用 Modulo 43 校驗碼,本實作未內建,若需可自行計算附加於文字末尾。

替代方案:使用成熟開源庫

若需支援 QR Code、Code128、EAN-13 等多種格式,建議直接使用:

  • ZXing.Net (NuGet: `ZXing.Net`):Google ZXing 移植版,支援多格式編碼/解碼。
  • BarcodeLib (NuGet: `BarcodeLib`):輕量、易用、支援 Code39/128/EAN 等。
  • QRCoder (NuGet: `QRCoder`):專精 QR Code。

// ZXing.Net 產生 Code39 範例
using ZXing;
using ZXing.Common;
using ZXing.Rendering;

var writer = new BarcodeWriterPixelData
{
    Format = BarcodeFormat.CODE_39,
    Options = new EncodingOptions
    {
        Width = 300,
        Height = 100,
        Margin = 10,
        PureBarcode = false // 含文字
    },
    Renderer = new PixelDataRenderer()
};
var pixelData = writer.Write("HELLO123");
// 轉 Bitmap 儲存或輸出...

總結:本文提供功能完整的 `Code39` 類別,支援尺寸調整、文字顯示、Full ASCII 模式,並示範 `.ashx` 處理常式動態輸出圖片。生產環境建議優先使用成熟庫 (ZXing.Net) 以確保相容性與維護性;若需自行實作或客製化渲染邏輯,本程式碼提供清晰的編碼邏輯與繪圖基礎。

copyright © 萬盛學電腦網 all rights reserved