VintaSoft Barcode .NET SDK 15.1: Руководство для .NET разработчика
Vintasoft.Barcode.SymbologySubsets Namespace / BarcodeSymbologySubset Class
    Класс BarcodeSymbologySubset
    В этом разделе
    Абстрактный базовый класс, который определяет подмножество символов штрих-кода.
    Объектная модель
    BarcodeSymbologySubset BarcodeSymbologySubset
    Синтаксис
    'Declaration
    
    Public MustInherit Class BarcodeSymbologySubset
       Inherits Vintasoft.Barcode.BarcodeSymbology
    
    
    public abstract class BarcodeSymbologySubset : Vintasoft.Barcode.BarcodeSymbology
    
    
    public __gc abstract class BarcodeSymbologySubset : public Vintasoft.Barcode.BarcodeSymbology*
    
    
    public ref class BarcodeSymbologySubset abstract : public Vintasoft.Barcode.BarcodeSymbology^
    
    
    Ремарки

    Этот класс необходимо использовать, если необходимо определить подмножество символов штрих-кода некоторого базового типа штрих-кода.
    Вот примеры возможных подмножеств символов штрих-кода:

    • Штрих-коды Code39 с контрольной суммой по модулю 256
    • Штрих-коды Code128, содержащие 10 символов, из которых 6 первых символов являются цифрами
    • Штрих-коды Code39, высота которых превышает указанное значение
    • Штрих-коды DataMatrix, значения которых закодированы в указанном формате

    Для определения подмножества символики штрих-кода необходимо переопределить метод Decode(IBarcodeInfo), который определяет алгоритм преобразования исходного значения символики штрих-кода в подмножество символики штрих-кода. value.
    Метод Encode(ValueItemBase,WriterSettings) также может быть переопределен, но это не обязательно, этот метод определяет алгоритм для преобразования значения поднабора символов штрих-кода в исходное значение символики штрих-кода.

    Использование подмножеств символики штрих-кода позволяет классифицировать искомый штрих-код как штрих-код из подмножества символики штрих-кода во время распознавания штрих-кода, что может значительно увеличить скорость распознавания штрих-кода и позволяет использовать свойство ExpectedBarcodes для указания ожидаемого количества штрих-кодов.

    VintaSoft Barcode .NET SDK имеет следующие встроенные подмножества символик штрих-кодов:

    Пример

    Вот C#/VB.NET код, который демонстрирует, как задать подмножество штрих-кодов Code39 с контрольной суммой по модулю 256.

       
       
    Imports Vintasoft.Barcode.SymbologySubsets   
    Imports Vintasoft.Barcode   
    Imports Vintasoft.Barcode.BarcodeInfo   
    Imports Vintasoft.Imaging   
       
    ''' <summary>
    ''' Test that demonstrates how to generate an image with Code39 barcode with checksum modulo 256
    ''' and how to read Code39 barcode with checksum modulo 256 in image.
    ''' </summary>
    Public NotInheritable Class Code39Checksum256SymbologyTest   
        Private Sub New()   
        End Sub   
       
        ''' <summary>
        ''' Runs the test.
        ''' </summary>
        Public Shared Sub Test()   
            Test("TEST12345")   
            Test("ABCDEF")   
            Test("AB")   
            Test("123456789")   
        End Sub   
       
        ''' <summary>
        ''' Runs the test for a single barcode value.
        ''' </summary>
        Public Shared Sub Test(value As String)   
            ' create an object that defines Code39 barcodes with checksum modulo 256
            Dim code39Checksum256 As New Code39Checksum256Symbology()   
       
            ' create the barcode writer
            Using writer As New BarcodeWriter()   
                ' specify that writer must generate Code39 barcode AND
                ' set the barcode value with checksum
                code39Checksum256.Encode(value, writer.Settings)   
       
                ' create image with Code39 barcode with checksum
                Using imageWithCode39BarcodeWithChecksum As VintasoftBitmap = writer.GetBarcodeAsVintasoftBitmap()   
                    ' specify that writer must generate Code39 barcode
                    writer.Settings.Barcode = BarcodeType.Code39   
       
                    ' set the barcode value without checksum
                    writer.Settings.Value = value   
       
                    ' create image with barcode without checksum
                    Using imageWithCode39Barcode As VintasoftBitmap = writer.GetBarcodeAsVintasoftBitmap()   
                        ' create the barcode reader
                        Using reader As New BarcodeReader()   
                            ' specify that reader must search for Code39 with checksum only
       
                            reader.Settings.ScanBarcodeTypes = BarcodeType.None   
                            reader.Settings.ScanBarcodeSubsets.Add(code39Checksum256)   
       
                            ' read barcode from image with barcode with checksum
                            Dim infos As IBarcodeInfo() = reader.ReadBarcodes(imageWithCode39BarcodeWithChecksum)   
       
                            ' show information about found barcode
       
                            Dim subsetInfo As BarcodeSubsetInfo = DirectCast(infos(0), BarcodeSubsetInfo)   
                            Console.WriteLine("Detected '{0}' barcode, value = {1}, base value = {2}.", subsetInfo.BarcodeSubset.Name, subsetInfo.Value, subsetInfo.BaseBarcodeInfo.Value)   
       
       
                            ' read barcodes from image with barcode without checksum
                            infos = reader.ReadBarcodes(imageWithCode39Barcode)   
                            ' if barcode is found
                            If infos.Length <> 0 Then   
                                ' throw exception
                                Throw New ApplicationException()   
                            End If   
                        End Using   
                    End Using   
                End Using   
            End Using   
        End Sub   
    End Class   
       
    ''' <summary>
    ''' Represents the barcode symbology subset that includes Code39 barcodes with checksum modulo 256.
    ''' </summary>
    Public Class Code39Checksum256Symbology   
        Inherits BarcodeSymbologySubset   
       
        #Region "Constructors"   
       
        ''' <summary>
        ''' Initializes a new instance of the <see cref="Code39Checksum256Symbology"/> class.
        ''' </summary>
        Public Sub New()   
            MyBase.New(BarcodeType.Code39, "Code39 CH256")   
        End Sub   
       
        #End Region   
       
       
       
        #Region "Methods"   
       
        ''' <summary>
        ''' Decodes the Code39 barcode value into Code39 barcode value with checksum modulo 256.
        ''' </summary>
        ''' <param name="info">Code39 barcode value.</param>
        ''' <returns>Code39 barcode value with checksum modulo 256.</returns>
        Public Overrides Function Decode(info As IBarcodeInfo) As BarcodeSubsetInfo   
            If info.Value IsNot Nothing AndAlso info.Value.Length >= 4 Then   
                ' get the barcode checksum
                Dim checksum As String = info.Value.Substring(info.Value.Length - 2)   
                ' get the barcode value
                Dim value As String = info.Value.Substring(0, info.Value.Length - 2)   
                ' if barcode checksum is correct
                If checksum = GenerateChecksum256(value) Then   
                    Dim result As New BarcodeSubsetInfo(info, Me, New TextValueItem(value))   
                    result.Confidence = 100   
                    Return result   
                End If   
            End If   
            Return Nothing   
        End Function   
       
        ''' <summary>
        ''' Encodes the Code39 barcode value with checksum modulo 256 into the Code39 barcode value
        ''' using provided barcode writer settings and
        ''' saves the source barcode symbology value in the barcode writer settings.
        ''' </summary>
        ''' <param name="value">Code39 barcode value with checksum modulo 256 to encode.</param>
        ''' <param name="settings">Barcode writer settings.</param>
        Public Overrides Sub Encode(value As ValueItemBase, settings As WriterSettings)   
            Dim textValue As String = value.ToString()   
            If textValue.Length < 2 Then   
                Throw New WriterSettingsException(WriterSettingsExceptionType.ExpectedNSymbolsInBarcodeValue, "minimum two symbols")   
            End If   
       
            ' specify the barcode symbology type
            settings.Barcode = Me.BarcodeType   
            ' add checksum to the barcode value
            settings.Value = String.Format("{0}{1}", textValue, GenerateChecksum256(textValue))   
        End Sub   
       
        ''' <summary>
        ''' Calculates simple checksum modulo 256.
        ''' </summary>
        ''' <param name="value">Text value.</param>
        ''' <returns>Checksum in HEX format.</returns>
        Private Shared Function GenerateChecksum256(value As String) As String   
            Dim checksum As Integer = 0   
            For i As Integer = 0 To value.Length - 1   
                Dim symbol As Integer = AscW(value(i)) Mod 39   
                If i Mod 2 = 0 Then   
                    checksum += symbol   
                Else   
                    checksum += symbol * 3   
                End If   
            Next   
            checksum = checksum Mod 256   
            Return checksum.ToString("X2")   
        End Function   
       
        #End Region   
       
    End Class   
       
    ' This code example produces the following output:
    '
    '   Detected 'Code39 CH256' barcode, value = TEST12345, base value = TEST12345E3.
    '   Detected 'Code39 CH256' barcode, value = ABCDEF, base value = ABCDEF59.
    '   Detected 'Code39 CH256' barcode, value = AB, base value = AB6B.
    '   Detected 'Code39 CH256' barcode, value = 123456789, base value = 123456789EE.
    '
    
    
    
    
    using System;
    
    using Vintasoft.Barcode.SymbologySubsets;
    using Vintasoft.Barcode;
    using Vintasoft.Barcode.BarcodeInfo;
    using Vintasoft.Imaging;
    
    /// <summary>
    /// Test that demonstrates how to generate an image with Code39 barcode with checksum modulo 256
    /// and how to read Code39 barcode with checksum modulo 256 in image.
    /// </summary>
    public static class Code39Checksum256SymbologyTest
    {
    
        /// <summary>
        /// Runs the test.
        /// </summary>
        public static void Test()
        {
            Test("TEST12345");
            Test("ABCDEF");
            Test("AB");
            Test("123456789");
        }
    
        /// <summary>
        /// Runs the test for a single barcode value.
        /// </summary>
        public static void Test(string value)
        {
            // create an object that defines Code39 barcodes with checksum modulo 256
            Code39Checksum256Symbology code39Checksum256 = new Code39Checksum256Symbology();
    
            // create the barcode writer
            using (BarcodeWriter writer = new BarcodeWriter())
            {
                // specify that writer must generate Code39 barcode AND
                // set the barcode value with checksum
                code39Checksum256.Encode(value, writer.Settings);
    
                // create image with Code39 barcode with checksum
                using (VintasoftBitmap imageWithCode39BarcodeWithChecksum = writer.GetBarcodeAsVintasoftBitmap())
                {
                    // specify that writer must generate Code39 barcode
                    writer.Settings.Barcode = BarcodeType.Code39;
    
                    // set the barcode value without checksum
                    writer.Settings.Value = value;
    
                    // create image with barcode without checksum
                    using (VintasoftBitmap imageWithCode39Barcode = writer.GetBarcodeAsVintasoftBitmap())
                    {
                        // create the barcode reader
                        using (BarcodeReader reader = new BarcodeReader())
                        {
                            // specify that reader must search for Code39 with checksum only
    
                            reader.Settings.ScanBarcodeTypes = BarcodeType.None;
                            reader.Settings.ScanBarcodeSubsets.Add(code39Checksum256);
    
                            // read barcode from image with barcode with checksum
                            IBarcodeInfo[] infos = reader.ReadBarcodes(imageWithCode39BarcodeWithChecksum);
    
                            // show information about found barcode
    
                            BarcodeSubsetInfo subsetInfo = ((BarcodeSubsetInfo)infos[0]);
                            Console.WriteLine("Detected '{0}' barcode, value = {1}, base value = {2}.",
                                subsetInfo.BarcodeSubset.Name,
                                subsetInfo.Value,
                                subsetInfo.BaseBarcodeInfo.Value);
    
    
                            // read barcodes from image with barcode without checksum
                            infos = reader.ReadBarcodes(imageWithCode39Barcode);
                            // if barcode is found
                            if (infos.Length != 0)
                                // throw exception
                                throw new ApplicationException();
                        }
                    }
                }
            }
        }
    }
    
    /// <summary>
    /// Represents the barcode symbology subset that includes Code39 barcodes with checksum modulo 256.
    /// </summary>
    public class Code39Checksum256Symbology : BarcodeSymbologySubset
    {
    
        #region Constructors
    
        /// <summary>
        /// Initializes a new instance of the <see cref="Code39Checksum256Symbology"/> class.
        /// </summary>
        public Code39Checksum256Symbology()
            :base(BarcodeType.Code39, "Code39 CH256")
        {
        }
        
        #endregion
    
    
    
        #region Methods
    
        /// <summary>
        /// Decodes the Code39 barcode value into Code39 barcode value with checksum modulo 256.
        /// </summary>
        /// <param name="info">Code39 barcode value.</param>
        /// <returns>Code39 barcode value with checksum modulo 256.</returns>
        public override BarcodeSubsetInfo Decode(IBarcodeInfo info)
        {
            if (info.Value != null && info.Value.Length >= 4)
            {
                // get the barcode checksum
                string checksum = info.Value.Substring(info.Value.Length - 2);
                // get the barcode value
                string value = info.Value.Substring(0, info.Value.Length - 2);
                // if barcode checksum is correct
                if (checksum == GenerateChecksum256(value))
                {
                    BarcodeSubsetInfo result = new BarcodeSubsetInfo(info, this, new TextValueItem(value));
                    result.Confidence = 100;
                    return result;
                }
            }
            return null;
        }
    
        /// <summary>
        /// Encodes the Code39 barcode value with checksum modulo 256 into the Code39 barcode value
        /// using provided barcode writer settings and
        /// saves the source barcode symbology value in the barcode writer settings.
        /// </summary>
        /// <param name="value">Code39 barcode value with checksum modulo 256 to encode.</param>
        /// <param name="settings">Barcode writer settings.</param>
        public override void Encode(ValueItemBase value, WriterSettings settings)
        {
            string textValue = value.ToString();
            if (textValue.Length < 2)
                throw new WriterSettingsException(
                    WriterSettingsExceptionType.ExpectedNSymbolsInBarcodeValue, 
                    "minimum two symbols");
    
            // specify the barcode symbology type
            settings.Barcode = this.BarcodeType;
            // add checksum to the barcode value
            settings.Value = string.Format("{0}{1}", textValue, GenerateChecksum256(textValue));
        }
    
        /// <summary>
        /// Calculates simple checksum modulo 256.
        /// </summary>
        /// <param name="value">Text value.</param>
        /// <returns>Checksum in HEX format.</returns>
        private static string GenerateChecksum256(string value)
        {
            int checksum = 0;
            for (int i = 0; i < value.Length; i++)
            {
                int symbol = (int)value[i] % 39;
                if (i % 2 == 0)
                    checksum += symbol;
                else
                    checksum += symbol * 3;
            }
            checksum = checksum % 256;
            return checksum.ToString("X2");
        }
    
        #endregion
    
    }
    
    /* This code example produces the following output:
         
       Detected 'Code39 CH256' barcode, value = TEST12345, base value = TEST12345E3.
       Detected 'Code39 CH256' barcode, value = ABCDEF, base value = ABCDEF59.
       Detected 'Code39 CH256' barcode, value = AB, base value = AB6B.
       Detected 'Code39 CH256' barcode, value = 123456789, base value = 123456789EE.
    */
    
    

    Иерархия наследования

    System.Object
       Vintasoft.Barcode.BarcodeSymbology
          Vintasoft.Barcode.SymbologySubsets.BarcodeSymbologySubset
             Vintasoft.Barcode.SymbologySubsets.AamvaBarcodeSymbology
             Vintasoft.Barcode.SymbologySubsets.BarcodeSymbologyWithChecksum
             Vintasoft.Barcode.SymbologySubsets.Code32BarcodeSymbology
             Vintasoft.Barcode.SymbologySubsets.Code39ExtendedBarcodeSymbology
             Vintasoft.Barcode.SymbologySubsets.CompositeBarcodeSymbologySubset
             Vintasoft.Barcode.SymbologySubsets.DeutschePost2Of5BaseSymbology
             Vintasoft.Barcode.SymbologySubsets.DhlAwbBarcodeSymbology
             Vintasoft.Barcode.SymbologySubsets.EanVelocityBarcodeSymbology
             Vintasoft.Barcode.SymbologySubsets.FedExGround96BarcodeSymbology
             Vintasoft.Barcode.SymbologySubsets.GS1BarcodeSymbologySubset
             Vintasoft.Barcode.SymbologySubsets.HibcLicBarcodeSymbology
             Vintasoft.Barcode.SymbologySubsets.IsbnBarcodeSymbology
             Vintasoft.Barcode.SymbologySubsets.IsbtBarcodeSymbology
             Vintasoft.Barcode.SymbologySubsets.IssnBarcodeSymbology
             Vintasoft.Barcode.SymbologySubsets.JanBarcodeSymbology
             Vintasoft.Barcode.SymbologySubsets.NumlyNumberBarcodeSymbology
             Vintasoft.Barcode.SymbologySubsets.OpcBarcodeSymbology
             Vintasoft.Barcode.SymbologySubsets.PpnBarcodeSymbology
             Vintasoft.Barcode.SymbologySubsets.PznBarcodeSymbology
             Vintasoft.Barcode.SymbologySubsets.MailmarkCmdmBarcodeSymbology
             Vintasoft.Barcode.SymbologySubsets.SwissPostParcelBarcodeSymbology
             Vintasoft.Barcode.SymbologySubsets.SwissQRCodeBarcodeSymbology
             Vintasoft.Barcode.SymbologySubsets.VicsBolBarcodeSymbology
             Vintasoft.Barcode.SymbologySubsets.VicsScacProBarcodeSymbology
             Vintasoft.Barcode.SymbologySubsets.VinSymbology
             Vintasoft.Barcode.SymbologySubsets.XFACompressedBarcodeSymbologySubset

    Требования

    Целевые платформы: .NET 8; .NET 7; .NET 6; .NET Framework 4.8, 4.7, 4.6, 4.5, 4.0, 3.5

    Смотрите также