2012年11月7日 星期三

Use ZXing library to decode/encode 2D barcode


Using ZXing in c#

How to decode a 2D barcode into text

The code snippet:
try
{
    // Get the width and height of the bitmap, 
    //and change it to a WriteableBitmap object
    int width = mBitmap.PixelWidth; 
    int height = mBitmap.PixelHeight;
    WriteableBitmap writableBitmap = new WriteableBitmap(mBitmap);

    // use RGBLuminanceSource and HybridBinarizer class to
    // process the WriteableBitmap into a BinaryBitmap
    var lsource = new RGBLuminanceSource(writableBitmap, width, height);
    Binarizer zer = new HybridBinarizer(lsource);
    BinaryBitmap binaryBitmap = new BinaryBitmap(zer);

    // Decode the binaryBitmap useing the QRCodeReader object
    QRCodeReader qrReader = new QRCodeReader();
    Result result = qrReader.decode(binaryBitmap);

    // the decoded text in place in the Result object.
    Title.Text = result.Text;
}
catch (Exception ex) // catch the exception here!!!
{
    System.Diagnostics.Debug.WriteLine(ex);
}

How to encode a text into a 2D barcode

The library will encode the text into ZXing-defined ByteMatrix. Here is the code snippet:

string encodeText = TextToEncode.Text;
if (!String.IsNullOrEmpty(encodeText))
{
    // use MultiFormatWriter class to encode.
    var qrCodeWriter = new MultiFormatWriter();
    var matrix = qrCodeWriter.encode(TextToEncode.Text, 
                                     BarcodeFormat.QR_CODE, 400, 400);

    var bitmap = ToBitmap(matrix);
    resultImage.Source = bitmap;
}

Then, ToBitmap() function is used to get the BitmapImage object from the ByteMatrix:

private WriteableBitmap ToBitmap(ByteMatrix aMatrix)
{
    int width = aMatrix.Width;
    int height = aMatrix.Height;
    var bitmap = new WriteableBitmap(width, height);
    for (int x = 0; x < width; x++)
    {
        for (int y = 0; y < height; y++)
        {
            if (aMatrix.get_Renamed(x, y) == -1)
            {
                bitmap.Pixels[y * width + x] =
                   BitConverter.ToInt32(BitConverter.GetBytes(0xffffffff), 0);
            }else
            {
                bitmap.Pixels[y * width + x] =
                   BitConverter.ToInt32(BitConverter.GetBytes(0x00000000), 0);
            }
        }
    }
    return bitmap;
}

沒有留言:

張貼留言