Scan QR Code with Windows Phone RT (WinPRT)

In a hackathon project, my app need qr code scanning functionality. So I search a quick solution and find ZXing and WriteableBitmalEx.WinRT are quite useful.

Here is my setup:

declare local variable of media device

private MediaCapture _mediaCapture;

create a function, to initialize qr code function, which iniate variable needed, preparing viewfinder to get camera as its video source

private async Task InitializeQrCode()
{
// Find all available webcams
DeviceInformationCollection webcamList = await DeviceInformation.FindAllAsync(DeviceClass.VideoCapture);

// Get the proper webcam (default one)
DeviceInformation backWebcam = (from webcam in webcamList
where webcam.IsEnabled
select webcam).FirstOrDefault();

// Initializing MediaCapture
_mediaCapture = new MediaCapture();
await _mediaCapture.InitializeAsync(new MediaCaptureInitializationSettings
{
VideoDeviceId = backWebcam.Id,
AudioDeviceId = "",
StreamingCaptureMode = StreamingCaptureMode.Video,
PhotoCaptureSource = PhotoCaptureSource.VideoPreview
});

// Adjust camera rotation for Phone
_mediaCapture.SetPreviewRotation(VideoRotation.Clockwise90Degrees);
_mediaCapture.SetRecordRotation(VideoRotation.Clockwise90Degrees);

// Set the source of CaptureElement to MediaCapture
capturePreview.Source = _mediaCapture;
await _mediaCapture.StartPreviewAsync();
}

And now for the actual code to have a qr code scanned :

private async void ScanQrCode()
{
await InitializeQrCode();

var imgProp = new ImageEncodingProperties { Subtype = "BMP", Width = 400, Height = 400 };
var bcReader = new BarcodeReader();
string qrCodeResult = String.Empty ;
while (true)
{
var stream = new InMemoryRandomAccessStream();
await _mediaCapture.CapturePhotoToStreamAsync(imgProp, stream);

stream.Seek(0);
var wbm = new WriteableBitmap(400, 400);
await wbm.SetSourceAsync(stream);

var result = bcReader.Decode(wbm);

if (result != null)
{
//var msgbox = new MessageDialog(result.Text);
//await msgbox.ShowAsync();
qrCodeResult = result.Text;
break;
}
}

TextBlockStatus.Text = "Item is detected..";
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s