Exemple #1
0
        private void Scan()
        {
            if (IsScanning && _initialized && _photoCamera != null && _luminanceSource != null && _reader != null)
            {
                try
                {
                    // 2-2-2012 - Rowdy.nl
                    // Focus the camera for better recognition of QR code's
                    if (_photoCamera.IsFocusSupported)
                    {
                        _photoCamera.Focus();
                    }
                    // End Rowdy.nl

                    _photoCamera.GetPreviewBufferY(_luminanceSource.PreviewBufferY);
                    var binarizer    = new HybridBinarizer(_luminanceSource);
                    var binaryBitmap = new BinaryBitmap(binarizer);
                    var result       = _reader.decode(binaryBitmap, QRCodeHint);

                    StopScanning();
                    OnResult(result);
                }
                catch (ReaderException)
                {
                    // There was not a successful QR code read in the scan
                    // pass. Invoke and try again soon.
                    Dispatcher.BeginInvoke(Scan);
                }
                catch (Exception ex)
                {
                    OnError(ex);
                }
            }
        }
Exemple #2
0
        static void barcode_decode(string path)
        {
            ImageConverter converter = new ImageConverter();

            var reader = new ZXing.QrCode.QRCodeReader();
            //ZXing.BinaryBitmap
            var dest = (Bitmap)Bitmap.FromFile(path);
            var bb   = (byte[])converter.ConvertTo(dest, typeof(byte[]));
            // ;
            // BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
            var source = new BitmapLuminanceSource(dest);
            // LuminanceSource source = new RGBLuminanceSource(bb,dest.Width,dest.Height, RGBLuminanceSource.BitmapFormat.RGB32);
            HybridBinarizer binarizer = new HybridBinarizer(source);
            BinaryBitmap    binBitmap = new BinaryBitmap(binarizer);
            QRCodeReader    qrr       = new QRCodeReader();
            var             result    = qrr.decode(binBitmap);

            if (result != null)
            {
                var text = result.Text;
                Console.WriteLine(text);
            }
            else
            {
                Console.WriteLine("Err");
            }
        }
Exemple #3
0
        private static Rectangle FindBarcodeRectangle(Bitmap bitmap, ResultPoint[] resultPoints)
        {
            var   startX = resultPoints[0].X;
            float startY;

            var   width = resultPoints[1].X - resultPoints[0].X;
            float height;


            var luminanceSource        = new BitmapLuminanceSource(bitmap);
            var binarizer              = new HybridBinarizer(luminanceSource);
            var bitMatrix              = binarizer.BlackMatrix;
            var whiteRectangleDetector = WhiteRectangleDetector.Create(bitMatrix);
            var whiteRectanblePoints   = whiteRectangleDetector.detect();

            if (whiteRectanblePoints != null)
            {
                height = whiteRectanblePoints[3].Y - whiteRectanblePoints[0].Y;
                startY = whiteRectanblePoints[0].Y;
            }
            else
            {
                height = 1;
                startY = resultPoints[0].Y;
            }

            var barcodeRectangle = new Rectangle((int)startX, (int)startY, (int)width, (int)height);

            return(barcodeRectangle);
        }
 /// <summary>
 /// Escanea el buffer de la cámara y si
 /// detectó un código QR lo manda a la vista ImagePicker
 /// </summary>
 private void ScanPreviewBuffer()
 {
     try
     {
         photoCamera.GetPreviewBufferY(luminance.PreviewBufferY);
         var binarizer = new HybridBinarizer(luminance);
         var binBitmap = new BinaryBitmap(binarizer);
         var result    = reader.decode(binBitmap);
         if (result == null)
         {
             return;
         }
         // Se leyó el código QR
         this.qrCodeText = result.Text;
         this.Dispatcher.BeginInvoke(() =>
         {
             timer.Stop();
             photoCamera.Dispose();
             NavigationService.Navigate(new Uri(String.Format("/ImagePicker.xaml?qr={0}", qrCodeText), UriKind.Relative));
         });
     }
     catch (Exception)
     {
         MessageBox.Show("Ocurrió un error al tratar de decodificar el código QR", "Photo Sharing", MessageBoxButton.OK);
     }
 }
Exemple #5
0
        //private void splitContainer1_Panel1_Paint(object sender, PaintEventArgs e)
        //{

        //}

        private void timer1_Tick(object sender, EventArgs e)
        {
            QRCodeReader Scanner = new QRCodeReader();

            if (pictureBox1.Image != null)
            {
                byte[]          mybyte = (byte[])new ImageConverter().ConvertTo(pictureBox1.Image, Type.GetType("Byte"));
                LuminanceSource source = new RGBLuminanceSource(mybyte, pictureBox1.Image.Width, pictureBox1.Image.Height);
                var             bin    = new HybridBinarizer(source);
                var             binBit = new BinaryBitmap(bin);
                Result          result = Scanner.decode(binBit);

                try
                {
                    string decoded = result.ToString().Trim();
                    if (decoded == "Hello")
                    {
                        MessageBox.Show(decoded);
                        timer1.Stop();
                    }



                    //splitContainer1.Panel2.Enabled = true;
                    //textBox1.Text = decoded;
                }
                catch (Exception ex)
                {
                }
            }
        }
    public void ReadQRCode(Color[] clist, int width, int height, Action <string> OnOk = null)
    {
        byte[] bcolor = new byte[width * height * 3];

        for (int y = 0; y < height; y++)
        {
            int offset = y * width;
            for (int x = 0; x < width; x++)
            {
                bcolor[offset * 3 + x * 3]     = (byte)(clist[x * height + y].r * 255);
                bcolor[offset * 3 + x * 3 + 1] = (byte)(clist[x * height + y].g * 255);
                bcolor[offset * 3 + x * 3 + 2] = (byte)(clist[x * height + y].b * 255);
            }
        }

        Loom.RunAsync(() =>
        {
            try
            {
                QRCodeReader qrreader      = new QRCodeReader();
                RGBLuminanceSource scource = new RGBLuminanceSource(bcolor, width, height);
                HybridBinarizer binarizer  = new HybridBinarizer(scource);
                BinaryBitmap bitmap        = new BinaryBitmap(binarizer);
                Result result = qrreader.decode(bitmap);
                Loom.QueueOnMainThread(() => { OnOk(result.Text); });
            }
            catch (Exception ex)
            {
            }
        });
    }
Exemple #7
0
        private void ScanPreviewBuffer()
        {
            try
            {
                _photoCamera.GetPreviewBufferY(_luminance.PreviewBufferY);
                var    binarizer = new HybridBinarizer(_luminance);
                var    binBitmap = new BinaryBitmap(binarizer);
                Result result    = _reader.decode(binBitmap);
                if (result != null)
                {
                    _timer.Stop();
                    SetStillPicture();
                    BarCodeRectSuccess();
                    Dispatcher.BeginInvoke(() =>
                    {
                        string destination = "/DrugResultPage.xaml";
                        Dictionary <string, string> dic = new Dictionary <string, string>();
                        dic.Add("code", result.Text);
                        PhoneApplicationService.Current.State["dic"] = dic;
                        destination += string.Format("?type={0}", "DrugCode");

                        //读取成功,结果存放在result.Text
                        NavigationService.Navigate(new Uri(destination, UriKind.Relative));
                    });
                }
                else
                {
                    _photoCamera.Focus();
                }
            }
            catch
            {
            }
        }
Exemple #8
0
        private void ScanPreviewBuffer()
        {
            if (NavigationService.CurrentSource == new Uri("/ScannerPage.xaml", UriKind.Relative))
            {
                try
                {
                    _photoCamera.GetPreviewBufferY(_luminance.PreviewBufferY);
                    var binarizer = new HybridBinarizer(_luminance);
                    var binBitmap = new BinaryBitmap(binarizer);
                    var result    = _reader.decode(binBitmap);
                    Dispatcher.BeginInvoke(() => DisplayResult(result.Text));
                    // katsotaan miten käy
                    if (result.Text != null)
                    {
                        string kysymysID;
                        string viesti          = result.Text;
                        int    categoryIdIndex = viesti.IndexOf("kysymys") + 7;
                        kysymysID = viesti.Substring(categoryIdIndex);


                        Dispatcher.BeginInvoke(() => KysymysSaatu(kysymysID));
                    }
                }
                catch (Exception ex)
                {
                    //Dispatcher.BeginInvoke(() => NaytaException(ex.Message));
                }
            }
        }
 private void ScanPreviewBuffer()
 {
     try
     {
         _photoCamera.GetPreviewBufferY(_luminance.PreviewBufferY);
         var    binarizer = new HybridBinarizer(_luminance);
         var    binBitmap = new BinaryBitmap(binarizer);
         Result result    = _reader.decode(binBitmap);
         if (result != null)
         {
             _timer.Stop();
             SetStillPicture();
             BarCodeRectSuccess();
             Dispatcher.BeginInvoke(() =>
             {
                 //读取成功,结果存放在result.Text
                 NavigationService.Navigate(new Uri("/ScanResult.xaml?result=" + result.Text, UriKind.Relative));
             });
         }
         else
         {
             _photoCamera.Focus();
         }
     }
     catch
     {
     }
 }
Exemple #10
0
        private async Task <string> ReadImageAsync(byte[] data)
        {
            try
            {
                var bitmap = new BitmapImage();
                using (var stream = new InMemoryRandomAccessStream())
                {
                    await stream.WriteAsync(data.AsBuffer());

                    stream.Seek(0);
                    await bitmap.SetSourceAsync(stream);
                }

                var source    = new RGBLuminanceSource(data, bitmap.PixelWidth, bitmap.PixelHeight);
                var reader    = new ZXing.QrCode.QRCodeReader();
                var binarizer = new HybridBinarizer(source);
                var bitmapx   = new BinaryBitmap(binarizer);
                var result    = reader.decode(bitmapx);

                return(result.Text);
            }
            catch (Exception ex)
            {
                return(string.Empty);
            }
        }
Exemple #11
0
        unsafe static void Main(string[] args)
        {
            var bitmap = new Bitmap(@"Z:\3.png");
            int w = bitmap.Width, h = bitmap.Height;
            var thresholds = HybridBinarizer.GetThreshold(bitmap);
            var output     = new Bitmap(bitmap.Width, bitmap.Height);
            var data       = bitmap.LockBits(new Rectangle(0, 0, w, h), System.Drawing.Imaging.ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppRgb);
            var bitmapData = output.LockBits(new Rectangle(0, 0, w, h), System.Drawing.Imaging.ImageLockMode.WriteOnly, System.Drawing.Imaging.PixelFormat.Format32bppRgb);
            var p0         = (uint *)data.Scan0;
            var p          = (uint *)bitmapData.Scan0;

            for (int y = 0; y < h; y++)
            {
                for (int x = 0; x < w; x++)
                {
                    byte *bgr  = (byte *)(p0 + y * w + x);
                    int   gray = (RWeight * bgr[2] + GWeight * bgr[1] + BWeight * bgr[0]) >> 16;
                    uint  g    = thresholds[x, y];
                    //p[y * w + x] = (g << 16) | (g << 8) | g;
                    p[y * w + x] = gray <= g ? 0 : 0xffffffu;
                }
            }
            output.UnlockBits(bitmapData);
            bitmap.UnlockBits(data);
            output.Save(@"Z:\out5.png");
        }
        private void Scan()
        {
            if (IsScanning && _initialized && _photoCamera != null && _luminanceSource != null && _reader != null)
            {
                try
                {
                    // 2-2-2012 - Rowdy.nl
                    // Focus the camera for better recognition of QR code's

                    if (_photoCamera.IsFocusSupported)
                    {
                        _photoCamera.Focus();
                    }
                    // End Rowdy.nl

                    _photoCamera.GetPreviewBufferY(_luminanceSource.PreviewBufferY);
                    var binarizer    = new HybridBinarizer(_luminanceSource);
                    var binaryBitmap = new BinaryBitmap(binarizer);
                    var result       = _reader.decode(binaryBitmap, QRCodeHint);

                    if (result != null)
                    {
                        StopScanning();
                        OnResult(result);
                    }
                }
                catch (ReaderException)
                {
                }
                catch (Exception ex)
                {
                    OnError(ex);
                }
            }
        }
Exemple #13
0
        private Result ProcessQRReader(Bitmap image)
        {
            image = preProcessImage(image);
            //image = new Bitmap("d:\\AMA_QR.bmp");
            LuminanceSource ls      = new RGBLuminanceSource(image, image.Width, image.Height);
            Binarizer       hb      = new HybridBinarizer(ls);
            Result          result  = null;
            BinaryBitmap    bbitmap = new BinaryBitmap(hb);

            try
            {
                result = reader.decode(bbitmap);
            }
            catch (ReaderException rex)
            {
                Console.WriteLine(rex.Message);
                if (counter == 0)
                {
                    image   = paddingImage(image, 20);
                    counter = 1;
                    return(ProcessQRReader(image));
                }
                else
                {
                    counter = 0;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            counter = 0;
            return(result);
        }
        /// <summary>
        /// Try to decode. Throws exception!!
        /// </summary>
        /// <returns>ScanResult if successful</returns>
        public ScanResult Decode()
        {
            binarizer = new HybridBinarizer(luminance);
            binBitmap = new BinaryBitmap(binarizer);
            Result r = reader.decode(binBitmap, hints);

            return(new ScanResult(ConvertFormat(r.BarcodeFormat), r.Text));
        }
Exemple #15
0
        private static byte[] ParseQR(Image q)
        {
            var bitmap    = new Bitmap(q);
            var img       = new RGBLuminanceSource(bitmap, bitmap.Width, bitmap.Height);
            var hybrid    = new HybridBinarizer(img);
            var binaryMap = new BinaryBitmap(hybrid);
            var reader    = new QRCodeReader().Decode(binaryMap, null);

            return(Array.ConvertAll(reader.RawBytes, a => (byte)a));
        }
        public byte[] parseQR(Image q)
        {
            Bitmap       bitmap    = new Bitmap(q);
            var          img       = new RGBLuminanceSource(bitmap, bitmap.Width, bitmap.Height);
            var          hybrid    = new HybridBinarizer(img);
            BinaryBitmap binaryMap = new BinaryBitmap(hybrid);
            var          reader    = new QRCodeReader().decode(binaryMap, null);

            byte[] data = Array.ConvertAll(reader.RawBytes, (a) => (byte)(a));
            return(data);
        }
        public static bool Detect(Bitmap capturedImage)
        {
            var source    = new BitmapLuminanceSource(capturedImage);
            var binarizer = new HybridBinarizer(source);
            var bbitmap   = new BinaryBitmap(binarizer);

            var detect = ZXing.PDF417.Internal.Detector.detect(bbitmap, null, false);
            var result = detect.Points.Count > 0;

            return(result);
        }
Exemple #18
0
        public BinaryBitmap GetBinaryBitmap(byte[] image)
        {
            //Bitmap bitmap = BitmapFactory.DecodeByteArray(image, 0, image.Length);

            Bitmap bitmap = BitmapFactory.DecodeStream(context.Resources.OpenRawResource(Resource.Raw.static_qr_code_without_logo));

            byte[] rgbBytes = GetRgbBytes(bitmap);
            var    bin      = new HybridBinarizer(new RGBLuminanceSource(rgbBytes, bitmap.Width, bitmap.Height));
            var    i        = new BinaryBitmap(bin);

            return(i);
        }
        private void PumpYFrames()
        {
            byte[] array = new byte[307200];
            bool   flag  = false;

            while (this._pumpYFrames)
            {
                BarcodeScanner._pauseFramesEvent.WaitOne();
                if (this._isScanning)
                {
                    try
                    {
                        this._cam.GetPreviewBufferY(array);
                        flag = true;
                    }
                    catch
                    {
                        flag = false;
                    }
                    if (flag)
                    {
                        DateTime           now = DateTime.Now;
                        RGBLuminanceSource rGBLuminanceSource = new RGBLuminanceSource(array, 640, 480, false);
                        if (this._scanType == CodeType.OneDCodes || this._scanType == CodeType.UPC || this._scanType == CodeType.ITF || this._scanType == CodeType.EAN || this._scanType == CodeType.Code128 || this._scanType == CodeType.Code39)
                        {
                            rGBLuminanceSource.rotateCounterClockwise();
                        }
                        HybridBinarizer binarizer = new HybridBinarizer(rGBLuminanceSource);
                        BinaryBitmap    image     = new BinaryBitmap(binarizer);
                        Reader          reader    = this.GetReader(this._scanType);
                        try
                        {
                            Result   results   = reader.decode(image, this._hintDictionary);
                            TimeSpan timeSpent = DateTime.Now.Subtract(now);
                            Deployment.Current.Dispatcher.BeginInvoke(delegate
                            {
                                this.ProcessScan(results, timeSpent, this.ScanType);
                                if (this.StopOnSuccess)
                                {
                                    this.IsScanning = false;
                                }
                            }
                                                                      );
                            BarcodeScanner._pauseFramesEvent.Set();
                        }
                        catch
                        {
                            BarcodeScanner._pauseFramesEvent.Set();
                        }
                    }
                }
            }
        }
Exemple #20
0
        public async Task <BinaryBitmap> GetBinaryBitmap(string path, CancellationToken token)
        {
            var bitmap   = BitmapFactory.DecodeFile(path);
            var rgbBytes = await Task.Run(() => GetRgbBytesFaster(bitmap, token));

            ResetToReuse();

            var rgbLuminanceSource = new RGBLuminanceSource(rgbBytes, bitmap.Width, bitmap.Height);
            var binarizer          = new HybridBinarizer(rgbLuminanceSource);
            var binaryBitmap       = new BinaryBitmap(binarizer);

            return(binaryBitmap);
        }
Exemple #21
0
        private async Task <Result> Decode(IRandomAccessStream stream)
        {
            BitmapDecoder decoder = await BitmapDecoder.CreateAsync(stream);

            SoftwareBitmap bitmap = await decoder.GetSoftwareBitmapAsync();

            LuminanceSource   luminanceSource = new SoftwareBitmapLuminanceSource(bitmap);
            Binarizer         binarizer       = new HybridBinarizer(luminanceSource);
            BinaryBitmap      binaryBitmap    = new BinaryBitmap(binarizer);
            MultiFormatReader reader          = new MultiFormatReader();

            return(reader.decode(binaryBitmap));
        }
 private void ScanPreviewBuffer()
 {
     try
     {
         _photoCamera.GetPreviewBufferY(_luminance.PreviewBufferY);
         var binarizer = new HybridBinarizer(_luminance);
         var binBitmap = new BinaryBitmap(binarizer);
         var result    = _reader.decode(binBitmap);
         Dispatcher.BeginInvoke(() => DisplayResult(result.Text));
     }
     catch
     {
     }
 }
 void createWorker()
 {
     //create worker thread for reading barcode
     readerWorker = new Task(async() =>
     {
         //use stopwatch to time the execution, and execute the reading process repeatedly
         var watch  = System.Diagnostics.Stopwatch.StartNew();
         var reader = new QRCodeMultiReader();
         SoftwareBitmap bitmap;
         HybridBinarizer binarizer;
         while (true)
         {
             try
             {
                 lock (bufLock)
                 {
                     bitmap = new SoftwareBitmap(BitmapPixelFormat.Bgra8, width, height);
                     bitmap.CopyFromBuffer(decodedDataBuf.AsBuffer());
                 }
             }
             catch
             {
                 //the size maybe incorrect due to unknown reason
                 await Task.Delay(10);
                 continue;
             }
             var source  = new SoftwareBitmapLuminanceSource(bitmap);
             binarizer   = new HybridBinarizer(source);
             var results = reader.decodeMultiple(new BinaryBitmap(binarizer));
             if (results != null && results.Length > 0)
             {
                 await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
                 {
                     foreach (var result in results)
                     {
                         if (!readed.Contains(result.Text))
                         {
                             readed.Add(result.Text);
                             Textbox.Text += result.Text + "\n";
                         }
                     }
                 });
             }
             watch.Stop();
             int elapsed = (int)watch.ElapsedMilliseconds;
             //run at max 5Hz
             await Task.Delay(Math.Max(0, 200 - elapsed));
         }
     });
 }
Exemple #24
0
 private void ScanPreviewBuffer()
 {
     try {
         photoCamera.GetPreviewBufferY(luminance.PreviewBufferY);
         var binarizer = new HybridBinarizer(luminance);
         var binBitmap = new BinaryBitmap(binarizer);
         var result    = reader.decode(binBitmap);
         if (result != null)
         {
             Dispatcher.BeginInvoke(() => Synchronize(result.Text));
         }
     }
     catch {
     }
 }
Exemple #25
0
 // Source: http://www.codeproject.com/Questions/441372/zxing-QRCode-Encoding-and-Decoding-in-csharp
 private String qrReader(Bitmap image)
 {
     byte[] byteImage = ImageToByte(image);
     try
     {
         ZXing.LuminanceSource source = new ZXing.RGBLuminanceSource(byteImage, image.Width, image.Height);
         var binarizer = new HybridBinarizer(source);
         var binBitmap = new BinaryBitmap(binarizer);
         return(reader.decode(binBitmap).Text);
     }
     catch
     {
         return(string.Empty);
     }
 }
Exemple #26
0
 static public CodeDecoder           Decode(byte[,] aabImage, int iWidth, int iHeight)
 {
    byte[] abImage = new byte[ iWidth * iHeight ];
    //
    for (int y = 0, i = 0; y < iHeight; y++)
       for (int x = 0; x < iWidth; x++)
          abImage[i++] = (byte)((aabImage[x, y] > 128) ? 255 : 0);
    //
    ZXing.LuminanceSource xSource = new RGBLuminanceSource(abImage, iWidth, iHeight, RGBLuminanceSource.BitmapFormat.Gray8);
    //
    var xBinarizer = new HybridBinarizer(xSource);
    var xBinBitmap = new BinaryBitmap(xBinarizer);
    //
    return Decode(xBinBitmap);
 }
Exemple #27
0
        //public BinaryBitmap GetBinaryBitmap(byte[] image)
        public BinaryBitmap GetBinaryBitmap()
        {
            //uncomment the line below to use the image that is passed instead of a raw image.
            //Bitmap bitmap = BitmapFactory.DecodeByteArray(image, 0, image.Length);

            //Bitmap bitmap = BitmapFactory.DecodeStream(context.Resources.OpenRawResource(global::Android.Resource.Raw.static_qr_code_without_logo));
            Bitmap bitmap = BitmapFactory.DecodeStream(context.Resources.Assets.Open("static_qr_code_without_logo"));

            //Bitmap bitmap = BitmapFactory.DecodeStream(context.Resources.OpenRawResource(Uri.("));

            byte[] rgbBytes = GetRgbBytes(bitmap);
            var    bin      = new HybridBinarizer(new RGBLuminanceSource(rgbBytes, bitmap.Width, bitmap.Height));
            var    i        = new BinaryBitmap(bin);

            return(i);
        }
Exemple #28
0
        public Dictionary <string, ResultPoint[]> findQrCodeText(Reader decoder, Bitmap bitmap)
        {
            var          rgb       = new ZXing.RGBLuminanceSource(GetRGBValues(bitmap), bitmap.Width, bitmap.Height);
            var          hybrid    = new HybridBinarizer(rgb);
            BinaryBitmap binBitmap = new BinaryBitmap(hybrid);

            Dictionary <string, ResultPoint[]> decodedString = new Dictionary <string, ResultPoint[]>();

            Result res = decoder.decode(binBitmap, null);

            if (res != null)
            {
                decodedString.Add(res.Text, res.ResultPoints);
            }
            return(decodedString);
        }
        private void RealStartTask(Reader reader, BarcodeDecodeTask task)
        {
            var bitmap = new WriteableBitmap(task.Width, task.Height);

            bitmap.SetSource(task.ImageStream.AsRandomAccessStream());
            ThreadPool.RunAsync(p =>
            {
                var result  = BarcodeDecodeResultType.Unknown;
                var message = string.Empty;
                try
                {
                    var wb = bitmap;
                    //Code from: btnReadTag_Click in "SLZXingQRSample\SLZXingQRSample\SLZXingSample\MainPage.xaml.vb"
                    var qrRead     = reader;                 // new com.google.zxing.qrcode.QRCodeReader();
                    var luminiance = new RGBLuminanceSource(wb.PixelBuffer.ToArray(), wb.PixelWidth, wb.PixelHeight);
                    var binarizer  = new HybridBinarizer(luminiance);
                    var binBitmap  = new BinaryBitmap(binarizer);
                    var results    = qrRead.decode(binBitmap);                  //NOTE: will throw exception if cannot decode image.
                    if (results == null)
                    {
                        result  = BarcodeDecodeResultType.NotDetected;
                        message = "Error: Cannot detect barcode image. Please make sure scan mode is correct and try again.";
                    }
                    else
                    {
                        result  = BarcodeDecodeResultType.Success;
                        message = results.Text;
                    }
                }
                catch (ReaderException)
                {
                    result  = BarcodeDecodeResultType.Fail;
                    message = "Error: Cannot decode barcode image. Please make sure scan mode is correct and try again.";
                }
                catch (Exception ex)
                {
                    result  = BarcodeDecodeResultType.Unknown;
                    message = String.Format("Barcode Library Processing Error: {0}\r\n{1}", ex.GetType(), ex.Message);
                }
                finally
                {
                    task.HandleResult(new BarcodeDecodeResult(result, message));
                    _availableReader.Enqueue(reader);
                    TryStartTask();
                }
            });
        }
        private void ScanBarcode()
        {
            var zxingHints = new Dictionary <object, object>()
            {
                { DecodeHintType.TRY_HARDER, true }
            };

            var cameraPreviewBuffer       = new byte[640 * 480];
            var cameraPreviewSampleBuffer = new byte[640 * 120];

            Thread.Sleep(300);

            while (_scanning)
            {
                _photoCameraService.GetPreviewBufferY(cameraPreviewBuffer);

                Array.Copy(cameraPreviewBuffer, 640 * 180, cameraPreviewSampleBuffer, 0, 640 * 120);

                Result readerResult = null;

                try
                {
                    var luminance    = new RGBLuminanceSource(cameraPreviewSampleBuffer, 640, 120, true);
                    var binarizer    = new HybridBinarizer(luminance);
                    var binaryBitmap = new BinaryBitmap(binarizer);

                    readerResult = _barcodeReader.decode(binaryBitmap, zxingHints);
                }
                catch
                {
                }

                if (readerResult != null)
                {
                    _vibrationService.Start();

                    _scanning = false;

                    DispatcherHelper.CheckBeginInvokeOnUI(() =>
                    {
                        MessengerInstance.Send <ScannedBarcodeMessage>(new ScannedBarcodeMessage(readerResult.Text));

                        _navigationService.GoBack();
                    });
                }
            }
        }