Generador de códigos de barras en .NET

Es útil saber crear código de barras, sobre todo si eres el dueño de un negocio y deseas promover lo que haces o lo que eres, colocando un código de barras en la parte posterior de tu tarjeta de visita, o en un escaparate, o utilizandolos para captar el números de referencia de un producto etc.

La aplicación que vamos a desarrollar en este artículo usa 3 tipos de código de barras:

  • Código de líneas (utilizado en libros, envases de alimentos, etc.).
  • Códigos QR (utilizados en tarjetas de visita, tarjetas de regalo, etc.).
  • Matrices de datos (utilizado en cartas).

Quisiera señalar ahora que los códigos de líneas y los QR soportan fondos transparentes, pero las matrices de datos no.

También deciros antes de empezar que las principales propiedades del código de barras deben ser completadas antes de ser generadas haciendo clic en el botón, de lo contrario obtendremos una excepción. Aclarado todo esto, vamos a echar un vistazo al código.

El código QR resultante de la cadena "Hello World"

Crea un nuevo proyecto de Visual Studio y guarda de inmediato para que el IDE hace genere los directorios relevantes. Personalmente me gusta copiar las librerías DLL en el directorio de la aplicación, por ejemplo. (Nombre del Proyecto/debug/bin), pero eso ya es cosa de cada uno.

Una vez que estas DLL se han ubicado en un lugar adecuado, hay que añadir las referencias a todas ellas haciendo clic en el Explorador de soluciones, y, a continuación, haciendo clic derecho sobre el nombre del proyecto. Ahora vamos a agregar la referencia haciendo clic en el botón Agregar referencia para añadir la de los 3 archivos DLL. Empezamos importando las librerías y declarando algunas variables.

Imports System                         
Imports System.Drawing                 
Imports ThoughtWorks.QRCode.Codec        ' this is the QRcode Library
Imports BarcodeLib.Barcode               ' this is the Linear library
Imports DataMatrix.net.DmtxImageEncoder  ' this is the Data Matrix library

    Dim QREncoder As ThoughtWorks.QRCode.Codec.QRCodeEncoder          ' QR code
    Dim LinearEncoder As BarcodeLib.Barcode                           ' LinearCdoe
    Dim DataEncoder As DataMatrix.net.DmtxImageEncoder                ' Data Matrix
    Dim DataEncodeOptions As DataMatrix.net.DmtxImageEncoderOptions   'set a variable to handle data
                                                                                      matrix options
    Dim Linearcode As Boolean  ' we are using these variables in an if statement
    Dim QRcode As Boolean      ' to determin what Barcode we are generating
    Dim Datacode As Boolean

    Dim QRimg As Image            ' Because the barcode result is an image we need to
    Dim QRbitmap As Bitmap        ' make a new image and bitmap in order to save the image
    Dim Linearimg As Image        '
    Dim Linearbitmap As Bitmap
    Dim Dataimg As Image
    Dim Databitmap As Bitmap
    Public barcodeImage As Bitmap ' we use this bitmap to assign the current barcode image to

    Dim DM_forecolour As Color    ' these variables are used to first fill the relevent comboboxes
    Dim DM_backcolour As Color    ' with the system colors and to use these colors to change the back
    Dim QR_foreColor As Color     ' and fore colors of the barcode image
    Dim QR_backColor As Color
    Dim L_foreColor As Color
    Dim L_backColor As Color
    Dim colorName As String       ' used to get all system colors

    Dim SelectedFont As Font      ' used to assign the selected font to the barcode label

    Dim X, Y As Integer           ' Declare 2 variables so we can make form_Viewer (form2)
    Dim buffer As Integer = 100   ' to the right size and add the buffer just to be sure we can see
                                  ' the entire Barcode

Form1_Load

Para posibles referencias, debéis saber que:

  • Cbo_D_name es el nombre del combobox para los comboboxes de las matrices de datos
  • Cbo_QR_name es el nombre del combobox para los comboboxes de los códigos QR
  • Cbo_L_name es el nombre del combobox para los comboboxes de los códigos de líneas
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        '
        Rdo_QR.Checked = True            ' auto select QRcodes on startup
        QRcode = True                    ' 
        '---------------------------------------
        Cbo_D_Size.SelectedIndex = 12    ' auto set some combobox perameters on startup
        Cbo_D_Scheme.SelectedIndex = 0   '
        Cbo_D_Module.SelectedIndex = 1   ' 
        Cbo_D_Margin.SelectedIndex = 1   '
        '---------------------------------------
        Cbo_QR_Scale.SelectedIndex = 1
        Cbo_QR_Mode.SelectedIndex = 0
        Cbo_QR_Version.SelectedIndex = 5
        Cbo_QR_ErrorC.SelectedIndex = 0
        '---------------------------------------
        '
        ' add the fore and back colors to the  relevent comboboxes (Explained more below)
        '
        For Each Me.colorName In System.Enum.GetNames(GetType(System.Drawing.KnownColor))
            Cbo_D_fColor.Items.Add(Color.FromName(colorName))
            Cbo_D_bColor.Items.Add(Color.FromName(colorName))
            Cbo_QR_fColor.Items.Add(Color.FromName(colorName))
            Cbo_QR_bColor.Items.Add(Color.FromName(colorName))
            Cbo_L_bColor.Items.Add(Color.FromName(colorName))
            Cbo_L_fColor.Items.Add(Color.FromName(colorName))
            ' Label12.Text = Cbo_D_fColor.Items.Count  (Debug Line) just to see how many colors ther was
        Next
        '
    End Sub

Una de las características que puedes agregar aquí es la función de, cuando el usuario final haga clic en uno de los botones de selección de los otros dos cuadros del grupo, estos se deshabiliten.

Selección del botón de la matriz de datos

' DataMatrix RadioButton
    Private Sub Rdo_DataM_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Rdo_DataM.CheckedChanged

        If Rdo_DataM.Checked = True Then
            Datacode = True
            Linearcode = False
            QRcode = False
            ' the feature mentioned above would be 
            ' groupboxQR.enabled = false
            ' groupboxLinear.enabled = false
            ' and apply the type of action on the other radio buttons
        End If

    End Sub

Selección del botón del código QR

' QR RadioButton
   Private Sub Rdo_QR_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Rdo_QR.CheckedChanged

       If Rdo_QR.Checked = True Then
           QRcode = True
           Datacode = False
           Linearcode = False
       End If

   End Sub

Selección del botón del código de líneas

' Linear RadioButton
   Private Sub Rdo_Linear_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Rdo_Linear.CheckedChanged

       If Rdo_Linear.Checked = True Then
           Linearcode = True
           Datacode = False
           QRcode = False
       End If

   End Sub

Código del botón

'Label Font Button
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

        Try
            ' without the TRY block the application would hang if all the options where not fill out
            '
            If FontDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
                LinearEncoder.LabelFont = FontDialog1.Font
            End If
        Catch ex As Exception
            MsgBox(ex.Message)
            Exit Sub
        End Try
    End Sub

Colores de la matriz de datos

' Handle the color selection for data matrix color
    '
    Private Sub Cbo_D_fColor_DrawItem(ByVal sender As Object, ByVal e As System.Windows.Forms.DrawItemEventArgs) Handles Cbo_D_fColor.DrawItem
        If e.Index < 0 Then
            e.DrawBackground()
            e.DrawFocusRectangle()
            Exit Sub
        End If
        e.DrawBackground()
        e.DrawFocusRectangle()
        DM_forecolour = CType(Cbo_D_fColor.Items(e.Index), Color)
        e.Graphics.DrawString(DM_forecolour.Name, Cbo_D_fColor.Font, Brushes.Black, e.Bounds.Height + 5, ((e.Bounds.Height - Cbo_D_fColor.Font.Height)  2) + e.Bounds.Top)
    '
    End Sub
    '
    '
    '
    Private Sub Cbo_D_bColor_DrawItem(ByVal sender As Object, ByVal e As System.Windows.Forms.DrawItemEventArgs) Handles Cbo_D_bColor.DrawItem
        '
        If e.Index < 0 Then
            e.DrawBackground()
            e.DrawFocusRectangle()
            Exit Sub
        End If
        e.DrawBackground()
        e.DrawFocusRectangle()
        DM_backcolour = CType(Cbo_D_bColor.Items(e.Index), Color)
        e.Graphics.DrawString(DM_backcolour.Name, Cbo_D_bColor.Font, Brushes.Black, e.Bounds.Height + 5, ((e.Bounds.Height - Cbo_D_bColor.Font.Height)  2) + e.Bounds.Top)
    '
    End Sub

Colores del QR

'Handle the color selection for QR color
   Private Sub Cbo_QR_fColor_DrawItem(ByVal sender As Object, ByVal e As System.Windows.Forms.DrawItemEventArgs) Handles Cbo_QR_fColor.DrawItem
       If e.Index < 0 Then
           e.DrawBackground()
           e.DrawFocusRectangle()
           Exit Sub
       End If
       e.DrawBackground()
       e.DrawFocusRectangle()
       QR_foreColor = CType(Cbo_D_bColor.Items(e.Index), Color)

       e.Graphics.DrawString(QR_foreColor.Name, Cbo_D_bColor.Font, Brushes.Black, e.Bounds.Height + 5, ((e.Bounds.Height - Cbo_D_bColor.Font.Height)  2) + e.Bounds.Top)
   End Sub
   '
   Private Sub Cbo_QR_bColor_DrawItem(ByVal sender As Object, ByVal e As System.Windows.Forms.DrawItemEventArgs) Handles Cbo_QR_bColor.DrawItem
       If e.Index < 0 Then
           e.DrawBackground()
           e.DrawFocusRectangle()
           Exit Sub
       End If
       e.DrawBackground()
       e.DrawFocusRectangle()
       QR_backColor = CType(Cbo_QR_bColor.Items(e.Index), Color)

       e.Graphics.DrawString(QR_backColor.Name, Cbo_QR_bColor.Font, Brushes.Black, e.Bounds.Height + 5, ((e.Bounds.Height - Cbo_QR_bColor.Font.Height)  2) + e.Bounds.Top)
   End Sub

Colores del código de líneas

'Handle the color selection for Linear color
    Private Sub Cbo_L_bColor_DrawItem(ByVal sender As Object, ByVal e As System.Windows.Forms.DrawItemEventArgs) Handles Cbo_L_bColor.DrawItem
        If e.Index < 0 Then
            e.DrawBackground()
            e.DrawFocusRectangle()
            Exit Sub
        End If
        e.DrawBackground()
        e.DrawFocusRectangle()
        L_backColor = CType(Cbo_L_bColor.Items(e.Index), Color)

        e.Graphics.DrawString(L_backColor.Name, Cbo_L_bColor.Font, Brushes.Black, e.Bounds.Height + 5, ((e.Bounds.Height - Cbo_L_bColor.Font.Height)  2) + e.Bounds.Top)
    End Sub
    '
    Private Sub Cbo_L_fColor_DrawItem(ByVal sender As Object, ByVal e As System.Windows.Forms.DrawItemEventArgs) Handles Cbo_L_fColor.DrawItem
        If e.Index < 0 Then
            e.DrawBackground()
            e.DrawFocusRectangle()
            Exit Sub
        End If
        e.DrawBackground()
        e.DrawFocusRectangle()
        L_foreColor = CType(Cbo_L_fColor.Items(e.Index), Color)

        e.Graphics.DrawString(L_foreColor.Name, Cbo_L_fColor.Font, Brushes.Black, e.Bounds.Height + 5, ((e.Bounds.Height - Cbo_L_fColor.Font.Height)  2) + e.Bounds.Top)
    End Sub

Ok, aquí viene la parte divertida del código donde vamos a ver la función del sub action. Ruego que me disculpéis si alguna parte no se ha entendido a ha parecido algo confusa.

GenerateBarcode()

' Generate Function
    Public Sub GenerateBarcode(ByVal inputData As String)     ' a public sub with additional argument
                                                              ' inputData wich takes a string
        '
        '
        '
        If Linearcode = True Then    ' if the user has clicked the Liear Radio Button we
                                     ' generate a Linear Barcode
            '
            ' if the textbox has no text raise an error

            If Txt_InputData.Text.Length <= 0 Then
                MsgBox("You must Include the data to be Encoded.", MsgBoxStyle.OkOnly, "Data Error")
            Else

            LinearEncoder = New BarcodeLib.Barcode            'declare a new LinearEncoder
            LinearEncoder.AlternateLabel = Txt_label.Text     ' text to use as the label text
            TextBox1.Text = LinearEncoder.Country_Assigning_Manufacturer_Code ' most of the time this is            '                                                                 ' not used
            LinearEncoder.BackColor = L_backColor
            LinearEncoder.ForeColor = L_foreColor
            '
            '
            If CheckBox1.Checked = True Then
                LinearEncoder.IncludeLabel = True    ' include the label text in the encoded image
            End If
            '
            ' combobox for label positions
            If Cbo_L_LPosition.SelectedIndex = 0 Then
                LinearEncoder.LabelPosition = BarcodeLib.LabelPositions.BOTTOMCENTER
            ElseIf Cbo_L_LPosition.SelectedIndex = 1 Then
                LinearEncoder.LabelPosition = BarcodeLib.LabelPositions.BOTTOMLEFT
            ElseIf Cbo_L_LPosition.SelectedIndex = 2 Then
                LinearEncoder.LabelPosition = BarcodeLib.LabelPositions.BOTTOMRIGHT
            ElseIf Cbo_L_LPosition.SelectedIndex = 3 Then
                LinearEncoder.LabelPosition = BarcodeLib.LabelPositions.TOPCENTER
            ElseIf Cbo_L_LPosition.SelectedIndex = 4 Then
                LinearEncoder.LabelPosition = BarcodeLib.LabelPositions.TOPLEFT
            ElseIf Cbo_L_LPosition.SelectedIndex = 5 Then
                LinearEncoder.LabelPosition = BarcodeLib.LabelPositions.TOPRIGHT
            End If
            '
            '
            ' Linear barcode Encoding types
            '
            If Cbo_L_E_Type.SelectedIndex = 0 Then
                LinearEncoder.EncodedType = BarcodeLib.TYPE.BOOKLAND
            ElseIf Cbo_L_E_Type.SelectedIndex = 1 Then
                LinearEncoder.EncodedType = BarcodeLib.TYPE.Codabar
            ElseIf Cbo_L_E_Type.SelectedIndex = 2 Then
                LinearEncoder.EncodedType = BarcodeLib.TYPE.CODE11
            ElseIf Cbo_L_E_Type.SelectedIndex = 3 Then
                LinearEncoder.EncodedType = BarcodeLib.TYPE.CODE128
            ElseIf Cbo_L_E_Type.SelectedIndex = 4 Then
                LinearEncoder.EncodedType = BarcodeLib.TYPE.CODE128A
            ElseIf Cbo_L_E_Type.SelectedIndex = 5 Then
                LinearEncoder.EncodedType = BarcodeLib.TYPE.CODE128B
            ElseIf Cbo_L_E_Type.SelectedIndex = 6 Then
                LinearEncoder.EncodedType = BarcodeLib.TYPE.CODE128C
            ElseIf Cbo_L_E_Type.SelectedIndex = 7 Then
                LinearEncoder.EncodedType = BarcodeLib.TYPE.CODE39
            ElseIf Cbo_L_E_Type.SelectedIndex = 8 Then
                LinearEncoder.EncodedType = BarcodeLib.TYPE.CODE39_Mod43
            ElseIf Cbo_L_E_Type.SelectedIndex = 9 Then
                LinearEncoder.EncodedType = BarcodeLib.TYPE.CODE39Extended
            ElseIf Cbo_L_E_Type.SelectedIndex = 10 Then
                LinearEncoder.EncodedType = BarcodeLib.TYPE.CODE93
            ElseIf Cbo_L_E_Type.SelectedIndex = 11 Then
                LinearEncoder.EncodedType = BarcodeLib.TYPE.EAN13
            ElseIf Cbo_L_E_Type.SelectedIndex = 12 Then
                LinearEncoder.EncodedType = BarcodeLib.TYPE.EAN8
            ElseIf Cbo_L_E_Type.SelectedIndex = 13 Then
                LinearEncoder.EncodedType = BarcodeLib.TYPE.FIM
            ElseIf Cbo_L_E_Type.SelectedIndex = 14 Then
                LinearEncoder.EncodedType = BarcodeLib.TYPE.Industrial2of5
            ElseIf Cbo_L_E_Type.SelectedIndex = 15 Then
                LinearEncoder.EncodedType = BarcodeLib.TYPE.Interleaved2of5
            ElseIf Cbo_L_E_Type.SelectedIndex = 16 Then
                LinearEncoder.EncodedType = BarcodeLib.TYPE.ISBN
            ElseIf Cbo_L_E_Type.SelectedIndex = 17 Then
                LinearEncoder.EncodedType = BarcodeLib.TYPE.ITF14
            ElseIf Cbo_L_E_Type.SelectedIndex = 18 Then
                LinearEncoder.EncodedType = BarcodeLib.TYPE.JAN13
            ElseIf Cbo_L_E_Type.SelectedIndex = 19 Then
                LinearEncoder.EncodedType = BarcodeLib.TYPE.LOGMARS
            ElseIf Cbo_L_E_Type.SelectedIndex = 20 Then
                LinearEncoder.EncodedType = BarcodeLib.TYPE.Modified_Plessey
            ElseIf Cbo_L_E_Type.SelectedIndex = 21 Then
                LinearEncoder.EncodedType = BarcodeLib.TYPE.MSI_2Mod10
            ElseIf Cbo_L_E_Type.SelectedIndex = 22 Then
                LinearEncoder.EncodedType = BarcodeLib.TYPE.MSI_Mod10
            ElseIf Cbo_L_E_Type.SelectedIndex = 23 Then
                LinearEncoder.EncodedType = BarcodeLib.TYPE.MSI_Mod11
            ElseIf Cbo_L_E_Type.SelectedIndex = 24 Then
                LinearEncoder.EncodedType = BarcodeLib.TYPE.MSI_Mod11_Mod10
            ElseIf Cbo_L_E_Type.SelectedIndex = 25 Then
                LinearEncoder.EncodedType = BarcodeLib.TYPE.PHARMACODE
            ElseIf Cbo_L_E_Type.SelectedIndex = 26 Then
                LinearEncoder.EncodedType = BarcodeLib.TYPE.PostNet
            ElseIf Cbo_L_E_Type.SelectedIndex = 27 Then
                LinearEncoder.EncodedType = BarcodeLib.TYPE.Standard2of5
            ElseIf Cbo_L_E_Type.SelectedIndex = 28 Then
                LinearEncoder.EncodedType = BarcodeLib.TYPE.TELEPEN
            ElseIf Cbo_L_E_Type.SelectedIndex = 29 Then
                LinearEncoder.EncodedType = BarcodeLib.TYPE.UCC12
            ElseIf Cbo_L_E_Type.SelectedIndex = 30 Then
                LinearEncoder.EncodedType = BarcodeLib.TYPE.UCC13
            ElseIf Cbo_L_E_Type.SelectedIndex = 31 Then
                LinearEncoder.EncodedType = BarcodeLib.TYPE.UNSPECIFIED
            ElseIf Cbo_L_E_Type.SelectedIndex = 32 Then
                LinearEncoder.EncodedType = BarcodeLib.TYPE.UPC_SUPPLEMENTAL_2DIGIT
            ElseIf Cbo_L_E_Type.SelectedIndex = 33 Then
                LinearEncoder.EncodedType = BarcodeLib.TYPE.UPC_SUPPLEMENTAL_5DIGIT
            ElseIf Cbo_L_E_Type.SelectedIndex = 34 Then
                LinearEncoder.EncodedType = BarcodeLib.TYPE.UPCA
            ElseIf Cbo_L_E_Type.SelectedIndex = 35 Then
                LinearEncoder.EncodedType = BarcodeLib.TYPE.UPCE
            ElseIf Cbo_L_E_Type.SelectedIndex = 36 Then
                LinearEncoder.EncodedType = BarcodeLib.TYPE.USD8
            End If
            '
            '
            '
            Try   ' try to encode and report any errors
                '
                FontDialog1.FontMustExist = True           ' the font must actually exist on the system
                LinearEncoder.LabelFont = FontDialog1.Font ' set the label font
                '
                ' Encode the string into the barcode image
                '
                Linearimg = LinearEncoder.Encode(Cbo_L_E_Type.SelectedIndex, inputData)
                Linearbitmap = New Bitmap(Linearimg)
                Label9.Text = "Hashcode: " & LinearEncoder.GetHashCode
                '
                ' enable the label on form 2 to have the same hashcode
                Form_Viewer.Label1.Text = "Hashcode: " & LinearEncoder.GetHashCode
                barcodeImage = Linearbitmap
                '
                '
                X = Linearbitmap.Width               ' make Form_Viewer the right size
                Y = Linearbitmap.Height
                Form_Viewer.Width = X + buffer
                Form_Viewer.Height = Y + buffer
                '
            Catch ex As Exception
                MsgBox(ex.Message)  ' Catch any error and if yes then exit this sub
                Exit Sub
            End Try
            Form_Viewer.Show()      ' Show Form_Viewer (Form2)
          End If
          '
        End If
        '
        '
        ' QR Barcodes
        '
        If QRcode = True Then

            If Txt_InputData.Text.Length <= 0 Then
                MsgBox("You must Include the data to be Encoded.", MsgBoxStyle.OkOnly, "Data Error")
            Else

                QREncoder = New ThoughtWorks.QRCode.Codec.QRCodeEncoder       ' Declare a new QREncoder
                QREncoder.QRCodeForegroundColor = QR_foreColor
                QREncoder.QRCodeBackgroundColor = QR_backColor
                QREncoder.QRCodeScale = Cbo_QR_Scale.SelectedItem.ToString     ' QR scale
                QREncoder.QRCodeVersion = Cbo_QR_Version.SelectedItem.ToString ' QR version
                ' QR version is recomended to be a 6 this is because most barcode scanners
                ' are on mobile devices and version 6 is readable by most if not all scanners
                '
                ' QR Encode type
                '
                If Cbo_QR_Mode.SelectedIndex = 0 Then
                    QREncoder.QRCodeEncodeMode = QRCodeEncoder.ENCODE_MODE.ALPHA_NUMERIC
                ElseIf Cbo_QR_Mode.SelectedIndex = 1 Then
                    QREncoder.QRCodeEncodeMode = QRCodeEncoder.ENCODE_MODE.BYTE
                ElseIf Cbo_QR_Mode.SelectedIndex = 2 Then
                    QREncoder.QRCodeEncodeMode = QRCodeEncoder.ENCODE_MODE.NUMERIC
                End If
                '
                ' QR Error Correction
                '
                If Cbo_QR_ErrorC.SelectedIndex = 0 Then
                    QREncoder.QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.L
                ElseIf Cbo_QR_ErrorC.SelectedIndex = 1 Then
                    QREncoder.QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.M
                ElseIf Cbo_QR_ErrorC.SelectedIndex = 2 Then
                    QREncoder.QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.Q
                ElseIf Cbo_QR_ErrorC.SelectedIndex = 2 Then
                    QREncoder.QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.H
                End If
                '
                Try
                    QRimg = QREncoder.Encode(inputData)
                    QRbitmap = New Bitmap(QRimg)
                    barcodeImage = QRbitmap
                    Form_Viewer.Label1.Text = "Hashcode: " & QREncoder.GetHashCode
                    Label10.Text = "Hashcode: " & QREncoder.GetHashCode
                    '
                    '
                    X = QRbitmap.Width                ' make Form_Viewer the right size
                    Y = QRbitmap.Height
                    Form_Viewer.Width = X + buffer
                    Form_Viewer.Height = Y + buffer
                    '
                Catch ex As Exception
                    MsgBox(ex.Message)   ' Catch any errors and exit sub
                    Exit Sub
                End Try
                Form_Viewer.Show()       ' show Form_Viewer (Form2)
            End If
            '
        End If
            '
        '-------------------------------
        '
        ' Note that Transparency does Not work
        ' with Data Matrix Codes the resulting image will be black
        '
        ' Data Matrix Barcodes
        '          
        If Datacode = True Then

            If Txt_InputData.Text.Length <= 0 Then
                MsgBox("You must Include the data to be Encoded.", MsgBoxStyle.OkOnly, "Data Error")
            Else
                '
                ' Note for Data Matrix all the options are inside the TRY Block
                ' this is because the data matrix encoder not only takes in the string
                ' to be encoded but the options aswell
                '
                Try 'Encode
                    DataEncoder = New DataMatrix.net.DmtxImageEncoder
                    DataEncodeOptions = New DataMatrix.net.DmtxImageEncoderOptions
                    'Options-----------------------------------
                    '
                    ' size options
                    '
                    If Cbo_D_Size.SelectedIndex = 0 Then
                        DataEncodeOptions.SizeIdx = DataMatrix.net.DmtxSymbolSize.DmtxSymbol8x18
                    ElseIf Cbo_D_Size.SelectedIndex = 1 Then
                        DataEncodeOptions.SizeIdx = DataMatrix.net.DmtxSymbolSize.DmtxSymbol8x32
                    ElseIf Cbo_D_Size.SelectedIndex = 2 Then
                        DataEncodeOptions.SizeIdx = DataMatrix.net.DmtxSymbolSize.DmtxSymbol10x10
                    ElseIf Cbo_D_Size.SelectedIndex = 3 Then
                        DataEncodeOptions.SizeIdx = DataMatrix.net.DmtxSymbolSize.DmtxSymbol12x12
                    ElseIf Cbo_D_Size.SelectedIndex = 4 Then
                        DataEncodeOptions.SizeIdx = DataMatrix.net.DmtxSymbolSize.DmtxSymbol12x26
                    ElseIf Cbo_D_Size.SelectedIndex = 5 Then
                        DataEncodeOptions.SizeIdx = DataMatrix.net.DmtxSymbolSize.DmtxSymbol12x36
                    ElseIf Cbo_D_Size.SelectedIndex = 6 Then
                        DataEncodeOptions.SizeIdx = DataMatrix.net.DmtxSymbolSize.DmtxSymbol14x14
                    ElseIf Cbo_D_Size.SelectedIndex = 7 Then
                        DataEncodeOptions.SizeIdx = DataMatrix.net.DmtxSymbolSize.DmtxSymbol16x16
                    ElseIf Cbo_D_Size.SelectedIndex = 8 Then
                        DataEncodeOptions.SizeIdx = DataMatrix.net.DmtxSymbolSize.DmtxSymbol16x36
                    ElseIf Cbo_D_Size.SelectedIndex = 9 Then
                        DataEncodeOptions.SizeIdx = DataMatrix.net.DmtxSymbolSize.DmtxSymbol16x48
                    ElseIf Cbo_D_Size.SelectedIndex = 10 Then
                        DataEncodeOptions.SizeIdx = DataMatrix.net.DmtxSymbolSize.DmtxSymbol18x18
                    ElseIf Cbo_D_Size.SelectedIndex = 11 Then
                        DataEncodeOptions.SizeIdx = DataMatrix.net.DmtxSymbolSize.DmtxSymbol20x20
                    ElseIf Cbo_D_Size.SelectedIndex = 12 Then
                        DataEncodeOptions.SizeIdx = DataMatrix.net.DmtxSymbolSize.DmtxSymbol22x22
                    ElseIf Cbo_D_Size.SelectedIndex = 13 Then
                        DataEncodeOptions.SizeIdx = DataMatrix.net.DmtxSymbolSize.DmtxSymbol24x24
                    ElseIf Cbo_D_Size.SelectedIndex = 14 Then
                        DataEncodeOptions.SizeIdx = DataMatrix.net.DmtxSymbolSize.DmtxSymbol26x26
                    ElseIf Cbo_D_Size.SelectedIndex = 15 Then
                        DataEncodeOptions.SizeIdx = DataMatrix.net.DmtxSymbolSize.DmtxSymbol32x32
                    ElseIf Cbo_D_Size.SelectedIndex = 16 Then
                        DataEncodeOptions.SizeIdx = DataMatrix.net.DmtxSymbolSize.DmtxSymbol36x36
                    ElseIf Cbo_D_Size.SelectedIndex = 17 Then
                        DataEncodeOptions.SizeIdx = DataMatrix.net.DmtxSymbolSize.DmtxSymbol40x40
                    ElseIf Cbo_D_Size.SelectedIndex = 18 Then
                        DataEncodeOptions.SizeIdx = DataMatrix.net.DmtxSymbolSize.DmtxSymbol44x44
                    ElseIf Cbo_D_Size.SelectedIndex = 19 Then
                        DataEncodeOptions.SizeIdx = DataMatrix.net.DmtxSymbolSize.DmtxSymbol48x48
                    ElseIf Cbo_D_Size.SelectedIndex = 20 Then
                        DataEncodeOptions.SizeIdx = DataMatrix.net.DmtxSymbolSize.DmtxSymbol52x52
                    ElseIf Cbo_D_Size.SelectedIndex = 21 Then
                        DataEncodeOptions.SizeIdx = DataMatrix.net.DmtxSymbolSize.DmtxSymbol64x64
                    ElseIf Cbo_D_Size.SelectedIndex = 22 Then
                        DataEncodeOptions.SizeIdx = DataMatrix.net.DmtxSymbolSize.DmtxSymbol72x72
                    ElseIf Cbo_D_Size.SelectedIndex = 23 Then
                        DataEncodeOptions.SizeIdx = DataMatrix.net.DmtxSymbolSize.DmtxSymbol80x80
                    ElseIf Cbo_D_Size.SelectedIndex = 24 Then
                        DataEncodeOptions.SizeIdx = DataMatrix.net.DmtxSymbolSize.DmtxSymbol88x88
                    ElseIf Cbo_D_Size.SelectedIndex = 25 Then
                        DataEncodeOptions.SizeIdx = DataMatrix.net.DmtxSymbolSize.DmtxSymbol96x96
                    ElseIf Cbo_D_Size.SelectedIndex = 26 Then
                        DataEncodeOptions.SizeIdx = DataMatrix.net.DmtxSymbolSize.DmtxSymbolRectAuto
                    ElseIf Cbo_D_Size.SelectedIndex = 27 Then
                        DataEncodeOptions.SizeIdx = DataMatrix.net.DmtxSymbolSize.DmtxSymbolShapeAuto
                    ElseIf Cbo_D_Size.SelectedIndex = 28 Then
                        DataEncodeOptions.SizeIdx = DataMatrix.net.DmtxSymbolSize.DmtxSymbolSquareAuto
                    End If
                    '
                    '
                    ' scheme options
                    '
                    If Cbo_D_Scheme.SelectedIndex = 0 Then
                        DataEncodeOptions.Scheme = DataMatrix.net.DmtxScheme.DmtxSchemeAscii
                    ElseIf Cbo_D_Size.SelectedIndex = 1 Then
                        DataEncodeOptions.Scheme = DataMatrix.net.DmtxScheme.DmtxSchemeAsciiGS1
                    ElseIf Cbo_D_Size.SelectedIndex = 2 Then
                        DataEncodeOptions.Scheme = DataMatrix.net.DmtxScheme.DmtxSchemeAutoBest
                    ElseIf Cbo_D_Size.SelectedIndex = 3 Then
                        DataEncodeOptions.Scheme = DataMatrix.net.DmtxScheme.DmtxSchemeAutoFast
                    ElseIf Cbo_D_Size.SelectedIndex = 4 Then
                        DataEncodeOptions.Scheme = DataMatrix.net.DmtxScheme.DmtxSchemeBase256
                    ElseIf Cbo_D_Size.SelectedIndex = 5 Then
                        DataEncodeOptions.Scheme = DataMatrix.net.DmtxScheme.DmtxSchemeC40
                    ElseIf Cbo_D_Size.SelectedIndex = 6 Then
                        DataEncodeOptions.Scheme = DataMatrix.net.DmtxScheme.DmtxSchemeEdifact
                    ElseIf Cbo_D_Size.SelectedIndex = 7 Then
                        DataEncodeOptions.Scheme = DataMatrix.net.DmtxScheme.DmtxSchemeText
                    ElseIf Cbo_D_Size.SelectedIndex = 8 Then
                        DataEncodeOptions.Scheme = DataMatrix.net.DmtxScheme.DmtxSchemeX12
                    End If
                    '
                    ' module size options
                    '
                    If Cbo_D_Module.SelectedIndex = 0 Then
                        DataEncodeOptions.ModuleSize = 1
                    ElseIf Cbo_D_Module.SelectedIndex = 1 Then
                        DataEncodeOptions.ModuleSize = 2
                    ElseIf Cbo_D_Module.SelectedIndex = 2 Then
                        DataEncodeOptions.ModuleSize = 3
                    ElseIf Cbo_D_Module.SelectedIndex = 3 Then
                        DataEncodeOptions.ModuleSize = 4
                    ElseIf Cbo_D_Module.SelectedIndex = 4 Then
                        DataEncodeOptions.ModuleSize = 5
                    ElseIf Cbo_D_Module.SelectedIndex = 5 Then
                        DataEncodeOptions.ModuleSize = 6
                    ElseIf Cbo_D_Module.SelectedIndex = 6 Then
                        DataEncodeOptions.ModuleSize = 7
                    ElseIf Cbo_D_Module.SelectedIndex = 7 Then
                        DataEncodeOptions.ModuleSize = 8
                    ElseIf Cbo_D_Module.SelectedIndex = 8 Then
                        DataEncodeOptions.ModuleSize = 9
                    ElseIf Cbo_D_Module.SelectedIndex = 9 Then
                        DataEncodeOptions.ModuleSize = 10
                    End If
                    '
                    ' margin size options
                    '
                    If Cbo_D_Margin.SelectedIndex = 0 Then
                        DataEncodeOptions.MarginSize = 1
                    ElseIf Cbo_D_Margin.SelectedIndex = 1 Then
                        DataEncodeOptions.MarginSize = 2
                    ElseIf Cbo_D_Margin.SelectedIndex = 2 Then
                        DataEncodeOptions.MarginSize = 3
                    ElseIf Cbo_D_Margin.SelectedIndex = 3 Then
                        DataEncodeOptions.MarginSize = 4
                    ElseIf Cbo_D_Margin.SelectedIndex = 4 Then
                        DataEncodeOptions.MarginSize = 5
                    End If
                    '
                    DataEncodeOptions.ForeColor = DM_forecolour
                    DataEncodeOptions.BackColor = DM_backcolour
                    '---------------------------
                    '
                    ' DataEncoder takes the inputdata string AND the DataEncode Options
                    '
                    Dataimg = DataEncoder.EncodeImage(inputData, DataEncodeOptions)
                    Databitmap = New Bitmap(Dataimg)
                    barcodeImage = Databitmap
                    Label12.Text = "Hashcode: " & DataEncoder.GetHashCode
                    Form_Viewer.Label1.Text = "Hashcode: " & DataEncoder.GetHashCode
                    '                   
                    '
                    '
                    X = Databitmap.Width              ' when Form_Viewer opens make the window
                    Y = Databitmap.Height             ' the right size
                    Form_Viewer.Width = X + buffer
                    Form_Viewer.Height = Y + buffer
                    '
                Catch ex As Exception
                    MsgBox(ex.Message)
                    Exit Sub
                End Try
                Form_Viewer.Show()
                '
            End If
            '
        End If
        '
    End Sub

Código del Form_Viewer

'    
    Dim CodeBitmap As Bitmap        ' declare a new bitmap
    Dim SFD As SaveFileDialog       ' delcare a save file dialog box
    '---------------------------------------
    '
    '
    Private Sub Form_Viewer_FormClosed(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosedEventArgs) Handles Me.FormClosed
        '
        ' Do this when this form closes
        '
        Form1.Label9.Text = ""
        Form1.Label10.Text = ""
        Form1.Label12.Text = ""
    End Sub
    '
    '
    '
    Private Sub Form_Viewer_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        '
        ' make a new savefile dialog
        SFD = New SaveFileDialog
        '
        ' savefiledialog filter (save types)
        '
       SFD.Filter = "Bmp (*.bmp) |*.bmp | Jpeg (*.jpg)|*.jpg | PNG (*.png)|*.png | TIFF (*.tiff)|*.tiff"
        '
        '
        ComboBox1.SelectedIndex = 2      ' auto select a save type on load
        SFD.AddExtension = True          ' will this savefile dialog add an extension to the filename
        '
        PicBox1.BackgroundImage = Form1.barcodeImage
        CodeBitmap = New Bitmap(Form1.barcodeImage)
        '
    End Sub
    '
    '
    ' Save Button
    '
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        '
        '
        If ComboBox1.SelectedIndex = 0 Then
            SFD.FilterIndex = 1
        ElseIf ComboBox1.SelectedIndex = 1 Then
            SFD.FilterIndex = 2
        ElseIf ComboBox1.SelectedIndex = 2 Then
            SFD.FilterIndex = 3
        ElseIf ComboBox1.SelectedIndex = 3 Then
            SFD.FilterIndex = 4
        ElseIf ComboBox1.SelectedIndex = 4 Then
            SFD.FilterIndex = 5
        End If
        '
        If SFD.ShowDialog = Windows.Forms.DialogResult.OK Then   ' Save the image to your choice of
            CodeBitmap.Save(SFD.FileName)                        ' location
        End If
        '
    End Sub

 

COMPARTE ESTE ARTÍCULO

COMPARTIR EN FACEBOOK
COMPARTIR EN TWITTER
COMPARTIR EN LINKEDIN
COMPARTIR EN WHATSAPP