ZXing-Core BitMatrix to BitMap

Viewed 5884

I am using ZXing-Core(0.14.0.2) to create a barcode which gives me a BitMatrix, however I have not found documentation as to how to extract the image part from the BitMatrix and use it as BitMap so I can incorporate in my bigger image. Eventually what I would like to end up with would be something like this:

White Image With Barcode at the bottom

The code I currently have is:

img = new Bitmap(300, 375);
drawing = Graphics.FromImage(img);
var barCode = new Code128Writer().encode(packageModel.TrackingId.PrintValue, BarcodeFormat.CODE_128, 280, 70);
src = transform **barCode** to **Drawing.Image**
drawing.DrawImage(src, new Rectangle(10, 255, 280, 70));

UPDATE I now have this code, however I am getting an error You have to set a renderer instance. I dont understand why the interface is not instantiating this class by itself. There is not documentation available revealing how this is supposed to work. I cant use the Write functions because the Rendering is set to null, however I am not sure how to instantiate it.

IBarcodeWriterGeneric<Image> barcodeWriterGeneric = new BarcodeWriterGeneric<Image>
{

      Format = BarcodeFormat.CODE_128,
      Options = new EncodingOptions
      {
            Width = 280,
            Height = 70
      },
      Renderer = new PixelData() //HOW DOES THE RENDERER WORK????
};

var test = barcodeWriterGeneric.Write("WORKS");
drawing.DrawImage(test, new Rectangle(10, 255, 280, 70));
2 Answers

Create a renderer that implements IBarcodeRenderer<TOut>. This one works for me in iOS.

var writer = new BarcodeWriter<UIImage>()
{
    Format = ZXing.BarcodeFormat.CODE_128,
    Options = new EncodingOptions
    {
        Height = height,
        Width = width,
        Margin = 0
    },
    Renderer = new BarcodeRenderer()
};

var image = writer.Write(barcodeValue);



private class BarcodeRenderer : IBarcodeRenderer<UIImage>
{
    public UIImage Render(BitMatrix matrix, ZXing.BarcodeFormat format, string content)
    {
        return RenderMatrix(matrix);
    }

    public UIImage Render(BitMatrix matrix, ZXing.BarcodeFormat format, string content, EncodingOptions options)
    {
        return RenderMatrix(matrix);
    }
}

/// <summary>
/// Renders the bitmatrix.
/// </summary>
private static UIImage RenderMatrix(BitMatrix matrix)
{
    var width = matrix.Width;
    var height = matrix.Height;

    var black = new CGColor(0f, 0f, 0f);
    var white = new CGColor(1.0f, 1.0f, 1.0f);

    UIGraphics.BeginImageContext(new CGSize(width, height));
    var context = UIGraphics.GetCurrentContext();

    for (var x = 0; x < width; x++)
    {
        for (var y = 0; y < height; y++)
        {
            context.SetFillColor(matrix[x, y] ? black : white);
            context.FillRect(new CGRect(x, y, 1, 1));
        }
    }

    var img = UIGraphics.GetImageFromCurrentImageContext();

    UIGraphics.EndImageContext();

    return img;
}
Related