Exemple #1
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;
         }
      }
Exemple #2
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);
        }
Exemple #3
0
        public string CodeDecoder(string path)
        {
            Bitmap       bitMap;
            MemoryStream ms;
            WebClient    Client = new WebClient();
            string       url    = @"https://api.telegram.org/file/bot649665785:AAF3lm9sagdFTtiF4t5p0uBhwr1PhabLSCs/";

            url = url + path;
            try
            {
                System.Net.WebRequest request =
                    System.Net.WebRequest.Create(
                        url);
                System.Net.WebResponse response       = request.GetResponse();
                System.IO.Stream       responseStream =
                    response.GetResponseStream();
                bitMap = new Bitmap(responseStream);

                ms = new MemoryStream();                                                             //实例化内存流

                bitMap.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);                             //把位图信息保存到内存流里面

                byte[] bytes = ms.GetBuffer();                                                       //把颜色信息转化为byte数据

                LuminanceSource source = new RGBLuminanceSource(bytes, bitMap.Width, bitMap.Height); //得到位图的像素数值内容

                BinaryBitmap bb = new BinaryBitmap(new ZXing.Common.HybridBinarizer(source));        //处理像素值内容信息

                MultiFormatReader mutireader = new ZXing.MultiFormatReader();                        //实例化MultiFormatReader

                Result str = mutireader.decode(bb);                                                  //通过mutireader.decode()得到解析后的结果

                ms.Close();                                                                          //关闭内存流

                if (str == null)
                {
                    return(null);
                }
                else
                {
                    return(str.Text);//返回解析结果
                }
            }
            catch (System.Net.WebException e)
            {
                return(e.ToString());
            }
        }
		public MultiFormatReader BuildMultiFormatReader()
		{
			var reader = new MultiFormatReader();

			var hints = new Dictionary<DecodeHintType, object>();

			if (this.TryHarder.HasValue && this.TryHarder.Value)
				hints.Add(DecodeHintType.TRY_HARDER, this.TryHarder.Value);
			if (this.PureBarcode.HasValue && this.PureBarcode.Value)
				hints.Add(DecodeHintType.PURE_BARCODE, this.PureBarcode.Value);

			if (this.PossibleFormats != null && this.PossibleFormats.Count > 0)
			hints.Add(DecodeHintType.POSSIBLE_FORMATS, this.PossibleFormats);

			reader.Hints = hints;

			return reader;
		}
Exemple #5
0
        //private string save_path = @"d:/";

        public string CodeDecoder(string path)
        {
            http = http + path;
            try
            {
                System.Net.WebRequest request =
                    System.Net.WebRequest.Create(
                        http);
                System.Net.WebResponse response       = request.GetResponse();
                System.IO.Stream       responseStream =
                    response.GetResponseStream();
                bitMap = new System.Drawing.Bitmap(responseStream);
            }
            catch (System.Net.WebException)
            {
                //MessageBox.Show("There was an error opening the image file."
                // + "Check the URL");
            }



            //bitMap = new Bitmap(http);
            MemoryStream ms = new MemoryStream();                                                //实例化内存流

            bitMap.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);                             //把位图信息保存到内存流里面
            byte[] bytes = ms.GetBuffer();                                                       //把颜色信息转化为byte数据

            LuminanceSource source = new RGBLuminanceSource(bytes, bitMap.Width, bitMap.Height); //得到位图的像素数值内容
            BinaryBitmap    bb     = new BinaryBitmap(new ZXing.Common.HybridBinarizer(source)); //处理像素值内容信息

            MultiFormatReader mutireader = new ZXing.MultiFormatReader();                        //实例化MultiFormatReader
            Result            str        = mutireader.decode(bb);                                //通过mutireader.decode()得到解析后的结果

            if (str == null)
            {
                return(null);
            }
            return(str.Text); //返回解析结果

            ms.Close();       //关闭内存流
        }
        static void ZXing_DBR_Test(string directory)
        {
            Dynamsoft.Barcode.BarcodeReader reader = new Dynamsoft.Barcode.BarcodeReader();
            reader.LicenseKeys = "t0068NQAAAJx5X8TaH/zQIy0Mm3HHIypzFTL+DQTIQah1eCiNcZygsi6sFa0cZiJVv+rRTyU29TpFsLA6hWiz+GAlQlGrRRg=";

            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);
                Console.BackgroundColor = ConsoleColor.Blue;
                ZXing_Test_Single(file, multiBarcodeReader);
                Console.ResetColor();

                Console.BackgroundColor = ConsoleColor.Red;
                Dynamsoft_Barcode_Reader_Test_Single(file, reader);
                Console.ResetColor();
                Console.WriteLine("\n");
            }
        }
        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 MultiFormatReader GetReader(BarcodeFormat format, KeyValuePair<DecodeHintType, object>[] additionalHints)
        {

            var reader = new MultiFormatReader();

            var hints = new System.Collections.Generic.Dictionary<DecodeHintType, object>();

                   


            hints.Add(DecodeHintType.POSSIBLE_FORMATS, new List<BarcodeFormat>() { format } );


            if (additionalHints != null)
                foreach (var ah in additionalHints)
                    hints.Add(ah.Key, ah.Value);


            reader.Hints = hints;
            
            return reader;
        }
		private void Initialize()
		{
            ScanOnAutoFocus = true; // scanOnAutoFocus;

			// Gets the Dispatcher for the current application so we can invoke the UI-Thread to get
			// preview-image and fire our timer events
			uiDispatcher = Application.Current.RootVisual.Dispatcher;

			InitializeCamera();

			
            _reader = this.Options.BuildMultiFormatReader();
		}
		public void StopWorker()
        {
			wasStopped = true;

            // starting timer
            if (WorkerTimer != null)
            {
                WorkerTimer.Invalidate();
				try { WorkerTimer.Dispose(); } catch { }
                WorkerTimer = null;
				try { NSRunLoop.Current.Dispose(); } catch { }
            }
			
			//Just in case
			_multiFormatReader = null;
			hints = null;
        }
		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.");

        }
			public ZxingScanner (ZxingViewController parent)
			{
				this.parent = parent;

				this.reader = this.parent.Options.BuildMultiFormatReader();
			}
Exemple #13
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;
 }
	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;
		}
	}
Exemple #15
0
		//BarcodeReader reader;

		public ZxingSurfaceView (ZxingActivity activity, MobileBarcodeScanningOptions options)
			: base (activity)
		{
			this.activity = activity;

			screenResolution = new Size(this.activity.WindowManager.DefaultDisplay.Width, this.activity.WindowManager.DefaultDisplay.Height);

			this.options = options;
			lastPreviewAnalysis = DateTime.Now.AddMilliseconds(options.InitialDelayBeforeAnalyzingFrames);

			this.reader = this.options.BuildMultiFormatReader();

			this.surface_holder = Holder;
			this.surface_holder.AddCallback (this);
			this.surface_holder.SetType (SurfaceType.PushBuffers);
			
			this.tokenSource = new System.Threading.CancellationTokenSource();
		}
        private void Initialize(List<BarcodeFormat> formats, bool scanOnAutoFocus)
        {
            ScanOnAutoFocus = scanOnAutoFocus;

            // Gets the Dispatcher for the current application so we can invoke the UI-Thread to get
            // preview-image and fire our timer events
            uiDispatcher = Application.Current.RootVisual.Dispatcher;

            InitializeCamera();

            _reader = new MultiFormatReader();

            // At first initialization we use all formats
            //            if (formats == null) formats = BarcodeFormat.AllFormats;

            var hints = new Dictionary<DecodeHintType, Object> { { DecodeHintType.POSSIBLE_FORMATS, formats } };

            _reader.Hints = hints;
        }
Exemple #17
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;
      }
		//BarcodeReader reader;

		public ZxingSurfaceView (ZxingActivity activity, MobileBarcodeScanningOptions options)
			: base (activity)
		{
			this.activity = activity;

			screenResolution = new Size(this.activity.WindowManager.DefaultDisplay.Width, this.activity.WindowManager.DefaultDisplay.Height);

			this.options = options;


			this.reader = this.options.BuildMultiFormatReader();

			this.surface_holder = Holder;
			this.surface_holder.AddCallback (this);
			this.surface_holder.SetType (SurfaceType.PushBuffers);



			this.tokenSource = new System.Threading.CancellationTokenSource();
		}
        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" });
            };
        }
Exemple #20
-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();
        }