How create barcode image using c#?

21,860

Solution 1

Here's some code I used for a recent project. It requires you downloading and installing the barcode font code39.

    private static void CreateBarcode(string code)
    {
        var myBitmap = new Bitmap(500,50);
        var g = Graphics.FromImage(myBitmap);
        var jgpEncoder = GetEncoder(ImageFormat.Jpeg);

        g.Clear(Color.White);

        var strFormat = new StringFormat {Alignment = StringAlignment.Center};
        g.DrawString(code, new Font("Free 3 of 9", 50), Brushes.Black, new RectangleF(0, 0, 500, 50), strFormat);

        var myEncoder = Encoder.Quality;
        var myEncoderParameters = new EncoderParameters(1);

        var myEncoderParameter = new EncoderParameter(myEncoder, 100L);
        myEncoderParameters.Param[0] = myEncoderParameter;
        myBitmap.Save(@"c:\Barcode.jpg", jgpEncoder, myEncoderParameters);
    }

    private static ImageCodecInfo GetEncoder(ImageFormat format)
    {

        var codecs = ImageCodecInfo.GetImageDecoders();

        foreach (var codec in codecs)
        {
            if (codec.FormatID == format.Guid)
            {
                return codec;
            }
        }
        return null;
    } 

Hope this helps.

Solution 2

C# Barcode Generator WebService

Creating EAN-13 Barcodes with C#

Solution 3

A barcode is really just a font. If you use a barcode font and provide a valid text value, the barcode will render correctly.

The barcode that I've had the most experience with is the 3 of 9 barcode. It had encodings for 0-9, A-Z and a few other characters. If you have the font for this barcode, you simply render the text (e.g. 'abc123') in that font and it will be encoded. There's nothing else to do!

The question needs more information to determine how you are using the barcode.

Share:
21,860
Akshay
Author by

Akshay

Updated on July 24, 2022

Comments

  • Akshay
    Akshay almost 2 years

    I want to create a barcode image, from an employee record using C#.

  • PUG
    PUG over 11 years
    I plugged the code in as it is, gives A generic error occurred in GDI+. exception. And I am pretty sure font is installed
  • Ash Burlaczenko
    Ash Burlaczenko over 11 years
    @jaminator, which line causes you a problem?
  • PUG
    PUG over 11 years
    My bad, It was not the code, its asp.net not having permission to write a file; now I am just doing response.write that image
  • informeto
    informeto about 5 years
    I am not able to scan the barcodes printed with the above logic. What could be the issue?