使用ZXing 2.0 C#Port在Windows Phone 7.1上生成QR代码

我在使用ZXing 2.0在mango 7.1上生成QR码时遇到了麻烦。 它应该是非常直接的,但它不起作用。

代码:

QRCodeWriter writer = new QRCodeWriter(); var bMatrix = writer.encode("Hey dude, QR FTW!", BarcodeFormat.QR_CODE, 25, 25); var asBitmap = bMatrix.ToBitmap(); image1.Source = asBitmap; 

image1来自xaml。

bMatrix似乎包含了我需要的数据,但是image1从未显示过。

所以我设法做了一个解决方法。 我不确定我的原始代码是否因为ZXing C#端口中的错误或者我做错了而无法正常工作。 无论如何,这是我做的显示QR码。

image1来自xaml。

 QRCodeWriter writer = new QRCodeWriter(); var bMatrix = writer.encode("Hey dude! QR FTW!", BarcodeFormat.QR_CODE, width, height); WriteableBitmap wbmi = new System.Windows.Media.Imaging.WriteableBitmap(width, height); for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { int grayValue = bMatrix.Array[y][x] & 0xff; if (grayValue == 0) wbmi.SetPixel(x, y, Color.FromArgb(255, 0, 0,0)); else wbmi.SetPixel(x, y, Color.FromArgb(255, 255, 255, 255)); } } image1.Source = wbmi; 

尝试像这样设置图像源:

 image1 = new ImageBrush { ImageSource = asBitmap ;} 

我遇到了同样的问题。 将WriteableBitmap直接分配给Image.Source不起作用。 经过一些搜索后,我找到了一个强化解决方法,它使用SaveJpeg方法将WritableBitap写入MemoryStream:

  using (MemoryStream ms = new MemoryStream()) { asBitmap.SaveJpeg(ms, (int)asBitmap.PixelWidth, (int)asBitmap.PixelHeight, 0, 100); BitmapImage bmp = new BitmapImage(); bmp.SetSource(ms); Image.Source = bmp; } 

除非QR码以深蓝色/浅蓝色显示,而不是黑/白,否则这种情况有效。 告诉他这个朋友他重新认为在Windows手机中像素颜色不是字节,而是整数。 凭借这些知识和zxing的来源,我改变了ByteMatrix.ToBitmap方法,如下所示:

  public WriteableBitmap ToBitmap() { const int BLACK = 0; const int WHITE = -1; sbyte[][] array = Array; int width = Width; int height = Height; var pixels = new byte[width*height]; var bmp = new WriteableBitmap(width, height); for (int y = 0; y < height; y++) { int offset = y*width; for (int x = 0; x < width; x++) { int c = array[y][x] == 0 ? BLACK : WHITE; bmp.SetPixel(x, y, c); } } //Return the bitmap return bmp; } 

这解决了这个问题,甚至将WritableBitmap直接分配给Image.Source。 似乎图像被正确分配,但alpha值是透明的,在创建jpeg时删除了。

最简单的解决方案:

 Uri uri = new Uri("http://www.esponce.com/api/v3/generate?content=" + "your content here" + "&format=png"); image1.Source = new BitmapImage(uri);