Click here to Skip to main content
15,891,204 members
Articles / Programming Languages / C#
Tip/Trick

Simple Source Code for Generating '2 of 5 Interleaved' Image Barcode

Rate me:
Please Sign up or sign in to vote.
5.00/5 (5 votes)
2 Jun 2016CPOL 16.9K   3   1
Simple class (component-free, TrueTypeFont-free) to generate an image with a 2of5int barcode

Introduction

Nowadays, it's somehow hard to find a simple and proper solution if you need to generate a barcode image using the '2 of 5 interleaved' pattern. Most of the approaches around use commercial TrueType fonts, or third-party components.

This is a regular C# class that uses only basic approaches to receive an numeric value (the amount of digits must be even) and generate a System.Drawing.Image with the barcode.

Using the Code

Include this class into your solution:

C#
public static class Int2of5
{
    private static string Encode(string Data)
    {
        try
        {
            //0 = thin
            //1 = thick
            IDictionary<int, string> NumbersMapping = new Dictionary<int, string>();
            NumbersMapping.Add(0, "00110");
            NumbersMapping.Add(1, "10001");
            NumbersMapping.Add(2, "01001");
            NumbersMapping.Add(3, "11000");
            NumbersMapping.Add(4, "00101");
            NumbersMapping.Add(5, "10100");
            NumbersMapping.Add(6, "01100");
            NumbersMapping.Add(7, "00011");
            NumbersMapping.Add(8, "10010");
            NumbersMapping.Add(9, "01010");

            if (string.IsNullOrEmpty(Data)) throw new Exception("No data received");
            if (!Data.All(char.IsDigit)) throw new Exception("Only numbers are accepted");
            if (Data.Length % 2 != 0) throw new Exception("Number os digits have to be even");

            IList<KeyValuePair<int, string>> Digits = new List<KeyValuePair<int, string>>();
            for (int i = 0; i < Data.Length; i++)
            {
                int key = Convert.ToInt32(Data[i].ToString());
                string value = NumbersMapping[Convert.ToInt32(Data[i].ToString())];

                Digits.Add(new KeyValuePair<int, string>(Convert.ToInt32(Data[i].ToString()),
                           NumbersMapping[Convert.ToInt32(Data[i].ToString())]));
            }

            string Result = string.Empty;
            for (int i = 0; i < Digits.Count; i+=2)
            {
                string Pair1 = Digits[i].Value;
                string Pair2 = Digits[i+1].Value;

                //Pair 1 e 2 will get interleaved
                //Pair 1 = will be bars
                //Pair 2 = will be spaces
                //Pseudo-codes:
                //A = thin space
                //B = thick space
                //X = thin bar
                //Y = thick bar
                for (int j = 0; j < 5; j++)
                    Result += (Pair1[j].ToString() == "0" ? "X" : "Y") +
                              (Pair2[j].ToString() == "0" ? "A" : "B");
            }

            //Append start and ending
            return "XAXA" + Result + "YAX";
        }
        catch (Exception ex)
        {
            return "#" + ex.Message;
        }
    }

    public static Image GenerateBarCode(string Data, int Width, int Height, int ScaleFactor)
    {
        try
        {
            string EncodedData = Encode(Data);
            if (string.IsNullOrEmpty(EncodedData))
                throw new Exception("Encoding process returned empty");
            if (EncodedData[0].ToString() == "#") throw new Exception(EncodedData);

            int Position = 20, ThinWidth = 1 * ScaleFactor, ThickWidth = 3 * ScaleFactor;
            Image img = new System.Drawing.Bitmap(Width, Height);
            using (Graphics gr = Graphics.FromImage(img))
            {
                //Initial white color filling
                gr.FillRectangle(Brushes.White, 0, 0, Width, Height);

                for (int i = 0; i < EncodedData.Length; i++)
                {
                    //Replace the pseudo-codes with bars or spaces
                    switch (EncodedData[i].ToString())
                    {
                        case "A":
                            gr.FillRectangle(System.Drawing.Brushes.White,
                                             Position, 0, ThinWidth, Height);
                            Position += ThinWidth;
                            break;
                        case "B":
                            gr.FillRectangle(System.Drawing.Brushes.White,
                                             Position, 0, ThickWidth, Height);
                            Position += ThickWidth;
                            break;
                        case "X":
                            gr.FillRectangle(System.Drawing.Brushes.Black,
                                             Position, 0, ThinWidth, Height);
                            Position += ThinWidth;
                            break;
                        case "Y":
                            gr.FillRectangle(System.Drawing.Brushes.Black,
                                             Position, 0, ThickWidth, Height);
                            Position += ThickWidth;
                            break;
                    }
                }
                return img;
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
}

Call the method <GenerateBarCode>, passing the numeric data, the desired width and height of the image, and the scale-size factor, like this:

C#
new PictureBox().Image = 
  Int2of5.GenerateBarCode("34191183400000292011090000107160253500375000", 1000, 100, 2);

Points of Interest

With this simple solution, you can embed a rich quality barcode into your application, with no need to buy expensive components, saving time and money.

History

  • 2nd June, 2016: Initial version

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionMany Thanks for sharing, it helped me a lot! Pin
Member 1480301718-Mar-21 15:29
Member 1480301718-Mar-21 15:29 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.