Wednesday, May 2, 2012

Creating QR Code from Text in wp7

You should add Silverlight_ZXing_Core.dll in references

In XAML Page you should place the image control like:
<Image Name="tempImage" />

In Code page
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.IO;
using System.Windows.Media.Imaging;


namespace EncodeIntoQRCode
{
    public partial class MainPage : PhoneApplicationPage
    {
// Constructor
public MainPage()
{
   InitializeComponent();
   CreateQRCode("Rachit Gaur");

}
private void CreateQRCode(string text)
{

   com.google.zxing.qrcode.QRCodeWriter qrWrite = new com.google.zxing.qrcode.QRCodeWriter();
   com.google.zxing.common.ByteMatrix bm = qrWrite.encode(text, com.google.zxing.BarcodeFormat.QR_CODE, 350, 350);
   this.tempImage.Source = ConvertByteMartixToWriteableBitmap(bm);
}

/// <summary>
/// results matrix encoded into Silverlight, write into a Bitmap image
/// </ summary>
/// <param name="bm"> </ param>
/// <returns> </ returns>
///<remarks> tag </ remarks>
public System.Windows.Media.Imaging.WriteableBitmap ConvertByteMartixToWriteableBitmap(com.google.zxing.common.ByteMatrix bm)
{
   System.Windows.Media.Imaging.WriteableBitmap wb = new System.Windows.Media.Imaging.WriteableBitmap(bm.Width, bm.Height);
   for (int x = 0; x <= wb.PixelWidth - 1; x++)
   {
for (int y = 0; y <= wb.PixelHeight - 1; y++)
{
   if (bm.Array[y][x] == -1)
   {
// white                      
wb.Pixels[wb.PixelWidth * y + x] = BitConverter.ToInt32(BitConverter.GetBytes(0xffffffff), 0);
   }
   else
   {
// black                      
wb.Pixels[wb.PixelWidth * y + x] = BitConverter.ToInt32(BitConverter.GetBytes(0xff000000), 0);
   }
}
   }
   return wb;
}
    }
}


Hope this will clear.




Happy Coding

No comments:

Post a Comment

Total Pageviews