Get Barcode Bitmap - CSharp System.Drawing

CSharp examples for System.Drawing:Image Convert

Description

Get Barcode Bitmap

Demo Code

// Bitcoin Address Utility is free software: you can redistribute it and/or modify
using System.Drawing;
using System.Text;
using System.Linq;
using System.Collections.Generic;
using System;//from  w w  w .java2s  .c om

public class Main{
        public static Bitmap GetBarcode(string message) {

            int pixelspermodule = 1;
            int margininmodules = 12;
            int heightinmodules = 30;

            string pattern = getPatternsForMessage(message);

            // get number of modules.  Pretty simple, just add up all the digits in the pattern.
            int modulecount=0;
            foreach (char c in pattern.ToCharArray()) modulecount += (c - '0');

            int neededWidth = pixelspermodule * (margininmodules + margininmodules + modulecount);
            int neededHeight = pixelspermodule * heightinmodules;
            Bitmap b = new Bitmap(neededWidth + 1, neededHeight + 1);
            SolidBrush brush = new SolidBrush(Color.White);

            Graphics gr = Graphics.FromImage(b);
            
            // start with a white background
            gr.FillRectangle(brush, new Rectangle(0, 0, neededWidth, neededHeight));

            brush.Color = Color.Black;

            int currentmodule = margininmodules;
            bool nowBlack = true;
            foreach (char c in pattern.ToCharArray()) {
                int modulewidth = (c - '0');
                if (nowBlack) {
                    gr.FillRectangle(brush, currentmodule * pixelspermodule, 0, modulewidth * pixelspermodule, neededHeight);
                }
                nowBlack = !nowBlack;
                currentmodule += modulewidth;
            }

            return b;
        }
}

Related Tutorials