Exemple #1
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;
            }
        }
Exemple #2
0
        private bool Zxing()
        {
            LuminanceSource source = new RGBLuminanceSource(img, img.Width, img.Height);

            com.google.zxing.BinaryBitmap bitmap1 = new com.google.zxing.BinaryBitmap(new HybridBinarizer(source));
            Result result;

            try
            {
                result    = new MultiFormatReader().decode(bitmap1);
                isScaning = false;
                scanTimer.Stop();
                System.Windows.Application.Current.Dispatcher.BeginInvoke(new Action(() =>
                {
                    btnScan.Content = "Scan";
                    tbQRCode.Text   = result.Text;
                }));

                return(true);
            }
            catch
            {
                return(false);
            }
        }
Exemple #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)) ;
        }
        private bool Zxing()
        {
            LuminanceSource source = new RGBLuminanceSource(img, img.Width, img.Height);

            com.google.zxing.BinaryBitmap bitmap1 = new com.google.zxing.BinaryBitmap(new HybridBinarizer(source));
            Result result;

            try
            {
                result = new MultiFormatReader().decode(bitmap1);
                Camera.Stop();
                scanTimer.Stop();
                System.Windows.Application.Current.Dispatcher.BeginInvoke(new Action(() =>
                {
                    epStatus.Visibility   = Visibility.Visible;
                    imgScan.Visibility    = Visibility.Collapsed;
                    QRCodeInfo qRCodeInfo = new QRCodeInfo(this, result.Text);
                    qRCodeInfo.Show();
                }));
                return(true);
            }
            catch
            {
                return(false);
            }
        }
        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 "";
            }
        }
Exemple #6
0
 private void DoQrToBin(string filename)
 {
     try
     {
         var fileStream = File.OpenRead(filename);
         var img = Image.FromStream(fileStream);
         var bmp = new Bitmap(img);
         fileStream.Close();
         var binary = new BinaryBitmap(new HybridBinarizer(new RGBLuminanceSource(bmp, bmp.Width, bmp.Height)));
         var reader = new QRCodeReader();
         var result = reader.decode(binary);
         var resultList = (ArrayList)result.ResultMetadata[ResultMetadataType.BYTE_SEGMENTS];
         if (resultList == null)
         {
             File.WriteAllBytes(filename + ".txt", Encoding.UTF8.GetBytes(result.Text));
             System.Diagnostics.Process.Start(filename + ".txt");
             txtQRText.Text = result.Text;
         }
         else
             File.WriteAllBytes(filename + ".bin", (byte[]) resultList[0]);
     }
     catch (ReaderException ex)
     {
         MessageBox.Show(@"Error Loading:" + Environment.NewLine + ex.Message);
     }
 }
Exemple #7
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;
        }
Exemple #8
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;
            }
        }
Exemple #9
0
        public static string Decode(string path)
        {
            Image           img    = Image.FromFile(path);
            Bitmap          bmap   = new Bitmap(img);
            LuminanceSource source = new RGBLuminanceSource(bmap, bmap.Width, bmap.Height);

            com.google.zxing.BinaryBitmap bitmap = new com.google.zxing.BinaryBitmap(new com.google.zxing.common.HybridBinarizer(source));
            return(new MultiFormatReader().decode(bitmap).Text);
        }
        private void button3_Click(object sender, EventArgs e)
        {
            if (this.pictureBox1.Image == null)
            {
                return;
            }
            Image  img = this.pictureBox1.Image;
            Bitmap bmap;

            try
            {
                bmap = new Bitmap(img);
            }
            catch (System.IO.IOException ioe)
            {
                MessageBox.Show(ioe.ToString());
                return;
            }
            if (bmap == null)
            {
                MessageBox.Show("无法解析该图像!");
                return;
            }
            LuminanceSource source = new RGBLuminanceSource(bmap, bmap.Width, bmap.Height);

            com.google.zxing.BinaryBitmap bitmap = new com.google.zxing.BinaryBitmap(new HybridBinarizer(source));
            Result result;

            try
            {
                result = new MultiFormatReader().decode(bitmap);
            }
            catch (ReaderException re)
            {
                MessageBox.Show("解码出现异常,可能不支持此编码!", "提示");
                //MessageBox.Show(re.ToString());
                return;
            }
            this.textBox1.Text = result.Text;
            if (result.BarcodeFormat == BarcodeFormat.DATAMATRIX)
            {
                this.lblFormat.Text = "Datamatrix";
            }
            else if (result.BarcodeFormat == BarcodeFormat.PDF417)
            {
                this.lblFormat.Text = "PDF417";
            }
            else if (result.BarcodeFormat == BarcodeFormat.QR_CODE)
            {
                this.lblFormat.Text = "QR Code";
            }
            else
            {
                this.lblFormat.Text = "未知格式";
            }
        }
Exemple #11
0
        public string findQrCodeText(com.google.zxing.Reader decoder, Bitmap bitmap)
        {
            var rgb    = new RGBLuminanceSource(bitmap, bitmap.Width, bitmap.Height);
            var hybrid = new com.google.zxing.common.HybridBinarizer(rgb);

            com.google.zxing.BinaryBitmap binBitmap = new com.google.zxing.BinaryBitmap(hybrid);
            string decodedString = decoder.decode(binBitmap, null).Text;

            return(decodedString);
        }
 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
     {
     }
 }
Exemple #13
0
        /// <summary>
        /// 从二维码图片读取二维码信息
        /// </summary>
        /// <param name="bmap"></param>
        /// <returns></returns>
        public static string ReadCode(Bitmap bmap)
        {
            if (bmap == null)
            {
                throw new Exception("Invalid code pictures.");
            }

            LuminanceSource source = new RGBLuminanceSource(bmap, bmap.Width, bmap.Height);

            com.google.zxing.BinaryBitmap bitmap = new com.google.zxing.BinaryBitmap(new HybridBinarizer(source));
            Result result;

            result = new MultiFormatReader().decode(bitmap);
            // 如果要捕获异常,用 catch (ReaderException re), re.ToString();

            return(result.Text);
        }
Exemple #14
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
//ORIGINAL LINE: private Result decodeInternal(BinaryBitmap image) throws NotFoundException
        private Result decodeInternal(BinaryBitmap image)
        {
            if (readers != null)
            {
                foreach (Reader reader in readers)
                {
                    try
                    {
                        return(reader.decode(image, hints));
                    }
                    catch (ReaderException re)
                    {
                        // continue
                    }
                }
            }
            throw NotFoundException.NotFoundInstance;
        }
        private Result decodeInternal(BinaryBitmap image)
        {
            int size = readers.Count;

            for (int i = 0; i < size; i++)
            {
                Reader reader = (Reader)readers[i];
                try
                {
                    return(reader.decode(image, hints));
                }
                catch (ReaderException)
                {
                    // continue
                }
            }

            throw ReaderException.Instance;
        }
Exemple #16
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;
        }
Exemple #17
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 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";
            }
        }
Exemple #20
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);        
        }
Exemple #21
0
        private void ScanPreviewBuffer()
        {
            try
            {
                lblQR.Text = "No se detecta ningún código QR";
                _photoCamera.GetPreviewBufferY(_luminance.PreviewBufferY);
                var binarizer = new HybridBinarizer(_luminance);
                var binBitmap = new BinaryBitmap(binarizer);
                var result = _reader.decode(binBitmap);

                var scan = result.Text;
                lblQR.Text = "Escanea un código de Museos App";
                //System.Media.SystemSounds.Beep.Play();
                //System.Media.SystemSounds.Asterisk.Play();
                //SystemSounds.Beep.Play();
                /*Stream stream = TitleContainer.OpenStream("/Assets/cartel.mp3");
                SoundEffect effect = SoundEffect.FromStream(stream);
                FrameworkDispatcher.Update();
                effect.Play();*/
                //mediaElement.Play();

                var textId = scan.Remove(0, 42);
                System.Diagnostics.Debug.WriteLine("ID DEL TEXTO: " + textId);
                var textQR = scan.Remove(42, 1);
                System.Diagnostics.Debug.WriteLine("TEXTO DEL QR: " + textQR);

                if (textQR.Equals("http://museosapp.azurewebsites.net/Piezas/"))
                {
                    lblQR.Text = "Código QR correcto";
                    NavigationService.Navigate(new Uri("/InfoQR.xaml?id=" + textId, UriKind.Relative));
                    _timer.Stop();
                }

                Dispatcher.BeginInvoke(() => DisplayResult(result.Text));
            }
            catch
            {
            }            
        }
        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;
            }
        }
Exemple #23
0
 /// <summary> Decode an image using the hints provided. Does not honor existing state.
 ///
 /// </summary>
 /// <param name="image">The pixel data to decode
 /// </param>
 /// <param name="hints">The hints to use, clearing the previous state.
 /// </param>
 /// <returns> The contents of the image
 /// </returns>
 /// <throws>  ReaderException Any errors which occurred </throws>
 // public Result decode(BinaryBitmap image, System.Collections.Hashtable hints) // commented by .net follower (http://dotnetfollower.com)
 public Result decode(BinaryBitmap image, System.Collections.Generic.Dictionary <Object, Object> hints) // added by .net follower (http://dotnetfollower.com)
 {
     Hints = hints;
     return(decodeInternal(image));
 }
 /// <summary> This version of decode honors the intent of Reader.decode(BinaryBitmap) in that it
 /// passes null as a hint to the decoders. However, that makes it inefficient to call repeatedly.
 /// Use setHints() followed by decodeWithState() for continuous scan applications.
 ///
 /// </summary>
 /// <param name="image">The pixel data to decode
 /// </param>
 /// <returns> The contents of the image
 /// </returns>
 /// <throws>  ReaderException Any errors which occurred </throws>
 public Result decode(BinaryBitmap image)
 {
     Hints = null;
     return(decodeInternal(image));
 }
		/// <summary> Decode an image using the hints provided. Does not honor existing state.
		/// 
		/// </summary>
		/// <param name="image">The pixel data to decode
		/// </param>
		/// <param name="hints">The hints to use, clearing the previous state.
		/// </param>
		/// <returns> The contents of the image
		/// </returns>
		/// <throws>  ReaderException Any errors which occurred </throws>
		public Result decode(BinaryBitmap image, System.Collections.Hashtable hints)
		{
			Hints = hints;
			return decodeInternal(image);
		}
 /// <summary> Decode an image using the hints provided. Does not honor existing state.
 ///
 /// </summary>
 /// <param name="image">The pixel data to decode
 /// </param>
 /// <param name="hints">The hints to use, clearing the previous state.
 /// </param>
 /// <returns> The contents of the image
 /// </returns>
 /// <throws>  ReaderException Any errors which occurred </throws>
 public Result decode(BinaryBitmap image, System.Collections.Hashtable hints)
 {
     Hints = hints;
     return(decodeInternal(image));
 }
Exemple #27
0
        /// <summary>
        /// Decode an image using the hints provided. Does not honor existing state.
        /// </summary>
        /// <param name="image"> The pixel data to decode </param>
        /// <param name="hints"> The hints to use, clearing the previous state. </param>
        /// <returns> The contents of the image </returns>
        /// <exception cref="NotFoundException"> Any errors which occurred </exception>
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
//ORIGINAL LINE: public Result decode(BinaryBitmap image, java.util.Map<DecodeHintType,?> hints) throws NotFoundException
        public Result decode(BinaryBitmap image, IDictionary <DecodeHintType, object> hints)
        {
            Hints = hints;
            return(decodeInternal(image));
        }
        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;

                    }

                }
        }
		public void OnPreviewFrame (byte [] bytes, Android.Hardware.Camera camera)
		{

			try {

				byte[] rotatedData = new byte[bytes.Length];
				for (int y = 0; y < height; y++) {
				    for (int x = 0; x < width; x++)
				        rotatedData[x * height + height - y - 1] = bytes[x + y * width];
				}

				var dataRect = GetFramingRectInPreview();

				var luminance = new YUVLuminanceSource ((sbyte[])(Array)rotatedData, width, height, dataRect.Left, dataRect.Top, dataRect.Width(), dataRect.Height());
				var binarized = new BinaryBitmap (new HybridBinarizer (luminance));
				var result = reader.decodeWithState (binarized);

				//drawResultPoints(binarized, result);

				// an exception would be thrown before this point if the QR code was not detected

				if (string.IsNullOrEmpty (result.Text))
					return;

				Android.Util.Log.Debug("AEGISSHIELD", "Barcode Found: " + result.Text);
				//ShutdownCamera ();

				ShutdownCamera();

				activity.OnScan (result);



			} catch (ReaderException) {
				Android.Util.Log.Debug("AEGISSHIELD", "No barcode Found");
				// ignore this exception; it happens every time there is a failed scan

			} catch (Exception){

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

				throw;
			}
		}
 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()
        {
       
				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 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();
             BarCodeResult barCodeResult = new BarCodeResult(TaskResult.OK);
             barCodeResult.result = result.Text;
             Dispatcher.BeginInvoke(() =>
             {
                 this.result = barCodeResult;
                 if (this.NavigationService.CanGoBack)
                 {
                     this.NavigationService.GoBack();
                 }
             });
         }
         else
         {
             _photoCamera.Focus();
         }
     }
     catch
     {
         //do nothing
     }
 }
 private void openQRCodeToolStripMenuItem_Click(object sender, EventArgs e)
 {
     var ofd = new OpenFileDialog { Filter = "All Supported|*.png;*.jpg;*.bmp;*.gif|PNG Files|*.png|Jpeg Files|*.jpg|Bitmap Files|*.bmp|GIF Files|*.gif" };
     if (ofd.ShowDialog() != DialogResult.OK) return;
     try
     {
         var file = new FileStream(ofd.FileName, FileMode.Open);
         var bmp = new Bitmap(Image.FromStream(file));
         file.Close();
         var binary = new BinaryBitmap(new HybridBinarizer(new RGBLuminanceSource(bmp, bmp.Width, bmp.Height)));
         var reader = new QRCodeReader();
         var hashtable = new Hashtable();
         hashtable.Add(DecodeHintType.POSSIBLE_FORMATS,BarcodeFormat.QR_CODE);
         hashtable.Add(DecodeHintType.TRY_HARDER,true);
         var result = reader.decode(binary, hashtable);
         var byteArray = (byte[])((ArrayList)result.ResultMetadata[ResultMetadataType.BYTE_SEGMENTS])[0];
         load_QR_data(byteArray);
     }
     catch (ReaderException ex)
     {
         MessageBox.Show("Error Loading:" + Environment.NewLine + ex.Message);
     }
     catch (InvalidOperationException ex)
     {
         MessageBox.Show("Error Loading:" + Environment.NewLine + ex.Message);
     }
 }
 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;
 }
			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 { }
				}
			}
Exemple #36
0
        private void open_Click(object sender, EventArgs e)
        {
            if (p1.Visible == true)
            {
                if (this.openFileDialog1.ShowDialog() != DialogResult.OK)
                {
                    return;
                }
                string path = this.openFileDialog1.FileName;
                openFileDialog1.DefaultExt = "*.txt";
                openFileDialog1.Filter     = "*.txt|";
                if (path.EndsWith(".txt"))
                {
                    string content = File.ReadAllText(path, Encoding.Default);
                    this.txtContent.Text = content;
                }
                else
                {
                    MessageBox.Show("只能读取txt文件", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            else
            {
                if (this.openFileDialog1.ShowDialog() != DialogResult.OK)
                {
                    return;
                }
                string path = this.openFileDialog1.FileName;
                if (!path.EndsWith(".png"))
                {
                    MessageBox.Show("图像格式不正确,只能读取png文件", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                else
                {
                    Image  img = Image.FromFile(path);
                    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;
                    }
                    else
                    {
                        this.picOpenQr.Image = bmap;
                    }
                    LuminanceSource source = new RGBLuminanceSource(bmap, bmap.Width, bmap.Height);
                    com.google.zxing.BinaryBitmap bitmap = new com.google.zxing.BinaryBitmap(new com.google.zxing.common.HybridBinarizer(source));
                    Result result;
                    try
                    {
                        result = new MultiFormatReader().decode(bitmap);
                    }
                    catch (ReaderException re)
                    {
                        MessageBox.Show(re.ToString());
                        return;
                    }

                    this.txtDencoder.Text = (result.Text);
                }
            }
        }
Exemple #37
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(() =>
             {
                 if (WebHelper.Instance.InternetIsAvailableNotify())
                 {
                     NavigationService.Navigate(new Uri("/BookDetailPanoramaPage.xaml?isbn=" + result.Text, UriKind.Relative));
                 }
                 else
                 {
                     if (NavigationService.CanGoBack)
                         NavigationService.GoBack();
                 }
             });
         }
         else
         {
             _photoCamera.Focus();
         }
     }
     catch
     {
     }
 }
        private void ScanPreviewBuffer()
        {
            string returnedString = null;

            photoCamera.GetPreviewBufferY(luminance.PreviewBufferY);
            var binarizer = new HybridBinarizer(luminance);
            var binBitmap = new BinaryBitmap(binarizer);
            var img = GetImage(luminance.PreviewBufferY);
            WP7BarcodeManager.ScanBarcode(img, result =>
                {
                    Debug.WriteLine(result.BarcodeImage);
                });
            
            try
            {                
                var result = ean13Reader.decode(binBitmap);
                returnedString = result.Text;
                Debug.WriteLine("EAN13  " + returnedString);
                return;
            }
            catch(Exception ex)
            {
            }

            try
            {
                var result = qrReader.decode(binBitmap);
                returnedString = result.Text;
                Debug.WriteLine("QR  " + returnedString);
                return;
            }
            catch (Exception ex)
            {
            }

            try
            {        
                var result = code39Reader.decode(binBitmap);
                returnedString = result.Text;
                Debug.WriteLine("CODE39  " + returnedString);
                return;
            }
            catch (Exception ex)
            {

            }
        }
        private Result decodeInternal(BinaryBitmap image)
        {
            int size = readers.Count;
            for (int i = 0; i < size; i++)
            {
                Reader reader = (Reader) readers[i];
                try
                {
                    return reader.decode(image, hints);
                }
                catch (ReaderException re)
                {
                    // continue
                }
            }

            throw ReaderException.Instance;
        }
Exemple #40
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);
                }
            }
        }
 /// <summary> Decode an image using the state set up by calling setHints() previously. Continuous scan
 /// clients will get a <b>large</b> speed increase by using this instead of decode().
 /// 
 /// </summary>
 /// <param name="image">The pixel data to decode
 /// </param>
 /// <returns> The contents of the image
 /// </returns>
 /// <throws>  ReaderException Any errors which occurred </throws>
 public Result decodeWithState(BinaryBitmap image)
 {
     // Make sure to set up the default state so we don't crash
     if (readers == null)
     {
         Hints = null;
     }
     return decodeInternal(image);
 }
 // added by .net follower (http://dotnetfollower.com)
 /// <summary> Decode an image using the hints provided. Does not honor existing state.
 /// 
 /// </summary>
 /// <param name="image">The pixel data to decode
 /// </param>
 /// <param name="hints">The hints to use, clearing the previous state.
 /// </param>
 /// <returns> The contents of the image
 /// </returns>
 /// <throws>  ReaderException Any errors which occurred </throws>
 // public Result decode(BinaryBitmap image, System.Collections.Hashtable hints) // commented by .net follower (http://dotnetfollower.com)
 public Result decode(BinaryBitmap image, System.Collections.Generic.Dictionary<Object, Object> hints)
 {
     Hints = hints;
     return decodeInternal(image);
 }
 /// <summary> This version of decode honors the intent of Reader.decode(BinaryBitmap) in that it
 /// passes null as a hint to the decoders. However, that makes it inefficient to call repeatedly.
 /// Use setHints() followed by decodeWithState() for continuous scan applications.
 /// 
 /// </summary>
 /// <param name="image">The pixel data to decode
 /// </param>
 /// <returns> The contents of the image
 /// </returns>
 /// <throws>  ReaderException Any errors which occurred </throws>
 public Result decode(BinaryBitmap image)
 {
     Hints = null;
     return decodeInternal(image);
 }
        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
            {
            }
        }
 /// 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;
     }
 }