Пример #1
1
	public static Result DecodeImage(Texture2D tex)
	{
		Color32LuminanceSource colLumSource = new Color32LuminanceSource(tex.GetPixels32(), tex.width, tex.height);
		HybridBinarizer hybridBinarizer = new HybridBinarizer(colLumSource);
		BinaryBitmap bitMap = new BinaryBitmap(hybridBinarizer);
		//We reset before we decode for safety;


		CodeReader.reset();

		return CodeReader.decode(bitMap);
	}
Пример #2
1
      private Result decode(Uri uri, string originalInput, IDictionary<DecodeHintType, object> hints)
      {
         Bitmap image;
         try
         {
            image = (Bitmap) Bitmap.FromFile(uri.LocalPath);
         }
         catch (Exception)
         {
            throw new FileNotFoundException("Resource not found: " + uri);
         }

         using (image)
         {
            LuminanceSource source;
            if (config.Crop == null)
            {
               source = new BitmapLuminanceSource(image);
            }
            else
            {
               int[] crop = config.Crop;
               source = new BitmapLuminanceSource(image).crop(crop[0], crop[1], crop[2], crop[3]);
            }
            BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
            if (config.DumpBlackPoint)
            {
               dumpBlackPoint(uri, image, bitmap, source);
            }
            Result result = new MultiFormatReader().decode(bitmap, hints);
            if (result != null)
            {
               if (config.Brief)
               {
                  Console.Out.WriteLine(uri + ": Success");
               }
               else
               {
                  ParsedResult parsedResult = ResultParser.parseResult(result);
                  var resultString = originalInput + " (format: " + result.BarcodeFormat + ", type: " + parsedResult.Type + "):" + Environment.NewLine;
                  for (int i = 0; i < result.ResultPoints.Length; i++)
                  {
                     ResultPoint rp = result.ResultPoints[i];
                     Console.Out.WriteLine("  Point " + i + ": (" + rp.X + ',' + rp.Y + ')');
                  }
                  resultString += "Raw result:" + Environment.NewLine + result.Text + Environment.NewLine;
                  resultString += "Parsed result:" + Environment.NewLine + parsedResult.DisplayResult + Environment.NewLine;

                  Console.Out.WriteLine(resultString);
                  ResultString = resultString;
               }
            }
            else
            {
               var resultString = originalInput + ": No barcode found";
               Console.Out.WriteLine(resultString);
               ResultString = resultString;
            }
            return result;
         }
      }
        static void ZXing_Test_Single(string file, ZXing.Multi.GenericMultipleBarcodeReader multiBarcodeReader)
        {
            Bitmap          bitmap = (Bitmap)Image.FromFile(file);
            LuminanceSource source = new BitmapLuminanceSource(bitmap);

            ZXing.BinaryBitmap bBitmap = new ZXing.BinaryBitmap(new HybridBinarizer(source));
            Stopwatch          swZXing = Stopwatch.StartNew();

            ZXing.Result[] zResults = multiBarcodeReader.decodeMultiple(bBitmap);
            swZXing.Stop();

            if (zResults != null)
            {
                //Console.WriteLine("ZXing\t time: " + swZXing.Elapsed.TotalMilliseconds + "ms" + ",\t result count: " + zResults.Length);
                Console.WriteLine("{0, -10}{1, -20}{2, -20}", "ZXing", "time: " + swZXing.Elapsed.TotalMilliseconds + "ms", " result count: " + zResults.Length);
            }
            else
            {
                //Console.WriteLine("ZXing\t time: " + swZXing.Elapsed.TotalMilliseconds + "ms" + ",\t result count: failed");
                Console.WriteLine("{0, -10}{1, -20}{2, -20}", "ZXing", "time: " + swZXing.Elapsed.TotalMilliseconds + "ms", " result count: failed");
            }

            if (zResults != null)
            {
                //foreach (ZXing.Result zResult in zResults)
                //{
                //    Console.WriteLine("ZXing result: " + zResult.Text);
                //}
            }
        }
Пример #4
0
 /// <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);
 }
Пример #5
0
        private static void imageWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            // scanning for a barcode
            var wbmp = (WriteableBitmap)e.Argument;

            var luminiance = new RGBLuminanceSource(wbmp, wbmp.PixelWidth, wbmp.PixelHeight);
            var binarizer = new HybridBinarizer(luminiance);
            var binBitmap = new BinaryBitmap(binarizer);
            var reader = new MultiFormatReader();
            e.Result = reader.decode(binBitmap);
        }
        /// <summary>
        /// برسی وجود کد QR در تصویر
        /// </summary>
        /// <param name="bitmapByteArray">تصویر مورد نظر در قالب آرایه ای از <c>byte</c></param>
        /// <param name="width">عرض تصویر به پیکسل</param>
        /// <param name="height">طور تصویر به پیکسل</param>
        /// <returns>نتیجه برسی</returns>
        public bool ContainsQRCode(byte[] bitmapByteArray, int width, int height)
        {
            ///[Checking picture for QR Code]
            ZXing.LuminanceSource        source    = new ZXing.RGBLuminanceSource(bitmapByteArray, width, height);
            ZXing.Common.HybridBinarizer binarizer = new ZXing.Common.HybridBinarizer(source);
            ZXing.BinaryBitmap           binBitmap = new ZXing.BinaryBitmap(binarizer);
            ZXing.Common.BitMatrix       bitMatrix = binBitmap.BlackMatrix;

            ZXing.Multi.QrCode.Internal.MultiDetector detector = new ZXing.Multi.QrCode.Internal.MultiDetector(bitMatrix);

            return(detector.detect() != null);
            ///[Checking picture for QR Code]
        }
Пример #7
0
 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
     {
     }
 }
Пример #8
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 = null;//[shove] new RGBLuminanceSource(bmap, bmap.Width, bmap.Height);

            ZXing.BinaryBitmap bitmap = new ZXing.BinaryBitmap(new HybridBinarizer(source));
            Result             result;

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

            return(result.Text);
        }
        static void ZXing_Test(string directory)
        {
            ZXing.MultiFormatReader multiFormatReader = new ZXing.MultiFormatReader();
            ZXing.Multi.GenericMultipleBarcodeReader multiBarcodeReader = new ZXing.Multi.GenericMultipleBarcodeReader(multiFormatReader);

            string[] files = Directory.GetFiles(directory);
            foreach (string file in files)
            {
                Console.WriteLine(file);
                Bitmap             bitmap   = (Bitmap)Image.FromFile(file);
                LuminanceSource    source   = new BitmapLuminanceSource(bitmap);
                ZXing.BinaryBitmap bBitmap  = new ZXing.BinaryBitmap(new HybridBinarizer(source));
                Stopwatch          swZXing  = Stopwatch.StartNew();
                ZXing.Result[]     zResults = multiBarcodeReader.decodeMultiple(bBitmap);
                swZXing.Stop();

                if (zResults != null)
                {
                    Console.WriteLine("ZXing time: " + swZXing.Elapsed.TotalMilliseconds + "ms" + ", result count: " + zResults.Length);
                }
                else
                {
                    Console.WriteLine("ZXing time: " + swZXing.Elapsed.TotalMilliseconds + "ms" + ", result count: failed");
                }

                if (zResults != null)
                {
                    //foreach (ZXing.Result zResult in zResults)
                    //{
                    //    Console.WriteLine("ZXing result: " + zResult.Text);
                    //}
                }

                Console.WriteLine("\n");
            }
        }
            public void CheckBarCode()
            {
                try {
                    using(var bbImage = new System.Drawing.Bitmap (codeImage)){
                        Reader barReader = new ZXing.QrCode.QRCodeReader();
                        //Reader barReader = new MultiFormatReader ();
                        LuminanceSource source = new RGBLuminanceSource (bbImage, (int)codeImage.Size.Width, (int)codeImage.Size.Height);
                        BinaryBitmap bb = new BinaryBitmap (new HybridBinarizer (source));

                        Result res = barReader.decode (bb);
                        InvokeOnMainThread (() => {
                            codeImage.Dispose();
                            if (res != null) {
                                //result has the string from the image
                                //AppDelegate.main.decryptVC.txtScanResult.Text = res.Text;
                                AppDelegate.main.decryptVC.ProcessScannedCode(res.Text);
                            } else {
                                //no valid code found;
                            }
                            numRuns++;
                            barChecking = false;
                        });
                    }

                } catch (Exception e) {
                    barChecking = false;
                    Console.WriteLine (e);
                }
            }
Пример #11
0
        public IndexModule()
        {
            Get["/"] = parameters =>
            {
                return View["index"];
            };

            Get["/upload"] = parameters =>
            {
                    return View["upload"];
            };

            Get["/certificate"] = parameters =>
            {
                return View["cert"];
            };

            Get["/result"] = parameters =>
            {
                string enhancedQRCodePath = Path.Combine("data", "qrdata") + @"\" + "EnhancedqrImage.bmp";
                Bitmap QRcodeImage = new Bitmap(Bitmap.FromFile(enhancedQRCodePath));

                Rectangle cropArea = new Rectangle();
                cropArea.Width = 357;
                cropArea.Height = 392;
                cropArea.X = (QRcodeImage.Width - cropArea.Width) / 2;
                cropArea.Y = (QRcodeImage.Height - cropArea.Height) / 2;
                Bitmap bmpCrop = QRcodeImage.Clone(cropArea, QRcodeImage.PixelFormat);

                string rawFPImage = Path.Combine("data", "qrdata") + @"\" + "fingerprint.bmp";
                bmpCrop.Save(rawFPImage);

                LuminanceSource source = new BitmapLuminanceSource(QRcodeImage);
                BinaryBitmap newbitmap = new BinaryBitmap(new HybridBinarizer(source));
                Result result = new MultiFormatReader().decodeWithState(newbitmap);

                if (result.Text != requestTime)
                {
                    return Response.AsJson(new { Result = "Authentication failure" });
                }
                else
                {
                    //Write your code here!(next time!)
                    //return Response.AsJson(new { Result = result.Text });
                }

                return Response.AsImage(rawFPImage);
            };

            Get["/securityUpload"] = parameters =>
            {
                return View["secert"];
            };

            Post["/severification"] = parameters =>
            {
                var file = this.Request.Files.ElementAt<HttpFile>(0);
                string uploadPath = Path.Combine("data", "test", file.Name);
                if (!Directory.Exists(Path.Combine("data", "test"))) Directory.CreateDirectory(Path.Combine("data", "test"));
                using (var fileStream = new FileStream(uploadPath, FileMode.Create))
                {
                    file.Value.CopyTo(fileStream);
                }

                string QRcodePath = Path.Combine("data", "qrdata") + @"\" + "qrImage.bmp";

                Bitmap fpImage = new Bitmap(Bitmap.FromFile(uploadPath));
                Bitmap RawQRImage = new Bitmap(Bitmap.FromFile(QRcodePath));

                Bitmap QRImage = new Bitmap(RawQRImage.Width, RawQRImage.Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
                using (Graphics g = Graphics.FromImage(QRImage))
                {
                    g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                    g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                    g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
                    g.DrawImage(RawQRImage, 0, 0);
                }

                int middleImgW = Math.Min((int)(realSize.Width / 3.5), fpImage.Width);
                int middleImgH = Math.Min((int)(realSize.Height / 3.5), fpImage.Height);
                int middleImgL = (QRImage.Width - middleImgW) / 2;
                int middleImgT = (QRImage.Height - middleImgH) / 2;

                System.Drawing.Graphics MyGraphic = System.Drawing.Graphics.FromImage(QRImage);

                MyGraphic.FillRectangle(Brushes.White, middleImgL, middleImgT, middleImgW, middleImgH);
                MyGraphic.DrawImage(fpImage, middleImgL, middleImgT, middleImgW, middleImgH);

                string enhancedQRCodePath = Path.Combine("data", "qrdata") + @"\" + "EnhancedqrImage.bmp";
                QRImage.Save(enhancedQRCodePath);
                return Response.AsImage(enhancedQRCodePath);
            };

            Get["/barcode"] = parameters =>
            {
                BarcodeWriter writer = new BarcodeWriter();
                writer.Format = BarcodeFormat.QR_CODE;
                writer.Options = new QrCodeEncodingOptions
                {
                    DisableECI = true,
                    CharacterSet = "UTF-8",
                    Width = 1840,
                    Height = 1840,
                    ErrorCorrection = ErrorCorrectionLevel.H
                };
                requestTime = DateTime.Now.ToString();
                Bitmap qrImage = writer.Write(requestTime);

                string path = Path.Combine("data", "qrdata");
                if (!Directory.Exists(path)) Directory.CreateDirectory(path);
                string imagePath = path + @"\" + "qrImage.bmp";
                qrImage.Save(imagePath);

                return Response.AsImage(imagePath);
            };


            Post["/verification"] = parameters =>
            {
                string userId = (string)this.Request.Form.userId;
                List<Model.Fingerprint> fingerprints = SqlHelper.getImages(userId);

                var file = this.Request.Files.ElementAt<HttpFile>(0);
                string uploadPath = Path.Combine("data", "test", file.Name);
                if (!Directory.Exists(Path.Combine("data", "test"))) Directory.CreateDirectory(Path.Combine("data", "test"));
                using (var fileStream = new FileStream(uploadPath, FileMode.Create))
                {
                    file.Value.CopyTo(fileStream);
                }
                SourceAFIS.Simple.Fingerprint fp1 = new SourceAFIS.Simple.Fingerprint();
                fp1.AsBitmap = new Bitmap(Bitmap.FromFile(uploadPath));
                Person person1 = new Person();
                person1.Fingerprints.Add(fp1);
                Afis.Extract(person1);

                List<MatchResult> results = new List<MatchResult>();

                foreach (var fp in fingerprints)
                {
                    SourceAFIS.Simple.Fingerprint fp2 = new SourceAFIS.Simple.Fingerprint();
                    fp2.AsBitmap = new Bitmap(Bitmap.FromFile(fp.fpPath));
                    Person person2 = new Person();
                    person2.Fingerprints.Add(fp2);
                    Afis.Extract(person2);


                    MatchResult result = new MatchResult();
                    result.fingerprint = fp.fpName + fp.sampleNumber.ToString();
                    result.score = Afis.Verify(person1, person2);

                    results.Add(result);
                }

                return Response.AsJson<List<MatchResult>>(results);
            };

            Post["/upload"] = parameters =>
            {
                User user = new User();
                Model.Fingerprint fp1 = new Model.Fingerprint();
                Model.Fingerprint fp2 = new Model.Fingerprint();
                Model.Fingerprint fp3 = new Model.Fingerprint();
                Model.Fingerprint fp4 = new Model.Fingerprint();
                Model.Fingerprint fp5 = new Model.Fingerprint();

                user.userId = (string)this.Request.Form.id;
                user.userName = (string)this.Request.Form.name;                

                fp1.fpName = (string)this.Request.Form.fpname1;
                fp2.fpName = (string)this.Request.Form.fpname2;
                fp3.fpName = (string)this.Request.Form.fpname3;
                fp4.fpName = (string)this.Request.Form.fpname4;
                fp5.fpName = (string)this.Request.Form.fpname5;

                fp1.sampleNumber = (int)this.Request.Form.samplenumber1;
                fp2.sampleNumber = (int)this.Request.Form.samplenumber2;
                fp3.sampleNumber = (int)this.Request.Form.samplenumber3;
                fp4.sampleNumber = (int)this.Request.Form.samplenumber4;
                fp5.sampleNumber = (int)this.Request.Form.samplenumber5;

                fp1.userID = user.userId;
                fp2.userID = user.userId;
                fp3.userID = user.userId;
                fp4.userID = user.userId;
                fp5.userID = user.userId;

                fp1.fpID = fp1.userID + fp1.fpName + fp1.sampleNumber.ToString();
                fp2.fpID = fp1.userID + fp2.fpName + fp2.sampleNumber.ToString();
                fp3.fpID = fp3.userID + fp3.fpName + fp3.sampleNumber.ToString();
                fp4.fpID = fp4.userID + fp4.fpName + fp4.sampleNumber.ToString();
                fp5.fpID = fp5.userID + fp5.fpName + fp5.sampleNumber.ToString();

                var file1 = this.Request.Files.ElementAt<HttpFile>(0);
                var file2 = this.Request.Files.ElementAt<HttpFile>(1);
                var file3 = this.Request.Files.ElementAt<HttpFile>(2);
                var file4 = this.Request.Files.ElementAt<HttpFile>(3);
                var file5 = this.Request.Files.ElementAt<HttpFile>(4);

                fp1.fpPath = @"data\" + user.userName + @"\" + fp1.fpID + file1.Name.Substring(file1.Name.Length -4,  4);
                fp2.fpPath = @"data\" + user.userName + @"\" + fp2.fpID + file2.Name.Substring(file2.Name.Length - 4, 4);
                fp3.fpPath = @"data\" + user.userName + @"\" + fp3.fpID + file3.Name.Substring(file3.Name.Length - 4, 4);
                fp4.fpPath = @"data\" + user.userName + @"\" + fp4.fpID + file4.Name.Substring(file4.Name.Length - 4, 4);
                fp5.fpPath = @"data\" + user.userName + @"\" + fp5.fpID + file5.Name.Substring(file5.Name.Length - 4, 4);

                //fp1.fpPath = Path.Combine("data", user.userName, fp1.fpID + file1.Name.Substring(file1.Name.Length - 4, 4));
                if (!Directory.Exists(Path.Combine("data", user.userName))) Directory.CreateDirectory(Path.Combine("data", user.userName));
                using (var fileStream = new FileStream(fp1.fpPath, FileMode.Create))
                {
                    file1.Value.CopyTo(fileStream);
                }
                using (var fileStream = new FileStream(fp2.fpPath, FileMode.Create))
                {
                    file2.Value.CopyTo(fileStream);
                }
                using (var fileStream = new FileStream(fp3.fpPath, FileMode.Create))
                {
                    file3.Value.CopyTo(fileStream);
                }
                using (var fileStream = new FileStream(fp4.fpPath, FileMode.Create))
                {
                    file4.Value.CopyTo(fileStream);
                }
                using (var fileStream = new FileStream(fp5.fpPath, FileMode.Create))
                {
                    file5.Value.CopyTo(fileStream);
                }

                if (!SqlHelper.isExistUser(user)) SqlHelper.insertToUser(user);
                int i1 = SqlHelper.insertToFingerprint(fp1);
                int i2 = SqlHelper.insertToFingerprint(fp2);
                int i3 = SqlHelper.insertToFingerprint(fp3);
                int i4 = SqlHelper.insertToFingerprint(fp4);
                int i5 = SqlHelper.insertToFingerprint(fp5);
                if (i1!=0 && i2!=0 && i3!=0 && i4!=0 && i5!=0)
                    return Response.AsJson(new { Result = "Insert Sucess" });
                else
                    return Response.AsJson(new { Result = "Insert Failed" });
            };

            Get["/getUser"] = parameters =>
            {
                string myconn = "Database='fingerprint';Data Source=localhost;User ID=lich;Password=123456;CharSet=utf8;";
                string mysql = "SELECT * from user";
                MySqlConnection myconnection = new MySqlConnection(myconn);
                myconnection.Open();
                MySqlCommand mycommand = new MySqlCommand(mysql, myconnection);
                MySqlDataReader myreader = mycommand.ExecuteReader();
                
                
                List<User> userList = new List<User>();
                while (myreader.Read())
                {
                    User user = new User();
                    user.userId = myreader.GetString(0);
                    user.userName = myreader.GetString(1);
                    userList.Add(user);
                }
                myreader.Close();
                myconnection.Close();                
                return Response.AsJson<List<User>>(userList);
            };

            Get["/inserttest"] = parameters =>
            {
                User user = new User();
                user.userId = "13T2001";
                user.userName = "******";
                int i = SqlHelper.insertToUser(user);
                if (i != 0) return Response.AsJson(new { Result = "Insert Sucess" });
                else return Response.AsJson(new { Result = "Insert Failed" });
            };
        }
Пример #12
0
      /**
       * Writes out a single PNG which is three times the width of the input image, containing from left
       * to right: the original image, the row sampling monochrome version, and the 2D sampling
       * monochrome version.
       */
      private static void dumpBlackPoint(Uri uri, Bitmap image, BinaryBitmap bitmap)
      {
         // TODO: Update to compare different Binarizer implementations.
         String inputName = uri.LocalPath;
         if (inputName.Contains(".mono.png"))
         {
            return;
         }

         // Use the current working directory for URLs
         String resultName = inputName;
         int pos;
         if ("http".Equals(uri.Scheme))
         {
            pos = resultName.LastIndexOf('/');
            if (pos > 0)
            {
               resultName = '.' + resultName.Substring(pos);
            }
         }
         pos = resultName.LastIndexOf('.');
         if (pos > 0)
         {
            resultName = resultName.Substring(0, pos);
         }
         resultName += ".mono.png";

         int width = bitmap.Width;
         int height = bitmap.Height;
         int stride = width * 3;
         var result = new Bitmap(stride, height, PixelFormat.Format32bppArgb);
         var offset = 0;

         // The original image
         for (int indexH = 0; indexH < height; indexH++)
         {
            for (int indexW = 0; indexW < width; indexW++)
            {
               result.SetPixel(indexW, indexH, image.GetPixel(indexW, indexH));
            }
         }

         // Row sampling
         BitArray row = new BitArray(width);
         offset += width;
         for (int y = 0; y < height; y++)
         {
            row = bitmap.getBlackRow(y, row);
            if (row == null)
            {
               // If fetching the row failed, draw a red line and keep going.
               for (int x = 0; x < width; x++)
               {
                  result.SetPixel(offset + x, y, Color.Red);
               }
               continue;
            }

            for (int x = 0; x < width; x++)
            {
               result.SetPixel(offset + x, y, row[x] ? Color.Black : Color.White);
            }
         }

         // 2D sampling
         offset += width;
         for (int y = 0; y < height; y++)
         {
            BitMatrix matrix = bitmap.BlackMatrix;
            for (int x = 0; x < width; x++)
            {
               result.SetPixel(offset + x, y, matrix[x, y] ? Color.Black : Color.White);
            }
         }

         result.Save(resultName, ImageFormat.Png);
      }
Пример #13
0
			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 { }
				}
			}
Пример #14
0
      private Result[] decodeMulti(Uri uri, IDictionary<DecodeHintType, object> hints)
      {
         Bitmap image;
         try
         {
            image = (Bitmap)Bitmap.FromFile(uri.LocalPath);
         }
         catch (Exception)
         {
            throw new FileNotFoundException("Resource not found: " + uri);
         }

         LuminanceSource source;
         if (config.Crop == null)
         {
            source = new BitmapLuminanceSource(image);
         }
         else
         {
            int[] crop = config.Crop;
            source = new BitmapLuminanceSource(image).crop(crop[0], crop[1], crop[2], crop[3]);
         }
         BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
         if (config.DumpBlackPoint)
         {
            dumpBlackPoint(uri, image, bitmap);
         }

         MultiFormatReader multiFormatReader = new MultiFormatReader();
         GenericMultipleBarcodeReader reader = new GenericMultipleBarcodeReader(
               multiFormatReader);
         Result[] results = reader.decodeMultiple(bitmap, hints);
         if (results != null && results.Length > 0)
         {
            if (config.Brief)
            {
               Console.Out.WriteLine(uri + ": Success");
            }
            else
            {
               foreach (var result in results)
               {
                  ParsedResult parsedResult = ResultParser.parseResult(result);
                  Console.Out.WriteLine(uri + " (format: "
                                          + result.BarcodeFormat + ", type: "
                                          + parsedResult.Type + "):\nRaw result:\n"
                                          + result.Text + "\nParsed result:\n"
                                          + parsedResult.DisplayResult);
                  Console.Out.WriteLine("Found " + result.ResultPoints.Length + " result points.");
                  for (int i = 0; i < result.ResultPoints.Length; i++)
                  {
                     ResultPoint rp = result.ResultPoints[i];
                     Console.Out.WriteLine("  Point " + i + ": (" + rp.X + ',' + rp.Y + ')');
                  }
               }
            }
            return results;
         }
         else
         {
            Console.Out.WriteLine(uri + ": No barcode found");
         }
         return null;
      }
Пример #15
0
        /// <summary>
        /// Scans the camera's preview buffer for a QR code.
        /// </summary>
        private void ScanPreviewBuffer()
        {
            int width = (int) _camera.PreviewResolution.Width;
            int height = (int) _camera.PreviewResolution.Height;
            byte[] pixelData = new byte[width * height];

            _camera.GetPreviewBufferY( pixelData );

            var luminance = new RGBLuminanceSource( pixelData, width, height, RGBLuminanceSource.BitmapFormat.Gray8 );
            var binarizer = new HybridBinarizer( luminance );
            var bitmap = new BinaryBitmap( binarizer );
            var result = new QRCodeReader().decode( bitmap );

            if ( result != null )
            {
                Dispatcher.BeginInvoke( () => ProcessResult( result ) );
            }
        }
Пример #16
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, Hashtable hints)
 {
     Hints = hints;
     return(decodeInternal(image));
 }
		private void Worker()
        {
       
				
				if(_multiFormatReader == null)
				{
				_multiFormatReader = this.Options.BuildMultiFormatReader();
				//_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
				//				} }
				//		}
				//	};
				}
				

			if (wasStopped)
				return;
				
			using (var ap = new NSAutoreleasePool())
			{
				try
				{
					// 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 != null && 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;

							
						}	
						}
					}
	      		
				}
				catch 
				{
				}
	        }

			GC.Collect();

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

        }
Пример #18
0
        /// <summary>
        /// Tries to decode barcodes within an image which is given by a luminance source.
        /// That method gives a chance to prepare a luminance source completely before calling
        /// the time consuming decoding method. On the other hand there is a chance to create
        /// a luminance source which is independent from external resources (like Bitmap objects)
        /// and the decoding call can be made in a background thread.
        /// </summary>
        /// <param name="luminanceSource">The luminance source.</param>
        /// <returns></returns>
        public virtual Result[] DecodeMultiple(LuminanceSource luminanceSource)
        {
            var results = default(Result[]);
            var binarizer = CreateBinarizer(luminanceSource);
            var binaryBitmap = new BinaryBitmap(binarizer);
            var rotationCount = 0;
            var rotationMaxCount = 1;
            MultipleBarcodeReader multiReader = null;

            if (AutoRotate)
            {
                Options.Hints[DecodeHintType.TRY_HARDER_WITHOUT_ROTATION] = true;
                rotationMaxCount = 4;
            }

            var formats = Options.PossibleFormats;
            if (formats != null &&
                formats.Count == 1 &&
                formats.Contains(BarcodeFormat.QR_CODE))
            {
                multiReader = new QRCodeMultiReader();
            }
            else
            {
                multiReader = new GenericMultipleBarcodeReader(Reader);
            }

            for (; rotationCount < rotationMaxCount; rotationCount++)
            {
                results = multiReader.decodeMultiple(binaryBitmap, Options.Hints);

                if (results == null)
                {
                    if (TryInverted && luminanceSource.InversionSupported)
                    {
                        binaryBitmap = new BinaryBitmap(CreateBinarizer(luminanceSource.invert()));
                        results = multiReader.decodeMultiple(binaryBitmap, Options.Hints);
                    }
                }

                if (results != null ||
                    !luminanceSource.RotateSupported ||
                    !AutoRotate)
                    break;

                binaryBitmap = new BinaryBitmap(CreateBinarizer(luminanceSource.rotateCounterClockwise()));
            }

            if (results != null)
            {
                foreach (var result in results)
                {
                    if (result.ResultMetadata == null)
                    {
                        result.putMetadata(ResultMetadataType.ORIENTATION, rotationCount * 90);
                    }
                    else if (!result.ResultMetadata.ContainsKey(ResultMetadataType.ORIENTATION))
                    {
                        result.ResultMetadata[ResultMetadataType.ORIENTATION] = rotationCount * 90;
                    }
                    else
                    {
                        // perhaps the core decoder rotates the image already (can happen if TryHarder is specified)
                        result.ResultMetadata[ResultMetadataType.ORIENTATION] =
                           ((int)(result.ResultMetadata[ResultMetadataType.ORIENTATION]) + rotationCount * 90) % 360;
                    }
                }

                OnResultsFound(results);
            }

            return results;
        }
	void Update()
	{
		if (!e_DeviceController.isPlaying  ) {
			return;
		}

		if (e_DeviceController.isPlaying && !decoding)
		{
			orginalc = e_DeviceController.cameraTexture.GetPixels32();
			W = e_DeviceController.cameraTexture.width;
			H = e_DeviceController.cameraTexture.height;
			WxH = W * H;
			targetbyte = new byte[ WxH ];
			z = 0;

			// convert the image color data
			for(int y = H - 1; y >= 0; y--) {
				for(int x = 0; x < W; x++) {
				//	targetbyte[z++] = (byte)( (((int)orginalc[y * W + x].r)+ ((int)orginalc[y * W + x].g) + ((int)orginalc[y * W + x].b))/3);

					targetbyte[z++]  = (byte)(((int)orginalc[y * W + x].r)<<16 | ((int)orginalc[y * W + x].g)<<8 | ((int)orginalc[y * W + x].b));
				}
			}

			Loom.RunAsync(() =>
			              {
				try
				{
					RGBLuminanceSource luminancesource = new RGBLuminanceSource(targetbyte, W, H, true);
					var bitmap = new BinaryBitmap(new HybridBinarizer(luminancesource.rotateCounterClockwise()));
					Result data;
					var reader = new MultiFormatReader();
		
					data = reader.decode(bitmap);
					if (data != null)
					{
						{
							decoding = true;
							dataText = data.Text;
						}
					}
					else 
					{
						for(int y = 0; y != targetbyte.Length; y++) {
							targetbyte[y] = (byte) ( 0xff - (targetbyte[y] &  0xff));
						}

						luminancesource = new RGBLuminanceSource(targetbyte, W, H, true);
						bitmap = new BinaryBitmap(new HybridBinarizer(luminancesource));

						data = reader.decode(bitmap);
						if (data != null)
						{
							{
								decoding = true;
								dataText = data.Text;
							}
						}
					}
				}
				catch (Exception e)
				{
					decoding = false;
				}
			});	
		}
		if(decoding)
		{
			if(tempDecodeing != decoding)
			{
				e_QRScanFinished(dataText);//triger the  sanfinished event;
			}
			tempDecodeing = decoding;
		}
	}
Пример #20
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, IDictionary<DecodeHintType, object> hints)
 {
    Hints = hints;
    return decodeInternal(image);
 }
Пример #21
0
        public bool DetectQRCode()
        {
            var qrReader = new QRCodeMultiReader();

            var qrReaderHints = new Dictionary<DecodeHintType, object>() {
                { DecodeHintType.TRY_HARDER, true }
            };

            var qrImageSource = new BitmapLuminanceSource((Bitmap)Image);

            var qrBinarizer = new HybridBinarizer(qrImageSource);
            var qrBinaryBitmap = new BinaryBitmap(qrBinarizer);

            try
            {
                qrCodeResult = qrReader.decodeMultiple(qrBinaryBitmap, qrReaderHints)?.FirstOrDefault();
                qrCodeResultScale = 1F;
            }
            catch (ReaderException)
            {
                // QR Detection Failed
                qrCodeResult = null;
            }

            if (qrCodeResult == null)
            {
                var sizePoints = PdfiumDocument.PageSizes[PageIndex];

                // Try at 175%
                using (var image = PdfiumDocument.Render(PageIndex, (int)(sizePoints.Width * 1.75), (int)(sizePoints.Height * 1.75), 72F, 72F, false))
                {
                    qrImageSource = new BitmapLuminanceSource((Bitmap)image);

                    // Try Entire Image
                    qrBinarizer = new HybridBinarizer(qrImageSource);
                    qrBinaryBitmap = new BinaryBitmap(qrBinarizer);

                    try
                    {
                        qrCodeResult = qrReader.decodeMultiple(qrBinaryBitmap, qrReaderHints)?.FirstOrDefault();
                        qrCodeResultScale = 1.75F;
                    }
                    catch (ReaderException)
                    {
                        // QR Detection Failed
                        qrCodeResult = null;
                    }
                }

                if (qrCodeResult == null)
                {
                    // Try at 200%
                    using (var image = PdfiumDocument.Render(PageIndex, (int)(sizePoints.Width * 2), (int)(sizePoints.Height * 2), 72F, 72F, false))
                    {
                        qrImageSource = new BitmapLuminanceSource((Bitmap)image);

                        // Try Entire Image
                        qrBinarizer = new HybridBinarizer(qrImageSource);
                        qrBinaryBitmap = new BinaryBitmap(qrBinarizer);

                        try
                        {
                            qrCodeResult = qrReader.decodeMultiple(qrBinaryBitmap, qrReaderHints)?.FirstOrDefault();
                            qrCodeResultScale = 2F;
                        }
                        catch (ReaderException)
                        {
                            // QR Detection Failed
                            qrCodeResult = null;
                        }
                    }
                }
            }

            if (qrCodeResult != null)
            {
                // Detect Rotation
                var rotationAngle = Math.Atan2(
                    qrCodeResult.ResultPoints[2].Y - qrCodeResult.ResultPoints[1].Y,
                    qrCodeResult.ResultPoints[2].X - qrCodeResult.ResultPoints[1].X) * 180 / Math.PI;
                if (rotationAngle <= 45 || rotationAngle > 315)
                {
                    detectedRotation = RotateFlipType.RotateNoneFlipNone;
                }
                else if (rotationAngle <= 135)
                {
                    detectedRotation = RotateFlipType.Rotate270FlipNone;
                }
                else if (rotationAngle <= 225)
                {
                    detectedRotation = RotateFlipType.Rotate180FlipNone;
                }
                else
                {
                    detectedRotation = RotateFlipType.Rotate90FlipNone;
                }

                // Reset Thumbnail
                if (renderedThumbnail != null)
                {
                    renderedThumbnail.Dispose();
                    renderedThumbnail = null;
                }

                // Try binary encoding (from v2)
                if (qrCodeResult.ResultMetadata.ContainsKey(ResultMetadataType.BYTE_SEGMENTS))
                {
                    var byteSegments = (List<byte[]>)qrCodeResult.ResultMetadata[ResultMetadataType.BYTE_SEGMENTS];
                    var qrBytes = byteSegments[0];
                    if (DocumentUniqueIdentifier.IsDocumentUniqueIdentifier(qrBytes))
                    {
                        Identifier = DocumentUniqueIdentifier.Parse(Database, qrBytes);
                    }
                }
                // Fall back to v1
                if (Identifier == null)
                {
                    Identifier = DocumentUniqueIdentifier.Parse(Database, qrCodeResult.Text);
                }

                return true;
            }

            return false;
        }
Пример #22
0
      private Result decodeInternal(BinaryBitmap image)
      {
         if (readers != null)
         {
            var rpCallback = hints != null && hints.ContainsKey(DecodeHintType.NEED_RESULT_POINT_CALLBACK)
                                ? (ResultPointCallback) hints[DecodeHintType.NEED_RESULT_POINT_CALLBACK]
                                : null;

            for (var index = 0; index < readers.Count; index++)
            {
               var reader = readers[index];
               reader.reset();
               var result = reader.decode(image, hints);
               if (result != null)
               {
                  // found a barcode, pushing the successful reader up front
                  // I assume that the same type of barcode is read multiple times
                  // so the reordering of the readers list should speed up the next reading
                  // a little bit
                  readers.RemoveAt(index);
                  readers.Insert(0, reader);
                  return result;
               }
               if (rpCallback != null)
                  rpCallback(null);
            }
         }

         return null;
      }
Пример #23
0
 /// <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);
 }
Пример #24
0
 /// <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));
 }
Пример #25
0
		public void OnPreviewFrame (byte [] bytes, Android.Hardware.Camera camera)
		{
			if ((DateTime.Now - lastPreviewAnalysis).TotalMilliseconds < 150)
				return;
			
			try 
			{
				//Fix for image not rotating on devices
				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 cameraParameters = camera.GetParameters();

				//Changed to using a YUV Image to get the byte data instead of manually working with it!
				var img = new YuvImage(rotatedData, ImageFormatType.Nv21, cameraParameters.PreviewSize.Width, cameraParameters.PreviewSize.Height, null);	
				var dataRect = GetFramingRectInPreview();
			
				var luminance = new PlanarYUVLuminanceSource (img.GetYuvData(), width, height, dataRect.Left, dataRect.Top, dataRect.Width(), dataRect.Height(), false);
				//var luminance = new PlanarYUVLuminanceSource(img.GetYuvData(), cameraParameters.PreviewSize.Width, cameraParameters.PreviewSize.Height, 0, 0, cameraParameters.PreviewSize.Width, cameraParameters.PreviewSize.Height, false);
				var binarized = new BinaryBitmap (new ZXing.Common.HybridBinarizer(luminance));
				var result = reader.decodeWithState(binarized);

				lastPreviewAnalysis = DateTime.Now;

				if (result == null || string.IsNullOrEmpty (result.Text))
					return;

				Android.Util.Log.Debug("ZXing.Mobile", "Barcode Found: " + result.Text);

				ShutdownCamera();

				activity.OnScan (result);

			} catch (ReaderException) {
				Android.Util.Log.Debug("ZXing.Mobile", "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 ScanPreviewBuffer()
        {
            if (_photoCamera == null) return;
            if (!_initialized) return;

            try
            {
                _photoCamera.GetPreviewBufferY(_luminance.PreviewBufferY);
                var binarizer = new HybridBinarizer(_luminance);
                var binBitmap = new BinaryBitmap(binarizer);

                var result = _reader.decode(binBitmap);
                if (result != null)
                    OnDecodingCompleted(result);
            }
            catch (Exception)
            {
                // If decoding fails it will throw a ReaderException
                // and we're not interested in doing anything with it
            }
        }
Пример #27
0
      /// <summary>
      /// Tries to decode a barcode within an image which is given by a luminance source.
      /// That method gives a chance to prepare a luminance source completely before calling
      /// the time consuming decoding method. On the other hand there is a chance to create
      /// a luminance source which is independent from external resources (like Bitmap objects)
      /// and the decoding call can be made in a background thread.
      /// </summary>
      /// <param name="luminanceSource">The luminance source.</param>
      /// <returns></returns>
      private Result Decode(LuminanceSource luminanceSource)
      {
         var result = default(Result);
         var binarizer = CreateBinarizer(luminanceSource);
         var binaryBitmap = new BinaryBitmap(binarizer);
         var multiformatReader = Reader as MultiFormatReader;
         var rotationCount = 0;
         var rotationMaxCount = 1;

         if (AutoRotate)
         {
            Options.Hints[DecodeHintType.TRY_HARDER_WITHOUT_ROTATION] = true;
            rotationMaxCount = 4;
         }
         else
         {
            if (Options.Hints.ContainsKey(DecodeHintType.TRY_HARDER_WITHOUT_ROTATION))
               Options.Hints.Remove(DecodeHintType.TRY_HARDER_WITHOUT_ROTATION);
         }

         for (; rotationCount < rotationMaxCount; rotationCount++)
         {
            if (usePreviousState && multiformatReader != null)
            {
               result = multiformatReader.decodeWithState(binaryBitmap);
            }
            else
            {
               result = Reader.decode(binaryBitmap, Options.Hints);
               usePreviousState = true;
            }

            if (result == null)
            {
               if (TryInverted && luminanceSource.InversionSupported)
               {
                  binaryBitmap = new BinaryBitmap(CreateBinarizer(luminanceSource.invert()));
                  if (usePreviousState && multiformatReader != null)
                  {
                     result = multiformatReader.decodeWithState(binaryBitmap);
                  }
                  else
                  {
                     result = Reader.decode(binaryBitmap, Options.Hints);
                     usePreviousState = true;
                  }
               }
            }

            if (result != null ||
                !luminanceSource.RotateSupported ||
                !AutoRotate)
               break;

            binaryBitmap = new BinaryBitmap(CreateBinarizer(luminanceSource.rotateCounterClockwise()));
         }

         if (result != null)
         {
            if (result.ResultMetadata == null)
            {
               result.putMetadata(ResultMetadataType.ORIENTATION, rotationCount * 90);
            }
            else if (!result.ResultMetadata.ContainsKey(ResultMetadataType.ORIENTATION))
            {
               result.ResultMetadata[ResultMetadataType.ORIENTATION] = rotationCount * 90;
            }
            else
            {
               // perhaps the core decoder rotates the image already (can happen if TryHarder is specified)
               result.ResultMetadata[ResultMetadataType.ORIENTATION] = ((int)(result.ResultMetadata[ResultMetadataType.ORIENTATION]) + rotationCount * 90) % 360;
            }

            OnResultFound(result);
         }

         return result;
      }
Пример #28
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, IDictionary <DecodeHintType, object> hints)
 {
     Hints = hints;
     return(decodeInternal(image));
 }
        /// <summary>
        /// Function for just fetching the QR-Codes in the WebCamTexture-Image.
        /// It stores the Data in a QrCodeData-Object.
        /// It uses the "pixels" field as the image-source, since we can not
        /// access the Unity-API from another thread than the main-thread.
        /// </summary>
        private void DecodeQr()
        {
            while (_runThread)
            {
                // waiting.
                if (_pixels != null)
                {
                    // Create a BitMatrix from the Color32[] of the camear image, so that XZing can detect QR-codes.
                    LuminanceSource lum = new Color32LuminanceSource(_pixels, GlobalState.Instance.CamWidth, GlobalState.Instance.CamHeight);
                    HybridBinarizer bin = new HybridBinarizer(lum);
                    BinaryBitmap binBip = new BinaryBitmap(bin);
                    BitMatrix matrix = binBip.BlackMatrix;

                    Detector detector = new Detector(matrix);
                    DetectorResult result = detector.detect();
                    _qrCodeCollection.UpdateData(result);
                }
            }
        }
Пример #30
0
 /// <summary>
 ///     读取二维码信息
 /// </summary>
 /// <param name="strBarcodeImgPath">二维码的存放路径</param>
 /// <returns>二维码信息</returns>
 public static string ReadBarcode(string strBarcodeImgPath)
 {
     var img = Image.FromFile(strBarcodeImgPath);
     var bmap = new Bitmap(img);
     var ms = new MemoryStream();
     bmap.Save(ms, ImageFormat.Bmp);
     var bytes = ms.GetBuffer();
     LuminanceSource source = new RGBLuminanceSource(bytes, bmap.Width, bmap.Height);
     var bitmap = new BinaryBitmap(new HybridBinarizer(source));
     var result = new MultiFormatReader().decode(bitmap);
     return result.Text;
 }
Пример #31
0
        /// <summary>
        /// Tries to decode a barcode within an image which is given by a luminance source.
        /// That method gives a chance to prepare a luminance source completely before calling
        /// the time consuming decoding method. On the other hand there is a chance to create
        /// a luminance source which is independent from external resources (like Bitmap objects)
        /// and the decoding call can be made in a background thread.
        /// </summary>
        /// <param name="luminanceSource">The luminance source.</param>
        /// <returns></returns>
        public virtual Result Decode(LuminanceSource luminanceSource)
        {
            var result = default(Result);
            var binarizer = CreateBinarizer(luminanceSource);
            var binaryBitmap = new BinaryBitmap(binarizer);
            var multiformatReader = Reader as MultiFormatReader;
            var rotationCount = 0;
            var rotationMaxCount = 1;

            if (AutoRotate)
            {
                Options.Hints[DecodeHintType.TRY_HARDER_WITHOUT_ROTATION] = true;
                rotationMaxCount = 4;
            }
            else
            {
                if (Options.Hints.ContainsKey(DecodeHintType.TRY_HARDER_WITHOUT_ROTATION))
                    Options.Hints.Remove(DecodeHintType.TRY_HARDER_WITHOUT_ROTATION);
            }

            for (; rotationCount < rotationMaxCount; rotationCount++)
            {
                if (usePreviousState && multiformatReader != null)
                {
                    result = multiformatReader.decodeWithState(binaryBitmap);
                }
                else
                {
                    result = Reader.decode(binaryBitmap, Options.Hints);
                    usePreviousState = true;
                }

                if (result == null)
                {
                    if (TryInverted && luminanceSource.InversionSupported)
                    {
                        binaryBitmap = new BinaryBitmap(CreateBinarizer(luminanceSource.invert()));
                        if (usePreviousState && multiformatReader != null)
                        {
                            result = multiformatReader.decodeWithState(binaryBitmap);
                        }
                        else
                        {
                            result = Reader.decode(binaryBitmap, Options.Hints);
                            usePreviousState = true;
                        }
                    }
                }

                if (result != null ||
                    !luminanceSource.RotateSupported ||
                    !AutoRotate)
                    break;

                luminanceSource = luminanceSource.rotateCounterClockwise();
                binarizer = CreateBinarizer(luminanceSource);
                binaryBitmap = new BinaryBitmap(binarizer);
            }

            if (result != null)
            {
                if (result.ResultMetadata == null)
                {
                    result.putMetadata(ResultMetadataType.ORIENTATION, rotationCount * 90);
                }
                else if (!result.ResultMetadata.ContainsKey(ResultMetadataType.ORIENTATION))
                {
                    result.ResultMetadata[ResultMetadataType.ORIENTATION] = rotationCount * 90;
                }
                else
                {
                    // perhaps the core decoder rotates the image already (can happen if TryHarder is specified)
                    result.ResultMetadata[ResultMetadataType.ORIENTATION] = ((int)(result.ResultMetadata[ResultMetadataType.ORIENTATION]) + rotationCount * 90) % 360;
                }

                OnResultFound(result);
            }

            return result;
        }
Пример #32
0
        public BinaryBitmap GetImage(string file)
        {

            var fullName = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Images", file);

            var bmp = new System.Drawing.Bitmap(fullName);

            var bin = new ZXing.Common.HybridBinarizer(new RGBLuminanceSource(bmp, bmp.Width, bmp.Height));

            var i = new BinaryBitmap(bin);

            return i;
        }
Пример #33
0
		public void OnPreviewFrame (byte [] bytes, Android.Hardware.Camera camera)
		{
			if ((DateTime.Now - lastPreviewAnalysis).TotalMilliseconds < 250)
				return;

			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 PlanarYUVLuminanceSource (rotatedData, width, height, dataRect.Left, dataRect.Top, dataRect.Width(), dataRect.Height(), false);
				var binarized = new BinaryBitmap (new ZXing.Common.HybridBinarizer(luminance));
				var result = reader.decodeWithState(binarized);

				lastPreviewAnalysis = DateTime.Now;

				if (result == null || string.IsNullOrEmpty (result.Text))
					return;

				Android.Util.Log.Debug("ZXing.Mobile", "Barcode Found: " + result.Text);

				ShutdownCamera();

				activity.OnScan (result);

			} catch (ReaderException) {
				Android.Util.Log.Debug("ZXing.Mobile", "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 ScanQRCodeItem_Click(object sender, EventArgs e)
        {
            foreach (Screen screen in Screen.AllScreens)
            {
                using (Bitmap fullImage = new Bitmap(screen.Bounds.Width,
                                                screen.Bounds.Height))
                {
                    using (Graphics g = Graphics.FromImage(fullImage))
                    {
                        g.CopyFromScreen(screen.Bounds.X,
                                         screen.Bounds.Y,
                                         0, 0,
                                         fullImage.Size,
                                         CopyPixelOperation.SourceCopy);
                    }
                    int maxTry = 10;
                    for (int i = 0; i < maxTry; i++)
                    {
                        int marginLeft = (int)((double)fullImage.Width * i / 2.5 / maxTry);
                        int marginTop = (int)((double)fullImage.Height * i / 2.5 / maxTry);
                        Rectangle cropRect = new Rectangle(marginLeft, marginTop, fullImage.Width - marginLeft * 2, fullImage.Height - marginTop * 2);
                        Bitmap target = new Bitmap(screen.Bounds.Width, screen.Bounds.Height);

                        double imageScale = (double)screen.Bounds.Width / (double)cropRect.Width;
                        using (Graphics g = Graphics.FromImage(target))
                        {
                            g.DrawImage(fullImage, new Rectangle(0, 0, target.Width, target.Height),
                                            cropRect,
                                            GraphicsUnit.Pixel);
                        }
                        var source = new BitmapLuminanceSource(target);
                        var bitmap = new BinaryBitmap(new HybridBinarizer(source));
                        QRCodeReader reader = new QRCodeReader();
                        var result = reader.decode(bitmap);
                        if (result != null)
                        {
                            var success = controller.AddServerBySSURL(result.Text);
                            QRCodeSplashForm splash = new QRCodeSplashForm();
                            if (success)
                            {
                                splash.FormClosed += splash_FormClosed;
                            }
                            else if (result.Text.StartsWith("http://") || result.Text.StartsWith("https://"))
                            {
                                _urlToOpen = result.Text;
                                splash.FormClosed += openURLFromQRCode;
                            }
                            else
                            {
                                MessageBox.Show(I18N.GetString("Failed to decode QRCode"));
                                return;
                            }
                            double minX = Int32.MaxValue, minY = Int32.MaxValue, maxX = 0, maxY = 0;
                            foreach (ResultPoint point in result.ResultPoints)
                            {
                                minX = Math.Min(minX, point.X);
                                minY = Math.Min(minY, point.Y);
                                maxX = Math.Max(maxX, point.X);
                                maxY = Math.Max(maxY, point.Y);
                            }
                            minX /= imageScale;
                            minY /= imageScale;
                            maxX /= imageScale;
                            maxY /= imageScale;
                            // make it 20% larger
                            double margin = (maxX - minX) * 0.20f;
                            minX += -margin + marginLeft;
                            maxX += margin + marginLeft;
                            minY += -margin + marginTop;
                            maxY += margin + marginTop;
                            splash.Location = new Point(screen.Bounds.X, screen.Bounds.Y);
                            // we need a panel because a window has a minimal size
                            // TODO: test on high DPI
                            splash.TargetRect = new Rectangle((int)minX + screen.Bounds.X, (int)minY + screen.Bounds.Y, (int)maxX - (int)minX, (int)maxY - (int)minY);
                            splash.Size = new Size(fullImage.Width, fullImage.Height);
                            splash.Show();
                            return;
                        }
                    }
                }
            }
            MessageBox.Show(I18N.GetString("No QRCode found. Try to zoom in or move it to the center of the screen."));
        }
Пример #35
-1
        private void btnSave_Click(object sender, EventArgs e)
        {
            var reader = new MultiFormatReader();
            var img = (Bitmap)Bitmap.FromFile(pictureBox1.ImageLocation);

            BitmapLuminanceSource ls = new BitmapLuminanceSource(img);
            var binarizer = new HybridBinarizer(ls);
            BinaryBitmap binaryBitmap = new BinaryBitmap(binarizer);
            var result = reader.decode(binaryBitmap);
            richTextBox1.Text = result.Text.Trim();
        }
Пример #36
-1
        public static String MultiDecode(Bitmap bitmap)
        {
            // convert
            if (bitmap == null)
            {
                return null;
            }
            LuminanceSource luminanceSource = new BitmapLuminanceSource(bitmap);
            BinaryBitmap binaryBitmap = new BinaryBitmap(new HybridBinarizer(luminanceSource));

            // decode
            ZXing.Result result = (new MultiFormatReader()).decode(binaryBitmap);
            if (result == null)
            {
                return null;
            }

            String text = result.Text;
            return text;
        }
Пример #37
-1
        public void Decode()
        {
            Bitmap bitmap = new Bitmap(@"text.png");
            try
            {
                MemoryStream memoryStream = new MemoryStream();
                bitmap.Save(memoryStream, ImageFormat.Bmp);

                byte[] byteArray = memoryStream.GetBuffer();

                ZXing.LuminanceSource source = new RGBLuminanceSource(byteArray, bitmap.Width, bitmap.Height);
                var binarizer = new HybridBinarizer(source);
                var binBitmap = new BinaryBitmap(binarizer);
                QRCodeReader qrCodeReader = new QRCodeReader();

                Result str = qrCodeReader.decode(binBitmap);
                Assert.AreEqual(str, "Hello World!");

            }
            catch { }
        }
Пример #38
-1
      /// <summary>
      /// Tries to decode barcodes within an image which is given by a luminance source.
      /// That method gives a chance to prepare a luminance source completely before calling
      /// the time consuming decoding method. On the other hand there is a chance to create
      /// a luminance source which is independent from external resources (like Bitmap objects)
      /// and the decoding call can be made in a background thread.
      /// </summary>
      /// <param name="luminanceSource">The luminance source.</param>
      /// <returns></returns>
      private Result[] DecodeMultiple(LuminanceSource luminanceSource)
      {
         var results = default(Result[]);
         var binarizer = CreateBinarizer(luminanceSource);
         var binaryBitmap = new BinaryBitmap(binarizer);
         var rotationCount = 0;
         var rotationMaxCount = 1;
         MultipleBarcodeReader multiReader = null;

         if (AutoRotate)
         {
            Options.Hints[DecodeHintType.TRY_HARDER_WITHOUT_ROTATION] = true;
            rotationMaxCount = 4;
         }

         var formats = Options.PossibleFormats;
         if (formats != null &&
             formats.Length == 1 &&
             formats[0] == BarcodeFormat.QR_CODE)
         {
            multiReader = new QRCodeMultiReader();
         }
         else
         {
            multiReader = new GenericMultipleBarcodeReader(Reader);
         }

         for (; rotationCount < rotationMaxCount; rotationCount++)
         {
            results = multiReader.decodeMultiple(binaryBitmap, Options.Hints);

            if (results == null)
            {
               if (TryInverted && luminanceSource.InversionSupported)
               {
                  binaryBitmap = new BinaryBitmap(CreateBinarizer(luminanceSource.invert()));
                  results = multiReader.decodeMultiple(binaryBitmap, Options.Hints);
               }
            }

            if (results != null ||
                !luminanceSource.RotateSupported ||
                !AutoRotate)
               break;

            binaryBitmap = new BinaryBitmap(CreateBinarizer(luminanceSource.rotateCounterClockwise()));
         }

         if (results != null)
         {
            foreach (var result in results)
            {
               if (result.ResultMetadata == null)
               {
                  result.putMetadata(ResultMetadataType.ORIENTATION, rotationCount * 90);
               }
               else if (!result.ResultMetadata.ContainsKey(ResultMetadataType.ORIENTATION))
               {
                  result.ResultMetadata[ResultMetadataType.ORIENTATION] = rotationCount * 90;
               }
               else
               {
                  // perhaps the core decoder rotates the image already (can happen if TryHarder is specified)
                  result.ResultMetadata[ResultMetadataType.ORIENTATION] =
                     ((int)(result.ResultMetadata[ResultMetadataType.ORIENTATION]) + rotationCount * 90) % 360;
               }
            }

            OnResultsFound(results);
         }

         return results;
      }
Пример #39
-1
		public BinaryBitmap GetImage(string file)
		{
			var fullName = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Images", file);

			//Try to find it from the source code folder
			if (!System.IO.File.Exists(fullName))
				fullName = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "..", "..", "Images", file);

			var bmp = new System.Drawing.Bitmap(fullName);

			var bin = new ZXing.Common.HybridBinarizer(new RGBLuminanceSource(bmp, bmp.Width, bmp.Height));

			var i = new BinaryBitmap(bin);

			return i;
		}