Shashank Bisen
Shashank Bisen

Reputation: 213

Reading QR codes / bar codes in windows 8 application

I want to Read QR codes / bar codes in windows 8 application using xaml C#, any pointers?

I tried this using ZXing.Net

    var openPicker = new FileOpenPicker { ViewMode = PickerViewMode.Thumbnail, SuggestedStartLocation = PickerLocationId.PicturesLibrary };
    openPicker.FileTypeFilter.Add(".jpg");
    openPicker.FileTypeFilter.Add(".jpeg");
    openPicker.FileTypeFilter.Add(".png");

    StorageFile file = await openPicker.PickSingleFileAsync();
    if (file != null)
    {
        // Application now has read/write access to the picked file

        BitmapImage bmp = new BitmapImage();
        IRandomAccessStream stream = await file.OpenAsync(FileAccessMode.Read);
        bmp.SetSource(stream);
        BarCodeImage.Source = bmp;

        IBarcodeReader reader = new BarcodeReader();
        WriteableBitmap barcodeBitmap = new WriteableBitmap(1,1);
        barcodeBitmap.SetSource(stream);
        var result = reader.Decode(barcodeBitmap);
    }

but while loading the result i am getting exception that "Value cannot be null". Please help what should be code for it

Upvotes: 0

Views: 1417

Answers (1)

Shashank Bisen
Shashank Bisen

Reputation: 213

I finally got the solution, hope it might help some one else in future

    private async void DecodeStaticResource(StorageFile file)
    {
        var stream = await file.OpenReadAsync();

        // initialize with 1,1 to get the current size of the image
        var writeableBmp = new WriteableBitmap(1, 1);
        writeableBmp.SetSource(stream);


        // and create it again because otherwise the WB isn't fully initialized and decoding
        // results in a IndexOutOfRange
        writeableBmp = new WriteableBitmap(writeableBmp.PixelWidth, writeableBmp.PixelHeight);
        stream.Seek(0);
        writeableBmp.SetSource(stream);

        var result = ScanBitmap(writeableBmp);
        if (result != null)
        {
            ScanResult.Text += result.Text;
        }
    }

    private Result ScanBitmap(WriteableBitmap writeableBmp)
    {
        var barcodeReader = new BarcodeReader
        {
            TryHarder = true,
            AutoRotate = true
        };
        var result = barcodeReader.Decode(writeableBmp);

        if (result != null)
        {
            CaptureImage.Source = writeableBmp;
        }

        return result;
    }

Upvotes: 2

Related Questions