user9945420
user9945420

Reputation:

Colorize barcode bitmap by Color

I'm generating barcodes using ZXing.NET with this code

BarcodeWriter barcodeWriter = new BarcodeWriter
{
    Format = BarcodeFormat,
    Options = new EncodingOptions
    {
        Width = barCodeWidth,
        Height = barCodeHeight,
        PureBarcode = !GenerateBarCodeWithText
    }
};

Bitmap barCodeBitmap = barcodeWriter.Write(content);

So currently each barcode (and with text) is just black. Is there a way I can pass in a Color object to colorize the barcode and text red for example? I tried this hacky solution to get the current pixel color, check if it's white and if not, colorize it to the specified font color.

for (int x = 0; x < barCodeBitmap.Width; x++)
{
    for (int y = 0; y < barCodeBitmap.Height; y++)
    {
        Color currentColor = barCodeBitmap.GetPixel(x, y);
        bool isWhite = currentColor == Color.White;

        if (!isWhite) // this pixel should get a new color
        {
            barCodeBitmap.SetPixel(x, y, fontColor); // set a new color
        }
    }
}

Unfortunately each pixel gets colorized..

Upvotes: 0

Views: 1178

Answers (1)

Michael
Michael

Reputation: 2506

For colorizing the whole code (including the text) you can use the following snippet:

BarcodeWriter barcodeWriter = new BarcodeWriter
{
   Format = BarcodeFormat,
   Options = new EncodingOptions
   {
      Width = barCodeWidth,
      Height = barCodeHeight,
      PureBarcode = !GenerateBarCodeWithText
   },
   Renderer = new BitmapRenderer
   {
      Foreground = Color.Red
   }
};

Bitmap barCodeBitmap = barcodeWriter.Write(content);

If you want different colors for the barcode and the text you have to write your own renderer implementation and use this instead of the BitmapRenderer. You can take a look at the sources of BitmapRenderer and use it as a template for your own implementation:

https://github.com/micjahn/ZXing.Net/blob/master/Source/lib/renderer/BitmapRenderer.cs

Add a new property "TextColor" for example and use it in the line

var brush = new SolidBrush(Foreground);

changed to

var brush = new SolidBrush(TextColor);

Upvotes: 2

Related Questions