示例#1
0
        //takes the video input and creates a bitmap of the image
        BinaryBitmap GetBitmapFromVideo(PhotoCamera cam)
        {
            BinaryBitmap binaryBitmap = null;

            try
            {
                // Update buffer size    
                var pixelWidth = (int)_cam.PreviewResolution.Width;
                var pixelHeight = (int)_cam.PreviewResolution.Height;

                if (_buffer == null || _buffer.Length != (pixelWidth * pixelHeight))
                {
                    _buffer = new byte[pixelWidth * pixelHeight];
                }

                _cam.GetPreviewBufferY(_buffer);

                var luminance = new RGBLuminanceSource(_buffer, pixelWidth, pixelHeight, true);
                var binarizer = new com.google.zxing.common.HybridBinarizer(luminance);

                binaryBitmap = new BinaryBitmap(binarizer);
            }
            catch
            {
            }

            return binaryBitmap;
        }
        public static String Decode(Image Image)
        {
            try
            {
                var hints = new Hashtable();
                hints.Add(DecodeHintType.TRY_HARDER, true);
                ArrayList fmts = new ArrayList();
                fmts.Add(BarcodeFormat.QR_CODE);
                hints.Add(DecodeHintType.POSSIBLE_FORMATS, fmts);

                var Bitmap = new Bitmap(Image);
                LuminanceSource source = new RGBLuminanceSource(Bitmap, Bitmap.Width, Bitmap.Height);
                var bitmap = new BinaryBitmap(new GlobalHistogramBinarizer(source));
                Reader reader = new MultiFormatReader();
                Result result = reader.decode(bitmap, hints);
                String DecodedString = result.Text;
                Console.WriteLine(DecodedString);
                return DecodedString;
            }
            catch (ReaderException ex)
            {
                return "";
            }
            catch (InvalidOperationException ex)
            {
                return "";
            }
        }
示例#3
0
        private static bool decode(FileInfo file)
        {
            Bitmap          image ;

             try {
            image = new Bitmap(file.FullName) ;
             } catch { return false ; }

             // Rectangle crop = new Rectangle(image.Width/2,0,image.Width/2, image.Height) ;
             // Bitmap    focusOn = image.Clone(crop, PixelFormat.DontCare) ;
             // RGBLuminanceSource j = new RGBLuminanceSource(focusOn, focusOn.Width, focusOn.Height) ;
             RGBLuminanceSource j = new RGBLuminanceSource(image, image.Width, image.Height) ;

             Binarizer[]     binarizer = {new HybridBinarizer(j), new GlobalHistogramBinarizer(j)} ;
             Reader[]        reader = {new QRCodeReader(), new ByQuadrantReader(new QRCodeReader())} ;
             Result          qrc = null ;
             Hashtable  hints = new Hashtable() ;

             hints[DecodeHintType.TRY_HARDER] = true ;
             hints[DecodeHintType.POSSIBLE_FORMATS] = BarcodeFormat.QR_CODE ;

             foreach (Binarizer b in binarizer) {
            BinaryBitmap  bitmap = new BinaryBitmap(b) ;

            foreach (Reader r in reader) {
               try {
                  qrc = r.decode(bitmap, hints) ;
               } catch {}
               if (qrc != null) break ;
            }
            if (qrc != null) break ;
             }
             return ((qrc != null) ? ifDecoded(file, qrc) : ifNotDecoded(file)) ;
        }
示例#4
0
        private void btn_File_Click(object sender, System.EventArgs e)
        {
            string sRes="";
            OpenFileDialog ofn=new OpenFileDialog();
            if(ofn.ShowDialog()==DialogResult.OK){
                try {
                            Reader barcodeReader=
                                new com.google.zxing.MultiFormatReader();
                            System.Drawing.Bitmap srcbitmap =
                                new System.Drawing.Bitmap(ofn.FileName.ToString()); // Make a copy of the image in the Bitmap variable
                            //make a grey bitmap of it
                            bmp_util util=new bmp_util();
                            srcbitmap = util.ConvertToGrayscale(srcbitmap);

                            RGBLuminanceSource source =
                                new RGBLuminanceSource(srcbitmap, srcbitmap.Width, srcbitmap.Height);
                            com.google.zxing.BinaryBitmap bitmap=
                                new com.google.zxing.BinaryBitmap(new HybridBinarizer(source));
                            com.google.zxing.Result result = barcodeReader.decode(bitmap);
                            System.Console.WriteLine(result.Text);
                    sRes=result.Text;
                }
                catch (com.google.zxing.ReaderException zex) {
                    sRes=zex.Message;
                    System.Console.WriteLine(zex.Message);
                }
                catch (Exception ex) {
                    sRes=ex.Message;
                    System.Console.WriteLine(ex.Message);
                }
                tb.Text=sRes;
            }
        }
示例#5
0
        private bool TryToRecognize(WriteableBitmap wb, Reader reader, Dictionary<object, object> zxhints, out string output)
        {
            bool res = false;
            output = null;
            try
            {
                var luminiance = new RGBLuminanceSource(wb, wb.PixelWidth, wb.PixelHeight);
                var binarizer = new com.google.zxing.common.HybridBinarizer(luminiance);
                var binBitmap = new com.google.zxing.BinaryBitmap(binarizer);

                // recognize
                var results = reader.decode(binBitmap, zxhints); // exception will be thrown if reader cannot decode image.

                output = results.Text;
                res = true;
            }
            catch {}
            return res;
        }
        public string ReadBarcode(Bitmap BarcodeImage)
        {
            RGBLuminanceSource BarcodeSource = new RGBLuminanceSource(BarcodeImage, BarcodeImage.Width, BarcodeImage.Height);
            BinaryBitmap BarcodeImageBin = new BinaryBitmap(new GlobalHistogramBinarizer(BarcodeSource));
            MultiFormatReader BarcodeReader = new MultiFormatReader();
            try
            {
                Result BarcodeDecodeResult;
                BarcodeDecodeResult = BarcodeReader.decode(BarcodeImageBin);
                if (BarcodeDecodeResult.Text != null)
                    return BarcodeDecodeResult.Text;
                else
                    return "NoBarcode";

            }
            catch (Exception e)
            {
                return "Fail";
            }
        }
        private void BarCodeDetectTimer_Tick(object sender, EventArgs e)
        {
            try
            {
                Bitmap img = (Bitmap)pictureBox1.Image;
                Reader reader = new MultiFormatReader();
                RGBLuminanceSource source1 = new RGBLuminanceSource(img, img.Width, img.Height);
                BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source1));
                Result result = reader.decode(bitmap);

                textBox1.Text = result.Text;
                dekodirano = textBox1.Text;
                BarCodeDetectTimer.Stop();

            }
            catch (Exception)
            {
                statusStrip1.Text = "Greska pri dekodiranju";
            }
        }
示例#8
0
        private void button1_Click(object sender, EventArgs e)
        {
            if (this.openFileDialog1.ShowDialog() != DialogResult.OK)
            {
                return;
            }

            Image img = Image.FromFile(this.openFileDialog1.FileName);                        
            Bitmap bmap;
            try
            {
                bmap = new Bitmap(img);
            }
            catch (System.IO.IOException ioe)
            {
                MessageBox.Show(ioe.ToString());
                return;
            }

            if (bmap == null)
            {
                MessageBox.Show("Could not decode image");
                return;
            }

            LuminanceSource source = new RGBLuminanceSource(bmap, bmap.Width, bmap.Height);
            com.google.zxing.BinaryBitmap bitmap = new com.google.zxing.BinaryBitmap(new COMMON.HybridBinarizer(source));
            Result result;
            try
            {
                result = new MultiFormatReader().decode(bitmap);
            }
            catch(ReaderException re)
            {
                MessageBox.Show(re.ToString());
                return;
            }
            
            MessageBox.Show(result.Text);        
        }
        public String decode(Bitmap bitmap)
        {
            if (bitmap == null)
            {
                return null;
            }

            LuminanceSource source = new RGBLuminanceSource(bitmap, bitmap.Width, bitmap.Height);
            BinaryBitmap binaryBitmap = new BinaryBitmap(new HybridBinarizer(source));

            try
            {
                Result result = this.reader.decode(binaryBitmap);

                if (result != null)
                {
                    String[] resultToken = result.Text.Split(';');

                    double lat = Convert.ToDouble(resultToken[0]);
                    double lng = Convert.ToDouble(resultToken[1]);

                    double distance = Convert.ToDouble(resultToken[2]);
                    GPoint pointA = new GPoint(Convert.ToInt32(result.ResultPoints[1].X), Convert.ToInt32(result.ResultPoints[1].Y));
                    GPoint pointB = new GPoint(Convert.ToInt32(result.ResultPoints[2].X), Convert.ToInt32(result.ResultPoints[2].Y));

                    MapOverlayForm.Instance.SetMapScale(pointA, pointB, distance);
                    MapOverlayForm.Instance.RotationAngle = Convert.ToSingle(this.computeRotation(result.ResultPoints));
                    MapOverlayForm.Instance.MoveMapToLocalPosition(this.computeCenter(result.ResultPoints), new GMap.NET.PointLatLng(lat, lng));
                }
                return result.Text;
            }
            catch (ReaderException)
            {
                return null;
            }
        }
 public String getQRCodeData(Bitmap bitmap)
 {
     LuminanceSource source = new RGBLuminanceSource(bitmap, bitmap.Width, bitmap.Height);
     BinaryBitmap binaryBitmap = new BinaryBitmap(new HybridBinarizer(source));
     return this.reader.decode(binaryBitmap).Text;
 }
示例#11
0
 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();
                 }
             }
         }
     }
 }
        private void Worker()
        {
            //iphone 4 : 960 x 640
                //iphone 3 : 320 x 480
                if(DeviceHardware.Version == DeviceHardware.HardwareVersion.iPhone4)
                {
                    picFrame = new RectangleF(0, 146*2, 320*2, 157*2);
                }

                if(hints==null)
                {
                    var list = new ArrayList();
                    list.Add(com.google.zxing.BarcodeFormat.EAN_8);
                    list.Add(com.google.zxing.BarcodeFormat.EAN_13);

                    hints = new Hashtable();
                    hints.Add(com.google.zxing.DecodeHintType.POSSIBLE_FORMATS, list);
                    hints.Add(com.google.zxing.DecodeHintType.NEED_RESULT_POINT_CALLBACK, new ResultCallBack(this));
                }

                if(_multiFormatOneDReader == null)
                {
                    _multiFormatOneDReader = new com.google.zxing.oned.MultiFormatOneDReader(hints);
                }

                // Capturing screen image
                using (var screenImage = CGImage.ScreenImage.WithImageInRect(picFrame))
                {
                    _theScreenImage = UIImage.FromImage(screenImage);
                    Bitmap srcbitmap = new System.Drawing.Bitmap(_theScreenImage);
                    LuminanceSource source = null;
                    BinaryBitmap bitmap = null;
                    try {
                        source = new RGBLuminanceSource(srcbitmap, screenImage.Width, screenImage.Height);
                      	bitmap = new BinaryBitmap(new HybridBinarizer(source));

                        com.google.zxing.common.BitArray row = new com.google.zxing.common.BitArray(screenImage.Width);
                        int middle = screenImage.Height >> 1;
                        int rowStep = System.Math.Max(1, screenImage.Height >> (4));

                        for (int x = 0; x < 9; x++)
                        {

                            // Scanning from the middle out. Determine which row we're looking at next:
                            int rowStepsAboveOrBelow = (x + 1) >> 1;
                            bool isAbove = (x & 0x01) == 0; // i.e. is x even?
                            int rowNumber = middle + rowStep * (isAbove?rowStepsAboveOrBelow:- rowStepsAboveOrBelow);
                            if (rowNumber < 0 || rowNumber >= screenImage.Height)
                            {
                                // Oops, if we run off the top or bottom, stop
                                break;
                            }

                            // Estimate black point for this row and load it:
                            try
                            {
                                row = bitmap.getBlackRow(rowNumber, row);

                                var resultb = _multiFormatOneDReader.decodeRow(rowNumber, row, hints);
                                if(resultb.Text!=null)
                                {
                                    BeepOrVibrate();
                                    _parentViewController.BarCodeScanned(resultb);

                                    break;
                                }
                                else {
                                    continue;
                                }

                            }
                            catch (ReaderException re)
                            {
                                continue;
                            }

                        }

            //					var result = _barcodeReader.decodeWithState(bitmap);
            //
            //					if(result.Text!=null)
            //					{
            //						_multiFormatOneDReader = null;
            //						BeepOrVibrate();
            //						_parentViewController.BarCodeScanned(result);
            //					}

                    } catch (Exception ex) {
                        Console.WriteLine(ex.Message);
                    }
                    finally {
                        if(bitmap!=null)
                            bitmap = null;

                         if(source!=null)
                            source = null;

                        if(srcbitmap!=null)
                            srcbitmap = null;

                    }

                }
        }
示例#13
0
        /// <summary>
        /// This code should be run on a background thread to prevent UI lockup issues.
        /// For information about background threads see http://msdn.microsoft.com/en-us/library/ff967560(VS.92).aspx#BKMK_Background
        /// </summary>
        private static void ProcessImage()
        {
            LastCaptureResults.State = CaptureState.Processing;
            try
            {
                bool bIsReady = LastCaptureResults.isReadyForProcessing.WaitOne(3000);
                if (!bIsReady)
                {
                    LastCaptureResults.State = CaptureState.UnknownError;
                    LastCaptureResults.ErrorMessage = "Error: Timeout waiting for images to be processed. Please try again or send issue report using app bar.";
                    return;
                }

                StartProgress();
                if (LastCaptureResults.BarcodeImage != null)
                {
                    var wb = LastCaptureResults.VGABarcodeImage;

                    //Code from: btnReadTag_Click in "SLZXingQRSample\SLZXingQRSample\SLZXingSample\MainPage.xaml.vb"
                    var qrRead = GetReader(); // new com.google.zxing.qrcode.QRCodeReader();
                    var luminiance = new RGBLuminanceSource(wb, wb.PixelWidth, wb.PixelHeight);
                    var binarizer = new com.google.zxing.common.HybridBinarizer(luminiance);
                    var binBitmap = new com.google.zxing.BinaryBitmap(binarizer);
                    var results = qrRead.decode(binBitmap, zxingHints); //NOTE: will throw exception if cannot decode image.
                    LastCaptureResults.BarcodeText = results.Text;
                    LastCaptureResults.State = CaptureState.Success;
                    LastCaptureResults.ProcessValue();
                }
                else
                {
                    LastCaptureResults.State = CaptureState.UnknownError;
                    LastCaptureResults.ErrorMessage = "Cannot process image: invalid or null BitmapImage.";
                }
            }
            catch (Exception ex)
            {
                LastCaptureResults.ExceptionThrown = ex;
                if (ex is com.google.zxing.ReaderException)
                {
                    LastCaptureResults.ErrorMessage = "Error: Cannot decode barcode image. Please make sure scan mode is correct and try again.";
                    LastCaptureResults.State = CaptureState.ScanFailed;
                }
                else
                {
                    Debug.WriteLine("Error: " + ex.ToString());
                    LastCaptureResults.ErrorMessage = String.Format("Barcode Library Processing Error: {0}\r\n{1}", ex.GetType(), ex.Message);
                    LastCaptureResults.State = CaptureState.UnknownError;
                }
            }
            finally
            {
                ExecuteCallback();
            }
        }
示例#14
0
        private static bool decode(FileInfo file)
        {
            Bitmap original;

              try {
            original = new Bitmap(file.FullName);
              } catch { return false; }

              // Extract 2 *vertical* strips - one from the left-edge and another from the
              // right edge of the scan. If the page has multiple questions, then it would have
              // multiple QR codes. All of these would - if the strips are wide enough - be
              // in one of the two strips
              Bitmap[] strips = new Bitmap[2];
              strips[0] = (Bitmap)ScanImg.Crop(original, 10, 0, 35, 95); // left strip
              strips[1] = (Bitmap)ScanImg.Crop(original, 70, 0, 95, 95); // right strip
              Result qrc = null;
              bool[] orientation = {false, true};
              bool wasRotated = false;

              foreach (Bitmap img in strips) {
            foreach (bool rotate in orientation) {
              if (rotate)
            img.RotateFlip(RotateFlipType.Rotate180FlipNone);

              RGBLuminanceSource j = new RGBLuminanceSource(img, img.Width, img.Height);
              Binarizer[] binarizer = { new HybridBinarizer(j), new GlobalHistogramBinarizer(j) };
              Reader[] reader = { new QRCodeReader(), new ByQuadrantReader(new QRCodeReader()) };
              Hashtable hints = new Hashtable();

              hints[DecodeHintType.TRY_HARDER] = true;
              hints[DecodeHintType.POSSIBLE_FORMATS] = BarcodeFormat.QR_CODE;

              foreach (Binarizer b in binarizer) {
            BinaryBitmap bitmap = new BinaryBitmap(b);

            foreach (Reader r in reader) {
              try {
                qrc = r.decode(bitmap, hints);
              } catch (SystemException) { continue; } catch (ReaderException) { continue; }

              if (qrc != null)
                break;
            }
            if (qrc != null)
              break;
              }
              if (qrc != null) {
            wasRotated = rotate;
            break;
              }
            }
            if (qrc != null)
              break;
              }

              // Cleanup - and cleaup good
              original.Dispose();
              foreach (Bitmap img in strips)
            img.Dispose();

              return ((qrc != null) ? ifDecoded(file, qrc, wasRotated) : ifNotDecoded(file));
        }
示例#15
0
        private string QRDecode(Bitmap image, Reader decoder)
        {
            /*
            MemoryStream ms = new MemoryStream();
            image.Save(ms,System.Drawing.Imaging.ImageFormat.Bmp);

            DataMatrix dmDecoder = new DataMatrix(ms.ToArray(), image.Width, image.Height, EncodingType.Binary);

            return dmDecoder.HexPbm;
             * */

            var rgb = new RGBLuminanceSource(image, image.Width, image.Height);
            var hybrid = new HybridBinarizer(rgb);

            BinaryBitmap binBitmap = new BinaryBitmap(hybrid);

            string sdecodedString = decoder.decode(binBitmap, null).Text;
            //Byte[] result = decoder.decode(binBitmap, null).;

            //return null;

            return sdecodedString;
        }
		private void Worker()
        {
       
				if(hints==null)
				{
					hints = new Hashtable();
					hints.Add(com.google.zxing.DecodeHintType.POSSIBLE_FORMATS, this.Options.GetFormats());
					hints.Add(com.google.zxing.DecodeHintType.NEED_RESULT_POINT_CALLBACK, new ResultCallBack(this));
				}
				
				if(_multiFormatReader == null)
				{
				//_multiFormatReader = new com.google.zxing.oned.MultiFormatOneDReader(hints);
				_multiFormatReader = new com.google.zxing.MultiFormatReader();
				_multiFormatReader.Hints = hints;
				//_multiFormatReader = new MultiFormatReader {
				//		Hints = new Hashtable {
				//			{ DecodeHintType.POSSIBLE_FORMATS, new ArrayList { 
				//					BarcodeFormat.UPC_A, BarcodeFormat.UPC_E , BarcodeFormat.CODE_128,
				//					BarcodeFormat.CODE_39, BarcodeFormat.EAN_13, BarcodeFormat.EAN_8
				//				} }
				//		}
				//	};
				}
				
				
			using (var ap = new NSAutoreleasePool())
			{
				// Capturing screen image            
				using (var screenImage = CGImage.ScreenImage.WithImageInRect(picFrame)) //.WithImageInRect(picFrame))
	            {
					using (var _theScreenImage = UIImage.FromImage(screenImage))
					using (var srcbitmap = new Bitmap(_theScreenImage))
					{
						LuminanceSource source = null;
						BinaryBitmap bitmap = null;
						try 
						{
							//Console.WriteLine(screenImage.Width.ToString() + " x " + screenImage.Height.ToString());

							//var cropY = (int)((screenImage.Height * 0.4) / 2);
							source = new RGBLuminanceSource(srcbitmap, screenImage.Width, screenImage.Height); //.crop(0, cropY, 0, screenImage.Height - cropY - cropY);

							//Console.WriteLine(source.Width + " x " + source.Height);

			              	bitmap = new BinaryBitmap(new HybridBinarizer(source));
												
					
						try
						{
							var result = _multiFormatReader.decodeWithState(bitmap); //
							//var result = _multiFormatReader.decodeWithState (bitmap);
						
								//srcbitmap.Dispose();

							if(result.Text!=null)
							{
								//BeepOrVibrate();
								_parentViewController.BarCodeScanned(result);
							}
						}
						catch (ReaderException)
						{
						}

						
					/*
						com.google.zxing.common.BitArray row = new com.google.zxing.common.BitArray(screenImage.Width);
						
						int middle = screenImage.Height >> 1;
						int rowStep = System.Math.Max(1, screenImage.Height >> (4));
						
						for (int x = 0; x < 9; x++)
						{
							
							// Scanning from the middle out. Determine which row we're looking at next:
							int rowStepsAboveOrBelow = (x + 1) >> 1;
							bool isAbove = (x & 0x01) == 0; // i.e. is x even?
							int rowNumber = middle + rowStep * (isAbove?rowStepsAboveOrBelow:- rowStepsAboveOrBelow);
							if (rowNumber < 0 || rowNumber >= screenImage.Height)
							{
								// Oops, if we run off the top or bottom, stop
								break;
							}
							
							// Estimate black point for this row and load it:
							try
							{
								row = bitmap.getBlackRow(rowNumber, row);
								
								
								var resultb = _multiFormatReader.decodeRow(rowNumber, row, hints);
								if(resultb.Text!=null)
								{
									Console.WriteLine("SCANNED");
									BeepOrVibrate();
									_parentViewController.BarCodeScanned(resultb);
										
								
									break;
								}
								else {
									continue;
								}
								
							}
							catch (ReaderException re)
							{
								continue;
							}
					
						}
*/
						
						
	//					var result = _barcodeReader.decodeWithState(bitmap);
	//					
	//					if(result.Text!=null)
	//					{
	//						_multiFormatOneDReader = null;
	//						BeepOrVibrate();
	//						_parentViewController.BarCodeScanned(result);
	//					}
						
					} catch (Exception ex) {
						Console.WriteLine(ex.Message);
					}
					finally {
						if(bitmap!=null)
							bitmap = null;

						 if(source!=null)
							source = null;
						
		              //  if(srcbitmap!=null)
						//	srcbitmap = null;
					
						//if (_theScreenImage != null)
						//	_theScreenImage = null;

						
					}	
					}
				}
	      
	        }

			GC.Collect();

			//Console.WriteLine("Done.");

        }
        private void ProcessImage(BarcodeCaptureResult captureResults) {
            captureResults.State = CaptureState.Processing;
            try {
                bool bIsReady = captureResults.isReadyForProcessing.WaitOne(3000);
                if (!bIsReady) {
                    captureResults.State = CaptureState.UnknownError;
                    captureResults.ErrorMessage = "Error: Timeout waiting for images to be processed. Please try again or send issue report using app bar.";
                    return;
                }


                if (captureResults.VGABarcodeImage != null)
                {
                    var wb = captureResults.VGABarcodeImage;

                    //Code from: btnReadTag_Click in "SLZXingQRSample\SLZXingQRSample\SLZXingSample\MainPage.xaml.vb"
                    var qrRead = new com.google.zxing.oned.MultiFormatUPCEANReader(zxingHints); ; // new com.google.zxing.qrcode.QRCodeReader();
                    var luminiance = new RGBLuminanceSource(wb, 640, 480);
                    var binarizer = new com.google.zxing.common.HybridBinarizer(luminiance);
                    var binBitmap = new com.google.zxing.BinaryBitmap(binarizer);
                    var results = qrRead.decode(binBitmap, zxingHints); //NOTE: will throw exception if cannot decode image.
                    captureResults.BarcodeText = results.Text;
                    captureResults.State = CaptureState.Success;

                    BarcodeCaptured.Invoke(captureResults);
                    //captureResults.ProcessValue();
                }
                else {
                    captureResults.State = CaptureState.UnknownError;
                    captureResults.ErrorMessage = "Cannot process image: invalid or null BitmapImage.";
                }
            }
            catch (Exception ex) {
                captureResults.ExceptionThrown = ex;
                if (ex is com.google.zxing.ReaderException) {
                    captureResults.ErrorMessage = "Error: Cannot decode barcode image. Please make sure scan mode is correct and try again.";
                    captureResults.State = CaptureState.ScanFailed;
                }
                else {
                    Debug.WriteLine("Error: " + ex.ToString());
                    captureResults.ErrorMessage = String.Format("Barcode Library Processing Error: {0}\r\n{1}", ex.GetType(), ex.Message);
                    captureResults.State = CaptureState.UnknownError;
                }
            }
            finally
            {
                lock (_resultTaskLock)
                {
                    _resultTask = null;
                }
            }
            
        }
        private void Worker()
        {
            float fY1;
                float fY2;

                float scale;

                // calculate picFrame just once
                if (picFrame == RectangleF.Empty)
                {

                    // check if device has retina display, if so scale factor by 2
                    if (UIScreen.MainScreen.RespondsToSelector(new MonoTouch.ObjCRuntime.Selector(@"scale")) &&
                        UIScreen.MainScreen.Scale == 2)
                        scale = 2f;
                    else
                        scale = 1f;

                    // check if the device is an ipad or an iphone
                    if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Phone)
                    {
                        fY1 = 146f / UIScreen.MainScreen.Bounds.Height * scale;
                        fY2 = 157f / UIScreen.MainScreen.Bounds.Height * scale;
                    }
                    else
                    {
                        // ipad - constants probably need to be modified if running at native screen res

                        fY1 = 146f / UIScreen.MainScreen.Bounds.Height * scale;
                        fY2 = 157f / UIScreen.MainScreen.Bounds.Height * scale;
                    }

                    picFrame = new RectangleF(0, UIScreen.MainScreen.Bounds.Height * fY1, UIScreen.MainScreen.Bounds.Width * scale, UIScreen.MainScreen.Bounds.Height * fY2);
                }

                if(hints==null)
                {
                    var list = new ArrayList();
                    list.Add(com.google.zxing.BarcodeFormat.EAN_8);
                    list.Add(com.google.zxing.BarcodeFormat.EAN_13);

                    hints = new Hashtable();
                    hints.Add(com.google.zxing.DecodeHintType.POSSIBLE_FORMATS, list);
                    hints.Add(com.google.zxing.DecodeHintType.NEED_RESULT_POINT_CALLBACK, new ResultCallBack(this));
                }

                if(_multiFormatOneDReader == null)
                {
                    _multiFormatOneDReader = new com.google.zxing.oned.MultiFormatOneDReader(hints);
                }

                // Capturing screen image
                using (var screenImage = CGImage.ScreenImage.WithImageInRect(picFrame))
                {
                    _theScreenImage = UIImage.FromImage(screenImage);
                    Bitmap srcbitmap = new System.Drawing.Bitmap(_theScreenImage);
                    LuminanceSource source = null;
                    BinaryBitmap bitmap = null;
                    try {
                        source = new RGBLuminanceSource(srcbitmap, screenImage.Width, screenImage.Height);
                      	bitmap = new BinaryBitmap(new HybridBinarizer(source));

                        com.google.zxing.common.BitArray row = new com.google.zxing.common.BitArray(screenImage.Width);
                        int middle = screenImage.Height >> 1;
                        int rowStep = System.Math.Max(1, screenImage.Height >> (4));

                        for (int x = 0; x < 9; x++)
                        {

                            // Scanning from the middle out. Determine which row we're looking at next:
                            int rowStepsAboveOrBelow = (x + 1) >> 1;
                            bool isAbove = (x & 0x01) == 0; // i.e. is x even?
                            int rowNumber = middle + rowStep * (isAbove?rowStepsAboveOrBelow:- rowStepsAboveOrBelow);
                            if (rowNumber < 0 || rowNumber >= screenImage.Height)
                            {
                                // Oops, if we run off the top or bottom, stop
                                break;
                            }

                            // Estimate black point for this row and load it:
                            try
                            {
                                row = bitmap.getBlackRow(rowNumber, row);

                                var resultb = _multiFormatOneDReader.decodeRow(rowNumber, row, hints);
                                if(resultb.Text!=null)
                                {
                                    BeepOrVibrate();
                                    _parentViewController.BarCodeScanned(resultb);

                                    break;
                                }
                                else {
                                    continue;
                                }

                            }
                            catch (ReaderException re)
                            {
                                continue;
                            }

                        }

            //					var result = _barcodeReader.decodeWithState(bitmap);
            //
            //					if(result.Text!=null)
            //					{
            //						_multiFormatOneDReader = null;
            //						BeepOrVibrate();
            //						_parentViewController.BarCodeScanned(result);
            //					}

                    } catch (Exception ex) {
                        Console.WriteLine(ex.Message);
                    }
                    finally {
                        if(bitmap!=null)
                            bitmap = null;

                         if(source!=null)
                            source = null;

                        if(srcbitmap!=null)
                            srcbitmap = null;

                    }

                }
        }
示例#19
0
        private Result DetectQRC(string file, Hashtable hints)
        {
            Image img = null;
            LuminanceSource source = null;
            BinaryBitmap bitmap = null;
            Binarizer binarizer = null;
            Reader reader = null;
            Result QRCodeResult = null;

            img = Image.FromFile(file);
            Bitmap bmp = new Bitmap(img);
            source = new RGBLuminanceSource(bmp, img.Width, img.Height);

            ZXingConfig[] configs = ZXingConfig.getInstances(source);
            foreach (ZXingConfig config in configs) {

                reader = config.reader;
                binarizer = config.binarizer;
                bitmap = new BinaryBitmap(binarizer);
                try {
                    QRCodeResult = reader.decode(bitmap, hints);
                } catch (Exception) {
                }
            }
            return QRCodeResult;
        }
示例#20
0
        void decoder_DoWork(object sender, DoWorkEventArgs e)
        {
            Bitmap bmp = (Bitmap)e.Argument;
            QRCodeReader reader = new QRCodeReader();
            RGBLuminanceSource source = new RGBLuminanceSource(bmp, bmp.Width, bmp.Height);

            BinaryBitmap binDecode = new BinaryBitmap(new HybridBinarizer(source));

            String decodedString = "";
            Result result;
            try
            {
                result = (Result)reader.decode(binDecode);
                decodedString = result.Text;
            }
            catch (ReaderException)
            {
                decodedString = "";
            }

            if (decodedString == "")
            {
                toolStripStatusLabel1.Text = "Scan a Player ID";
            }
            else
            {
                String[] items = (decodedString).Split('|');

                this.Invoke((MethodInvoker)delegate//run on UI thread
                {
                    label_Name.Text = "Name: " + items[0];
                    label_Kill.Text = "Kill ID: " + items[1];
                    toolStripStatusLabel1.Text = "Decoded";
                });
            }
        }
			public override void DidOutputSampleBuffer (AVCaptureOutput captureOutput, CMSampleBuffer sampleBuffer, AVCaptureConnection connection)
			{
				try {

					if (!gotResult)
					{
						LuminanceSource luminance;
						//connection.VideoOrientation = AVCaptureVideoOrientation.Portrait;

						using (var pixelBuffer = sampleBuffer.GetImageBuffer () as CVPixelBuffer) {
		
							if (bytes == null)
								bytes = new byte [pixelBuffer.Height * pixelBuffer.BytesPerRow];
		
							pixelBuffer.Lock (0);
							Marshal.Copy (pixelBuffer.BaseAddress, bytes, 0, bytes.Length);
		
							luminance = new RGBLuminanceSource (bytes, pixelBuffer.Width, pixelBuffer.Height);


							pixelBuffer.Unlock (0);
						}

						var binarized = new BinaryBitmap (new HybridBinarizer (luminance));
						var result = reader.decodeWithState (binarized);

						//parent.session.StopRunning ();

						gotResult = true;

					
						if (parent.Scan != null)
							parent.Scan (result);
					}

				} catch (ReaderException) {

					// ignore this exception; it happens every time there is a failed scan

				} catch (Exception e) {

					// TODO: this one is unexpected.. log or otherwise handle it

					throw;

				} finally {
					try {
						// lamest thing, but seems that this throws :(
						sampleBuffer.Dispose ();
					} catch { }
				}
			}
示例#22
0
        private string DecodeImage(Image image)
        {
            //image = image.Substring("data:image/png;base64,".Length);

            //var buffer = Convert.FromBase64String(image);
            //// TODO: I am saving the image on the hard disk but
            //// you could do whatever processing you want with it
            //string documentName = DateTime.Now.ToString("yyyyMMddHHmmssfff")+".png";
            //System.IO.File.WriteAllBytes(Server.MapPath("~/app_data/"+documentName), buffer);
            //byte[] bytes = Convert.FromBase64String(image);

            //Image _image;
            //using (MemoryStream ms = new MemoryStream(bytes))
            //{
            //    _image = Image.FromStream(ms);
            //}
            Result result = null;
            try
            {
                Reader reader = new com.google.zxing.MultiFormatReader();
                Bitmap image1 = new Bitmap(image);
                LuminanceSource source = new RGBLuminanceSource(image1, image1.Width, image1.Height);
                BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
                result = reader.decode(bitmap);
                //QRCodeDecoder decoder = new QRCodeDecoder();
                ////QRCodeDecoder.Canvas = new ConsoleCanvas();
                //String decodedString = decoder.decode(new QRCodeBitmapImage(new Bitmap(_image)));
                ////txtDecodedData.Text = decodedString;
            }
            catch
            {
                return null;
            }
            return result.Text;
        }
示例#23
-1
 /// Processes the specified bitmap.
 public string Process(Bitmap bitmap)
 {
     try
     {
         com.google.zxing.LuminanceSource source = new RGBLuminanceSource(bitmap, bitmap.Width, bitmap.Height);
         var binarizer = new HybridBinarizer(source);
         var binBitmap = new BinaryBitmap(binarizer);
         return reader.decode(binBitmap).Text;
     }
     catch
     {
         return string.Empty;
     }
 }