如何在Windows Phone 8.1上使用Zxing创建QR码图像

时间:2015-01-16 13:02:51

标签: c# windows-phone-8.1 barcode zxing barcode-printing

我一直在网上搜索Windows Phone 8.1中使用Zxing的代码示例,但是很简单。我用C#编写,下面是我的代码,到目前为止我已经提出了这个代码:

BarcodeWriter _writer = new BarcodeWriter();

var hello =  _writer.Encoder.encode("HelloWhoIsThere", BarcodeFormat.QR_CODE, 350, 350);

ZXing.Common.BitMatrix matrix = new ZXing.Common.BitMatrix(359,350);

ZXing.Rendering.PixelData rendered = _writer.Renderer.Render(hello, BarcodeFormat.CODE_128, "HelloWhoIsThere");

byte[] byte1 = rendered.Pixel;

Stream memStream = new MemoryStream(byte1);

memStream.Position = 0;

BitmapDecoder decoder = await BitmapDecoder.CreateAsync(memStream.AsRandomAccessStream());

// create a new stream and encoder for the new image
InMemoryRandomAccessStream mrAccessStream = new InMemoryRandomAccessStream();
BitmapEncoder encoder = await BitmapEncoder.CreateForTranscodingAsync(mrAccessStream, decoder);

// convert the bitmap to a 400px by 400px bitmap
encoder.BitmapTransform.ScaledHeight = 350;
encoder.BitmapTransform.ScaledWidth = 350;

// write out to the stream
try
{
    await encoder.FlushAsync();
}
catch (Exception ex)
{
    string s = ex.ToString();
}

// render the stream to the screen
WB = new WriteableBitmap(350, 350);
WB.SetSource(mrAccessStream);
if (WB != null)
{
    SelectedImage.Source = WB;
}
if (WB == null)
{
    txtDecoderContent.Text = "WB = null";
}

我收到错误“System.NullReferenceException:对象引用未设置为对象的实例。”我认为当我尝试将渲染的QR码转换为byte []时会发生这种情况。

感谢您的帮助,谢谢

1 个答案:

答案 0 :(得分:6)

<强> usings

using ZXing;
using Windows.UI.Xaml.Media.Imaging;

<强>码

IBarcodeWriter writer = new BarcodeWriter
            {
                Format = BarcodeFormat.QR_CODE,
                Options = new ZXing.Common.EncodingOptions
                {
                    Height = 300,
                    Width = 300
                }
            };
var result = writer.Write("generator works");
var wb = result.ToBitmap() as WriteableBitmap;

//add to image component
image.Source = wb;

更简单和有效(在我的一个应用程序中测试过)