/// <summary> /// Verify and create the authenticator if needed /// </summary> /// <returns>true is successful</returns> private bool verifyAuthenticator(string privatekey) { if (string.IsNullOrEmpty(privatekey) == true) { return(false); } this.Authenticator.Name = nameField.Text; string authtype = "totp"; // if this is a URL, pull it down Uri uri; Match match; if (Regex.IsMatch(privatekey, "https?://.*") == true && Uri.TryCreate(privatekey, UriKind.Absolute, out uri) == true) { try { var request = (HttpWebRequest)WebRequest.Create(uri); request.AllowAutoRedirect = true; request.Timeout = 20000; request.UserAgent = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; Trident/4.0)"; using (var response = (HttpWebResponse)request.GetResponse()) { if (response.StatusCode == HttpStatusCode.OK && response.ContentType.StartsWith("image/", StringComparison.OrdinalIgnoreCase) == true) { using (Bitmap bitmap = (Bitmap)Bitmap.FromStream(response.GetResponseStream())) { IBarcodeReader reader = new BarcodeReader(); var result = reader.Decode(bitmap); if (result != null) { privatekey = HttpUtility.UrlDecode(result.Text); } } } } } catch (Exception ex) { WinAuthForm.ErrorDialog(this.Owner, "Cannot load QR code image from " + privatekey, ex); return(false); } } else if ((match = Regex.Match(privatekey, @"data:image/([^;]+);base64,(.*)", RegexOptions.IgnoreCase)).Success == true) { byte[] imagedata = Convert.FromBase64String(match.Groups[2].Value); using (MemoryStream ms = new MemoryStream(imagedata)) { using (Bitmap bitmap = (Bitmap)Bitmap.FromStream(ms)) { IBarcodeReader reader = new BarcodeReader(); var result = reader.Decode(bitmap); if (result != null) { privatekey = HttpUtility.UrlDecode(result.Text); } } } } else if (IsValidFile(privatekey) == true) { // assume this is the image file using (Bitmap bitmap = (Bitmap)Bitmap.FromFile(privatekey)) { IBarcodeReader reader = new BarcodeReader(); var result = reader.Decode(bitmap); if (result != null) { privatekey = result.Text; } } } // check for otpauth://, e.g. "otpauth://totp/[email protected]?secret=IHZJDKAEEC774BMUK3GX6SA" match = Regex.Match(privatekey, @"otpauth://([^/]+)/([^?]+)\?(.*)", RegexOptions.IgnoreCase); if (match.Success == true) { authtype = match.Groups[1].Value; // @todo we only handle totp (not hotp) if (string.Compare(authtype, "totp", true) != 0) { WinAuthForm.ErrorDialog(this.Owner, "Only time-based (TOTP) authenticators are supported when adding a Google Authenticator. Use the general \"Add Authenticator\" for counter-based (HOTP) authenticators."); return(false); } string label = match.Groups[2].Value; if (string.IsNullOrEmpty(label) == false) { this.Authenticator.Name = this.nameField.Text = label; } NameValueCollection qs = WinAuthHelper.ParseQueryString(match.Groups[3].Value); privatekey = qs["secret"] ?? privatekey; } // just get the hex chars privatekey = Regex.Replace(privatekey, @"[^0-9a-z]", "", RegexOptions.IgnoreCase); if (privatekey.Length == 0) { WinAuthForm.ErrorDialog(this.Owner, "The secret code is not valid"); return(false); } try { GoogleAuthenticator auth = new GoogleAuthenticator(); auth.Enroll(privatekey); this.Authenticator.AuthenticatorData = auth; codeProgress.Visible = true; string key = Base32.getInstance().Encode(this.Authenticator.AuthenticatorData.SecretKey); this.secretCodeField.Text = Regex.Replace(key, ".{3}", "$0 ").Trim(); this.codeField.Text = auth.CurrentCode; if (auth.ServerTimeDiff == 0L && SyncErrorWarned == false) { SyncErrorWarned = true; MessageBox.Show(this, string.Format(strings.AuthenticatorSyncError, "Google"), WinAuthMain.APPLICATION_TITLE, MessageBoxButtons.OK, MessageBoxIcon.Warning); } } catch (Exception irre) { WinAuthForm.ErrorDialog(this.Owner, "Unable to create the authenticator. The secret code is probably invalid.", irre); return(false); } return(true); }
public void SetImage(System.Drawing.Bitmap image) { var scanner = new BarcodeReader() { TryInverted = true, AutoRotate = true, Options = new ZXing.Common.DecodingOptions() { TryHarder = true, CharacterSet = "ISO-8859-1", PossibleFormats = new List <BarcodeFormat>() { BarcodeFormat.QR_CODE }, } }; var result = scanner.Decode(image); if (result != null) { var resultBytes = new byte[result.RawBytes.Length - 2]; for (int i = 5; i < result.RawBytes.Length * 2; i++) { int byteIndex = (i - 5) / 2; int rawByteIndex = i / 2; byte value = 0; if (i % 2 == 0) { value = (byte)((result.RawBytes[rawByteIndex] & 0xF0) >> 4); } else { value = (byte)(result.RawBytes[rawByteIndex] & 0x0F); } if ((i - 5) % 2 == 0) { resultBytes[byteIndex] += (byte)(value << 4); } else { resultBytes[byteIndex] += value; } } var bytes = resultBytes; if (bytes[0x69] == 0x09) { IsQRCode = true; } if (IsQRCode) { SetBytes(bytes); } else { this.Image = image; } } else { this.Image = image; } }
private void _initiateScanButton_Click(object sender, EventArgs e) { _barcodeReader.Aim(true); _barcodeReader.Light(true); _barcodeReader.Decode(true); }
void AnalyzeBitmap(Bitmap bitmap, TimeSpan time) { Result result = null; try { result = reader.Decode( bitmap.Buffers[0].Buffer.ToArray(), (int)bitmap.Buffers[0].Pitch, (int)bitmap.Dimensions.Height, BitmapFormat.Gray8 ); } catch { mDialog("Fehler beim Einlesen des QR-Codes", 1); } if (result != null) { var ignore = Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { DispatcherTimerOff(); removeEffects(); // show frame, progress ring and text enableSearchFrame(); // QR-Code hat nun einen json string // host + andere (uid) DTO.QRCodeDTO qrcDTO; try { qrcDTO = JsonConvert.DeserializeObject <DTO.QRCodeDTO>(result.Text); } catch (Exception e) { qrcDTO = null; } if (qrcDTO == null) { disableSearchFrame(); mDialog("Falscher QR-Code!" + Environment.NewLine + "Weiter scannen?", 0); } else { // check http url if (Uri.IsWellFormedUriString(qrcDTO.host, UriKind.RelativeOrAbsolute)) { getQuestions(qrcDTO); } else { disableSearchFrame(); mDialog("Fehler: Keine gültige URL gefunden!", 1); } } }); } }
void Update() { #if UNITY_EDITOR if (framerate++ % 15 == 0) { #elif UNITY_IOS || UNITY_ANDROID if (framerate++ % 15 == 0) { #else if (framerate++ % 20 == 0) { #endif if (e_DeviceController.isPlaying && !decoding) { W = e_DeviceController.Width(); // get the image width H = e_DeviceController.Height(); // get the image height if (W < 100 || H < 100) { return; } if (!isInit && W > 100 && H > 100) { blockWidth = Math.Min(W, H); isInit = true; } if (targetColorARR == null) { targetColorARR = new Color32[blockWidth * blockWidth]; } int posx = ((W - blockWidth) >> 1); // int posy = ((H - blockWidth) >> 1); orginalc = e_DeviceController.GetPixels(posx, posy, blockWidth, blockWidth); // get the webcam image colors //convert the color(float) to color32 (byte) for (int i = 0; i != blockWidth; i++) { for (int j = 0; j != blockWidth; j++) { targetColorARR[i + j * blockWidth].r = (byte)(orginalc[i + j * blockWidth].r * 255); targetColorARR[i + j * blockWidth].g = (byte)(orginalc[i + j * blockWidth].g * 255); targetColorARR[i + j * blockWidth].b = (byte)(orginalc[i + j * blockWidth].b * 255); targetColorARR[i + j * blockWidth].a = 255; } } #if !UNITY_WEBGL // scan the qrcode Loom.RunAsync(() => { try { Result data; data = barReader.Decode(targetColorARR, blockWidth, blockWidth); //start decode if (data != null) // if get the result success { decoding = true; // set the variable is true dataText = data.Text; // use the variable to save the code result } } catch (Exception e) { // Debug.LogError("Decode Error: " + e.Data.ToString()); decoding = false; } }); #else Result data; data = barReader.Decode(targetColorARR, blockWidth, blockWidth); //start decode if (data != null) // if get the result success { decoding = true; // set the variable is true dataText = data.Text; // use the variable to save the code result } #endif } if (decoding) { // if the status variable is change if (tempDecodeing != decoding) { onQRScanFinished(dataText); //triger the scan finished event; } tempDecodeing = decoding; } } }
public string GetData() { var upc = ""; var another = " "; // create a barcode reader instance //another = System.Web.Hosting.HostingEnvironment.ApplicationPhysicalPath; //another += "images\\barcode.jpg"; // jpg part will be changed another = "http://vhost0221.dc1.on.ca.compute.ihost.com/aspnet_client/WcfService2/WcfService2/images/barcode.jpg"; var localPath = new Uri(another).AbsolutePath; //var barcodeImageFile = another; var barcodeImageFile = localPath; //var bitmap1 = (Bitmap)Bitmap.FromFile(barcodeImageFile); IBarcodeReader barcodeReader; barcodeReader = new BarcodeReader { AutoRotate = true, Options = new DecodingOptions { TryHarder = true } }; try { //BarcodeReader reader = new BarcodeReader(); //another = "http://vhost0221.dc1.on.ca.compute.ihost.com/aspnet_client/WcfService2/WcfService2/images/barcode.jpg"; //using (var bitmap = (Bitmap)Bitmap.FromFile(barcodeImageFile)) using (var bitmap = (Bitmap)Bitmap.FromFile(barcodeImageFile)) { //another += "dsdsdsd "; try { var result = barcodeReader.Decode(bitmap); upc = result.ToString(); // THIS IS THE UPC NUMBER :) //upc += result.ToString(); //another += "kkkkkk"; //return result.ToString(); } catch (Exception innerExc) { upc += "first"; Console.WriteLine("Exception: {0}", innerExc.Message); } } } catch (Exception exc) { upc += "second "; upc += barcodeImageFile; another += " exccc " + exc.Message; Console.WriteLine("Exception: {0}", exc.Message); } // Result result = reader.Decode((Bitmap)Bitmap.FromFile("http://vhost0221.dc1.on.ca.compute.ihost.com/aspnet_client/WcfService2/WcfService2/barcode.jpg")); // load a bitmap //var barcodeBitmap = (Bitmap)Bitmap.FromFile("http://vhost0221.dc1.on.ca.compute.ihost.com/aspnet_client/WcfService2/WcfService2/barcode.jpg"); // detect and decode the barcode inside the bitmap //return upc+" "+another; //return upc + another; return(upc); }
private void Decode(IEnumerable <Bitmap> bitmaps, bool tryMultipleBarcodes, IList <BarcodeFormat> possibleFormats) { resultPoints.Clear(); lastResults.Clear(); txtContent.Text = String.Empty; var timerStart = DateTime.Now.Ticks; IList <Result> results = null; var previousFormats = barcodeReader.Options.PossibleFormats; if (possibleFormats != null) { barcodeReader.Options.PossibleFormats = possibleFormats; } foreach (var bitmap in bitmaps) { if (tryMultipleBarcodes) { results = barcodeReader.DecodeMultiple(bitmap); } else { var result = barcodeReader.Decode(bitmap); if (result != null) { if (results == null) { results = new List <Result>(); } results.Add(result); } } } var timerStop = DateTime.Now.Ticks; barcodeReader.Options.PossibleFormats = previousFormats; if (results == null) { txtContent.Text = "No barcode recognized"; } labDuration.Text = new TimeSpan(timerStop - timerStart).ToString(); if (results != null) { foreach (var result in results) { if (result.ResultPoints.Length > 0) { var offsetX = picBarcode.SizeMode == PictureBoxSizeMode.CenterImage ? (picBarcode.Width - picBarcode.Image.Width) / 2 : 0; var offsetY = picBarcode.SizeMode == PictureBoxSizeMode.CenterImage ? (picBarcode.Height - picBarcode.Image.Height) / 2 : 0; var rect = new Rectangle((int)result.ResultPoints[0].X + offsetX, (int)result.ResultPoints[0].Y + offsetY, 1, 1); foreach (var point in result.ResultPoints) { if (point.X + offsetX < rect.Left) { rect = new Rectangle((int)point.X + offsetX, rect.Y, rect.Width + rect.X - (int)point.X - offsetX, rect.Height); } if (point.X + offsetX > rect.Right) { rect = new Rectangle(rect.X, rect.Y, rect.Width + (int)point.X - (rect.X - offsetX), rect.Height); } if (point.Y + offsetY < rect.Top) { rect = new Rectangle(rect.X, (int)point.Y + offsetY, rect.Width, rect.Height + rect.Y - (int)point.Y - offsetY); } if (point.Y + offsetY > rect.Bottom) { rect = new Rectangle(rect.X, rect.Y, rect.Width, rect.Height + (int)point.Y - (rect.Y - offsetY)); } } using (var g = picBarcode.CreateGraphics()) { g.DrawRectangle(Pens.Green, rect); } } } } }
static void Main(string[] args) { // create a barcode reader instance var barcodeReader = new BarcodeReader { AutoRotate = true }; // create an in memory bitmap //var barcodeBitmap = (Bitmap)Bitmap.FromFile(@"C:\temp\authdoc079790-1.tif"); var pages = GetAllPages(@"C:\temp\authdoc079790-1.tif"); foreach (var page in pages) { Bitmap bmp = (Bitmap)page; var barcodeResult = barcodeReader.Decode(bmp); } // decode the barcode from the in memory bitmap //var barcodeResult = barcodeReader.Decode(barcodeBitmap); // output results to console //Console.WriteLine($"Decoded barcode text: {barcodeResult?.Text}"); //Console.WriteLine($"Barcode format: {barcodeResult?.BarcodeFormat}"); //var barcodeReader = new BarcodeReader(); ////IBarcodeReader reader = new BarcodeReader(); //// load a bitmap //var barcodeBitmap = (Bitmap)Bitmap.FromFile(@"C:\temp\test.bmp"); //// detect and decode the barcode inside the bitmap //var result = barcodeReader.Decode(barcodeBitmap); //// do something with the result //if (result != null) //{ // Console.WriteLine(result.BarcodeFormat.ToString()); // Console.WriteLine(result.Text); //} //string path = @"c:\temp\test.png"; //Bitmap originalImage = (Bitmap)Bitmap.FromFile(path); //ImageConverter imCo = new ImageConverter(); //byte[] bbt = (byte[])imCo.ConvertTo(originalImage, typeof(byte[])); //IDictionary<DecodeHintType, object> hintMap = new Dictionary<DecodeHintType, object>(); //hintMap.Add(DecodeHintType.TRY_HARDER, true); //LuminanceSource source = new RGBLuminanceSource(bbt, originalImage.Width, originalImage.Height); //BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source)); //// decode the barcode //QRCodeReader reader = new QRCodeReader(); //BarcodeReader rr = new BarcodeReader(); //rr.Options.PossibleFormats = new List<BarcodeFormat> { BarcodeFormat.QR_CODE }; //Result result = null; //try //{ // Result[] results = rr.DecodeMultiple(source); // result = reader.decode(bitmap, hintMap); //} //catch (ReaderException e) //{ //} }
private void ReadBarcodeZXing(Bitmap cropped) { IList <BarcodeFormat> possibleFormats = new List <BarcodeFormat>(); switch ((BarcodeTypeComboBox.SelectedValue as ComboBoxItem)?.Content as string) { case "QR | ITF": possibleFormats.Add(BarcodeFormat.QR_CODE); possibleFormats.Add(BarcodeFormat.ITF); break; case "QR": possibleFormats.Add(BarcodeFormat.QR_CODE); break; case "ITF": possibleFormats.Add(BarcodeFormat.ITF); break; case "1D": possibleFormats.Add(BarcodeFormat.All_1D); break; case "DataMatrix": possibleFormats.Add(BarcodeFormat.DATA_MATRIX); break; case "2D": possibleFormats.Add(BarcodeFormat.DATA_MATRIX); possibleFormats.Add(BarcodeFormat.QR_CODE); possibleFormats.Add(BarcodeFormat.PDF_417); possibleFormats.Add(BarcodeFormat.AZTEC); possibleFormats.Add(BarcodeFormat.CODE_128); break; case "Alle": possibleFormats.Add(BarcodeFormat.All_1D); possibleFormats.Add(BarcodeFormat.DATA_MATRIX); possibleFormats.Add(BarcodeFormat.QR_CODE); possibleFormats.Add(BarcodeFormat.PDF_417); possibleFormats.Add(BarcodeFormat.AZTEC); possibleFormats.Add(BarcodeFormat.CODE_128); break; } IBarcodeReader reader = new BarcodeReader() { AutoRotate = true, Options = new DecodingOptions() { TryHarder = true, PossibleFormats = possibleFormats } }; // load a bitmap // detect and decode the barcode inside the bitmap var result = reader.Decode(cropped); // do something with the result if (result != null) { LabelBarcodeContent.Text = result.Text; LabelBarcodeType.Text = result.BarcodeFormat.ToString(); //SystemSounds.Hand.Play(); Console.Beep(3100, 80); } }
private void timer1_Tick(object sender, EventArgs e) { DT_Now = DateTime.Now; if (VideoViewer.GetCurrentVideoFrame() != null) { BarcodeReader Reader = new BarcodeReader(); Bitmap img = new Bitmap(VideoViewer.GetCurrentVideoFrame()); //----------------加入CV--------------------- //Image<Gray, byte> I = new Image<Gray, byte>(img); //Image<Bgr, byte> DrawI = I.Convert<Bgr, byte>(); //Image<Gray, byte> CannyImage = I.Clone(); //灰階處理 //CvInvoke.GaussianBlur(I, CannyImage, new Size(5, 5), 0); //CvInvoke.Canny(I, CannyImage, 100, 200); //MyCV.BoundingBox(CannyImage, DrawI); //pictureBox1.Image = DrawI.Bitmap; //pictureBox2.Image = CannyImage.Bitmap; //Result result = Reader.Decode(DrawI.Bitmap); //----------------CV end---------------------- Result result = Reader.Decode(img); //原本 img.Dispose(); //釋放資源 if (result != null) { Scan_result_richTextBox.SelectionColor = Color.Green; Scan_result_richTextBox.AppendText("[" + DT_Now + "] 掃描條碼顯示: " + result + Environment.NewLine); //Scan_result.Items.Add("DBconnection = " + connectionString); //資料庫(自動Dispose寫法) String check_psd = "SELECT * FROM staff_info WHERE Encode_ID = '" + result + "'"; using (OleDbCommand cmd = new OleDbCommand()) { DataSet ds = new DataSet(); Table_Row TBR = new Table_Row(); List <Table_Row> table_row = new List <Table_Row>(); //OleDbDataReader dr; cmd.Connection = Access_DataBase.DB_Conn_Open(connectionString_StaffDB); cmd.CommandText = check_psd; //dr = cmd.ExecuteReader(); OleDbDataAdapter adapter = new OleDbDataAdapter(cmd); try { adapter.Fill(ds, "Encode_ID"); adapter.Fill(ds, "Name"); adapter.Fill(ds, "Sex"); adapter.Fill(ds, "Job"); adapter.Fill(ds, "Phone"); adapter.Fill(ds, "CarNumP"); adapter.Fill(ds, "Photo"); try { TBR.Id = ds.Tables["Encode_ID"].Rows[0]["Encode_ID"].ToString(); TBR.Name = ds.Tables["Name"].Rows[0]["Name"].ToString(); TBR.Sex = ds.Tables["Sex"].Rows[0]["Sex"].ToString(); TBR.Job = ds.Tables["Job"].Rows[0]["Job"].ToString(); TBR.CarNumP = ds.Tables["CarNumP"].Rows[0]["CarNumP"].ToString(); TBR.CarNumP = ds.Tables["Phone"].Rows[0]["Phone"].ToString(); TBR.Photo = (byte[])ds.Tables["Photo"].Rows[0]["Photo"]; table_row.Add(TBR); ds.Tables.Clear(); string Table_name = DT_Now.ToString("yyyy_MM"); Check_Table_Exsits(Access_DataBase.DB_Conn_Open(connectionString_QRcode_Scan), cmd, Table_name);//檢查有無當月Table沒有建立 ShowInfo SI_form = new ShowInfo(table_row, this, Table_name, connectionString_QRcode_Scan); } catch { TimerThread.Stop(); string message = "此條碼可能被註銷,或者不是岡山榮家發行"; string caption = "查無此資料"; MessageBoxButtons buttons = MessageBoxButtons.OK; DialogResult DiaResult = MessageBox.Show(message, caption, buttons); //MessageBox.Show(message, caption, buttons); if (DiaResult == DialogResult.OK) { TimerThread.Start(); } } } catch (Exception ex) { MessageBox.Show(ex.ToString()); } } } } }
/// <summary> /// Apply template /// </summary> /// <param name="template"></param> /// <param name="image"></param> public OmrPageOutput ApplyTemplate(OmrTemplate template, ScannedImage image) { // Image ready for scan if (!image.IsReadyForScan) { if (!image.IsScannable) { image.Analyze(); } image.PrepareProcessing(); } // Page output var retVal = new OmrPageOutput { Id = image.TemplateName + DateTime.Now.ToString("yyyyMMddHHmmss"), TemplateId = image.TemplateName, Parameters = image.Parameters, StartTime = DateTime.Now, Template = template }; // Save directory for output images var saveDirectory = string.Empty; var parmStr = new StringBuilder(); if (SaveIntermediaryImages) { if (image.Parameters != null) { foreach (var pv in image.Parameters) { parmStr.AppendFormat("{0}.", pv); } } retVal.RefImages = new List <string> { string.Format("{0}-{1}-init.bmp", retVal.Id, parmStr), string.Format("{0}-{1}-tx.bmp", retVal.Id, parmStr), string.Format("{0}-{1}-fields.bmp", retVal.Id, parmStr), string.Format("{0}-{1}-gs.bmp", retVal.Id, parmStr), string.Format("{0}-{1}-bw.bmp", retVal.Id, parmStr), string.Format("{0}-{1}-inv.bmp", retVal.Id, parmStr) }; saveDirectory = Path.Combine(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location), "imgproc"); if (!Directory.Exists(saveDirectory)) { Directory.CreateDirectory(saveDirectory); } image.Image.Save(Path.Combine(saveDirectory, string.Format("{0}-{1}-init.bmp", DateTime.Now.ToString("yyyyMMddHHmmss"), parmStr))); } // First, we want to get the image from the scanned image and translate it to the original // position in the template Bitmap bmp = null; try { bmp = new Bitmap((int)template.BottomRight.X, (int)template.BottomRight.Y, PixelFormat.Format24bppRgb); // Scale float width = template.TopRight.X - template.TopLeft.X, height = template.BottomLeft.Y - template.TopLeft.Y; // Translate to original using (var g = Graphics.FromImage(bmp)) { var bc = new ResizeBicubic((int)width, (int)height); g.DrawImage(bc.Apply((Bitmap)image.Image), template.TopLeft.X, template.TopLeft.Y); } if (SaveIntermediaryImages) { bmp.Save(Path.Combine(saveDirectory, string.Format("{0}-{1}-tx.bmp", DateTime.Now.ToString("yyyyMMddHHmmss"), parmStr))); } // Now try to do hit from the template if (SaveIntermediaryImages) { using (var tbmp = bmp.Clone() as Bitmap) { using (var g = Graphics.FromImage(tbmp)) { foreach (var field in template.Fields) { g.DrawRectangle(Pens.Black, field.TopLeft.X, field.TopLeft.Y, field.TopRight.X - field.TopLeft.X, field.BottomLeft.Y - field.TopLeft.Y); g.DrawString(field.Id, SystemFonts.CaptionFont, Brushes.Black, field.TopLeft); } } tbmp.Save(Path.Combine(saveDirectory, string.Format("{0}-{1}-fields.bmp", DateTime.Now.ToString("yyyyMMddHHmmss"), parmStr))); } } // Now convert to Grayscale var grayFilter = new GrayscaleY(); var gray = grayFilter.Apply(bmp); bmp.Dispose(); bmp = gray; if (SaveIntermediaryImages) { bmp.Save(Path.Combine(saveDirectory, string.Format("{0}-{1}-gs.bmp", DateTime.Now.ToString("yyyyMMddHHmmss"), parmStr))); } // Prepare answers var hitFields = new Dictionary <OmrQuestionField, OmrOutputData>(); var barScan = new BarcodeReader(); barScan.Options.UseCode39ExtendedMode = true; barScan.Options.UseCode39RelaxedExtendedMode = true; barScan.Options.TryHarder = true; barScan.TryInverted = true; barScan.Options.PureBarcode = false; barScan.AutoRotate = true; foreach (var itm in template.Fields.Where(o => o is OmrBarcodeField)) { var position = itm.TopLeft; var size = new SizeF(itm.TopRight.X - itm.TopLeft.X, itm.BottomLeft.Y - itm.TopLeft.Y); using ( var areaOfInterest = new Crop(new Rectangle((int)position.X, (int)position.Y, (int)size.Width, (int)size.Height)).Apply(bmp)) { // Scan the barcode var result = barScan.Decode(areaOfInterest); if (result != null) { hitFields.Add(itm, new OmrBarcodeData { BarcodeData = result.Text, Format = result.BarcodeFormat, Id = itm.Id, TopLeft = new PointF(result.ResultPoints[0].X + position.X, result.ResultPoints[0].Y + position.Y), BottomRight = new PointF(result.ResultPoints[1].X + position.X, result.ResultPoints[0].Y + position.Y + 10) }); } } } // Now binarize var binaryThreshold = new Threshold(template.ScanThreshold); binaryThreshold.ApplyInPlace(bmp); if (SaveIntermediaryImages) { bmp.Save(Path.Combine(saveDirectory, string.Format("{0}-{1}-bw.bmp", DateTime.Now.ToString("yyyyMMddHHmmss"), parmStr))); } // Set return parameters var tAnalyzeFile = Path.Combine(Path.GetTempPath(), Path.GetTempFileName()); bmp.Save(tAnalyzeFile, ImageFormat.Jpeg); retVal.AnalyzedImage = tAnalyzeFile; retVal.BottomRight = new PointF(bmp.Width, bmp.Height); // Now Invert var invertFiter = new Invert(); invertFiter.ApplyInPlace(bmp); if (SaveIntermediaryImages) { bmp.Save(Path.Combine(saveDirectory, string.Format("{0}-{1}-inv.bmp", DateTime.Now.ToString("yyyyMMddHHmmss"), parmStr))); } // Crop out areas of interest var areasOfInterest = new List <KeyValuePair <OmrQuestionField, Bitmap> >(); foreach (var itm in template.Fields.Where(o => o is OmrBubbleField)) { var position = itm.TopLeft; var size = new SizeF(itm.TopRight.X - itm.TopLeft.X, itm.BottomLeft.Y - itm.TopLeft.Y); areasOfInterest.Add(new KeyValuePair <OmrQuestionField, Bitmap>( itm, new Crop(new Rectangle((int)position.X, (int)position.Y, (int)size.Width, (int)size.Height)).Apply(bmp)) ); } // Queue analysis var wtp = new WaitThreadPool(); var syncLock = new object(); foreach (var itm in areasOfInterest) { wtp.QueueUserWorkItem(img => { var parm = itm; try { var areaOfInterest = parm.Value; var field = parm.Key; var blobCounter = new BlobCounter(); blobCounter.FilterBlobs = true; // Check for circles blobCounter.ProcessImage(areaOfInterest); var blobs = blobCounter.GetObjectsInformation(); var blob = blobs.FirstOrDefault(o => o.Area == blobs.Max(b => b.Area)); if (blob != null) { //var area = new AForge.Imaging.ImageStatistics(blob).PixelsCountWithoutBlack; if (blob.Area < 30) { return; } var bubbleField = field as OmrBubbleField; lock (syncLock) { hitFields.Add(field, new OmrBubbleData { Id = field.Id, Key = bubbleField.Question, Value = bubbleField.Value, TopLeft = new PointF(blob.Rectangle.X + field.TopLeft.X, blob.Rectangle.Y + field.TopLeft.Y), BottomRight = new PointF(blob.Rectangle.X + blob.Rectangle.Width + field.TopLeft.X, blob.Rectangle.Y + blob.Rectangle.Height + field.TopLeft.Y), BlobArea = blob.Area }); } } } catch (Exception e) { Trace.TraceError(e.ToString()); } finally { parm.Value.Dispose(); } }, itm); } wtp.WaitOne(); // Organize the response foreach (var res in hitFields) { if (string.IsNullOrEmpty(res.Key.AnswerRowGroup)) { AddAnswerToOutputCollection(retVal, res); } else { // Rows of data var rowGroup = retVal.Details.Find(o => o.Id == res.Key.AnswerRowGroup) as OmrRowData; if (rowGroup == null) { rowGroup = new OmrRowData { Id = res.Key.AnswerRowGroup }; retVal.Details.Add(rowGroup); } AddAnswerToOutputCollection(rowGroup, res); } } // Remove temporary images //foreach (var f in retVal.RefImages) // File.Delete(Path.Combine(saveDirectory, f)); // Outcome is success retVal.Outcome = OmrScanOutcome.Success; } catch (Exception e) { retVal.Outcome = OmrScanOutcome.Failure; retVal.ErrorMessage = e.Message; Trace.TraceError(e.ToString()); } finally { retVal.StopTime = DateTime.Now; bmp.Dispose(); } return(retVal); }
/// <summary> /// 从Qr中获取内容 /// </summary> /// <param name="path"></param> /// <returns></returns> public string GetQrData(string path) { Image <Gray, Byte> image = new Image <Gray, Byte>(path), dist1 = image.CopyBlank(), dest2 = image.CopyBlank(); Image <Gray, Byte> threshimg = new Image <Gray, Byte>(image.Width, image.Height); CvInvoke.Threshold(image, threshimg, 120, 255, ThresholdType.Binary); //threshimg.Save(string.Format(@"E:\data\image\testimage\{0}-threshimg.jpg", Path.GetFileNameWithoutExtension(path))); var contours = new VectorOfVectorOfPoint(); CvInvoke.FindContours(threshimg, contours, dist1, RetrType.List, ChainApproxMethod.ChainApproxNone); var results = new List <Rectangle>(); for (var k = 0; k < contours.Size; k++) { if (contours[k].Size < 50) { continue; } var rectangle = CvInvoke.BoundingRectangle(contours[k]); float w = rectangle.Width; float h = rectangle.Height; float rate = Math.Min(w, h) / Math.Max(w, h); if (rate > 0.85) { dest2.Draw(rectangle, new Gray(255)); results.Add(rectangle); } } dest2.Save(string.Format(@"E:\data\image\testimage\{0}-range.jpg", Path.GetFileNameWithoutExtension(path))); //按照二维码规则,过滤不符合规范的区域 var filterResults = new List <Rectangle>(); foreach (var rectangle in results) { //if (results.Exists( // p => p.X > rectangle.X && p.X + p.Width < rectangle.X + rectangle.Width && p.Y > rectangle.Y && p.Y + p.Height < rectangle.Y + rectangle.Height)) //{ // filterResults.Add(rectangle); //} filterResults.Add(rectangle); } //根据矩形面积进行分组,面积允许误差范围为10% var sizeGroups = new Dictionary <int, List <Rectangle> >(); foreach (var filterResult in filterResults) { var size = filterResult.Height * filterResult.Width; foreach (var sizeGroup in sizeGroups) { if (Math.Abs(sizeGroup.Key - size) <= sizeGroup.Key * 0.1) { sizeGroup.Value.Add(filterResult); } } if (!sizeGroups.ContainsKey(size)) { var items = new List <Rectangle>() { filterResult }; sizeGroups[size] = items; } } //遍历分组,找出最符合二维码的组合 var groupItems = new List <List <Rectangle> >(); foreach (var sizeGroup in sizeGroups) { if (sizeGroup.Value.Count < 3) { continue; } var combinationResults = GetCombinationList(sizeGroup.Value.Count, 3); foreach (var combinationResult in combinationResults) { var r1 = sizeGroup.Value[combinationResult[0]]; var r2 = sizeGroup.Value[combinationResult[1]]; var r3 = sizeGroup.Value[combinationResult[2]]; if (Math.Abs(r1.Width - r2.Width) < 3 && Math.Abs(r1.Height - r2.Height) < 3 && Math.Abs(r2.Width - r3.Width) < 3 && Math.Abs(r2.Height - r3.Height) < 3) { int x = 0; int y = 0; if (Math.Abs(r1.X - r2.X) < r1.Width * 0.25) { y = Math.Abs(r1.Y - r2.Y); var min = r1.Y > r2.Y ? r2 : r1; if (Math.Abs(min.Y - r3.Y) > r1.Height * 0.25) { continue; } x = Math.Abs(r1.X - r3.X); } else if (Math.Abs(r1.Y - r2.Y) < r1.Height * 0.25) { y = Math.Abs(r1.Y - r3.Y); var min = r1.X > r2.X ? r2 : r1; if (Math.Abs(min.X - r3.X) > r1.Width * 0.25) { continue; } x = Math.Abs(r1.X - r2.X); } else if (Math.Abs(r1.Y - r3.Y) < r1.Height * 0.25) { y = Math.Abs(r1.Y - r2.Y); var min = r1.X > r3.X ? r3 : r1; if (Math.Abs(min.X - r2.X) > r1.Width * 0.25) { continue; } x = Math.Abs(r1.X - r3.X); } else if (Math.Abs(r1.X - r3.X) < r1.Width * 0.25) { y = Math.Abs(r1.Y - r3.Y); var min = r1.Y > r3.Y ? r3 : r1; if (Math.Abs(min.Y - r2.Y) > r1.Height * 0.25) { continue; } x = Math.Abs(r1.X - r2.X); } else { continue; } if (Math.Abs(x - y) < r1.Width * 0.25) { var item = new List <Rectangle>(); item.Add(r1); item.Add(r2); item.Add(r3); groupItems.Add(item); } } } } if (groupItems.Count == 0) { return(null); } var max = groupItems.OrderByDescending(p => (p[0].Height * p[0].Width)).ElementAt(0); //var newRects = max.OrderBy(p => p.X).ThenBy(p => p.Y).ToList(); //if (newRects[0].X != newRects[1].X && newRects[0].Y != newRects[2].Y) //{ // //三点仿射进行图片纠正 // var srcPoints = new PointF[] // { // new PointF(newRects[0].X, newRects[0].Y), new PointF(newRects[1].X, newRects[1].Y), // new PointF(newRects[2].X, newRects[2].Y) // }; // var destPoints = new PointF[] // { // new PointF(newRects[0].X, newRects[0].Y), new PointF(newRects[0].X, newRects[1].Y), // new PointF(newRects[2].X, newRects[0].Y) // }; // var warpImage = RotateHelper.WarpPerspective(image.Bitmap, srcPoints, destPoints); // image = new Image<Gray, Byte>(warpImage); // image.Save(string.Format(@"E:\data\image\testimage\{0}-Rotate.jpg", Path.GetFileNameWithoutExtension(path))); //} var minx = max.Min(p => p.X) - 10; var miny = max.Min(p => p.Y) - 10; var width = max.Max(p => (p.X + p.Width)) + 20; var height = max.Max(p => (p.Y + p.Height)) + 20; var code = ImageHelper.CutImage(image.Bitmap, new Rectangle(minx, miny, width - minx, height - miny)); code.Save(string.Format(@"E:\data\image\testimage\{0}-qr.jpg", Path.GetFileNameWithoutExtension(path))); BarcodeReader reader = new BarcodeReader(); reader.Options.CharacterSet = "utf-8"; reader.Options.TryHarder = true; var decodeObj = reader.Decode(code); if (decodeObj != null) { return(decodeObj.Text); } else { int count = 0; while (decodeObj == null) { if (count > 2) { break; } code = (Bitmap)code.ResizeImage( new Size((int)Math.Round(code.Width * 0.8), (int)Math.Round(code.Height * 0.8))); decodeObj = reader.Decode(code); if (decodeObj != null) { return(decodeObj.Text); } count++; } } return(null); }
/// <summary> /// Запустить сканирование /// </summary> public void StartScanning() { IsStarted = true; // Get our preview properties var previewProperties = _capture.VideoDeviceController.GetMediaStreamProperties(MediaStreamType.VideoPreview) as VideoEncodingProperties; _scanningTimer = new Timer(async(state) => { if (_isProcessingFrame || _capture == null || _capture.CameraStreamState != CameraStreamState.Streaming) { _scanningTimer?.Change(DelayBetweenAnalyzingFrames, Timeout.Infinite); return; } var token = _scanCancellationToken.Token; var delay = DelayBetweenAnalyzingFrames; _isProcessingFrame = true; VideoFrame destFrame = null; VideoFrame frame = null; try { // Setup a frame to use as the input settings destFrame = new VideoFrame(Windows.Graphics.Imaging.BitmapPixelFormat.Bgra8, (int)previewProperties.Width, (int)previewProperties.Height); // Get preview frame = await _capture.GetPreviewFrameAsync(destFrame); } catch (Exception ex) { Debug.WriteLine("GetPreviewFrame Failed: {0}", ex); } if (token.IsCancellationRequested) { return; } Result result = null; // Try decoding the image try { if (frame != null) { await _dispatcher.RunAsync(CoreDispatcherPriority.Low, () => { if (_bitmap == null) { _bitmap = new WriteableBitmap(frame.SoftwareBitmap.PixelWidth, frame.SoftwareBitmap.PixelHeight); } frame.SoftwareBitmap.CopyToBuffer(_bitmap.PixelBuffer); result = _barcodeReader.Decode(_bitmap); if (destFrame != null) { destFrame.Dispose(); destFrame = null; } frame.Dispose(); frame = null; }); } } catch (Exception ex) { } if (token.IsCancellationRequested) { return; } if (result != null) { CodeScanned?.Invoke(this, result); delay = DelayBetweenContinuousScans; } _isProcessingFrame = false; _scanningTimer?.Change(delay, Timeout.Infinite); }, null, InitialDelayBeforeAnalyzingFrames, Timeout.Infinite); }
private async void DecodeBarCode() { var reader = new BarcodeReader { AutoRotate = true, Options = new DecodingOptions { TryHarder = true, } }; var result = await Task.Run(() => reader.Decode(Image)); Debug.WriteLine(result != null ? "Barcode text : " + result.Text + "\nFormat : " + result.BarcodeFormat : "Barcode not found!"); }
bool SetupCaptureSession() { var started = DateTime.UtcNow; var availableResolutions = new List <CameraResolution> (); var consideredResolutions = new Dictionary <NSString, CameraResolution> { { AVCaptureSession.Preset352x288, new CameraResolution { Width = 352, Height = 288 } }, { AVCaptureSession.PresetMedium, new CameraResolution { Width = 480, Height = 360 } }, //480x360 { AVCaptureSession.Preset640x480, new CameraResolution { Width = 640, Height = 480 } }, { AVCaptureSession.Preset1280x720, new CameraResolution { Width = 1280, Height = 720 } }, { AVCaptureSession.Preset1920x1080, new CameraResolution { Width = 1920, Height = 1080 } } }; // configure the capture session for low resolution, change this if your code // can cope with more data or volume session = new AVCaptureSession() { SessionPreset = AVCaptureSession.Preset640x480 }; // create a device input and attach it to the session // var captureDevice = AVCaptureDevice.DefaultDeviceWithMediaType (AVMediaType.Video); AVCaptureDevice captureDevice = null; var devices = AVCaptureDevice.DevicesWithMediaType(AVMediaType.Video); foreach (var device in devices) { captureDevice = device; if (options.UseFrontCameraIfAvailable.HasValue && options.UseFrontCameraIfAvailable.Value && device.Position == AVCaptureDevicePosition.Front) { break; //Front camera successfully set } else if (device.Position == AVCaptureDevicePosition.Back && (!options.UseFrontCameraIfAvailable.HasValue || !options.UseFrontCameraIfAvailable.Value)) { break; //Back camera succesfully set } } if (captureDevice == null) { Console.WriteLine("No captureDevice - this won't work on the simulator, try a physical device"); if (overlayView != null) { this.AddSubview(overlayView); this.BringSubviewToFront(overlayView); } return(false); } CameraResolution resolution = null; // Find resolution // Go through the resolutions we can even consider foreach (var cr in consideredResolutions) { // Now check to make sure our selected device supports the resolution // so we can add it to the list to pick from if (captureDevice.SupportsAVCaptureSessionPreset(cr.Key)) { availableResolutions.Add(cr.Value); } } resolution = options.GetResolution(availableResolutions); // See if the user selected a resolution if (resolution != null) { // Now get the preset string from the resolution chosen var preset = (from c in consideredResolutions where c.Value.Width == resolution.Width && c.Value.Height == resolution.Height select c.Key).FirstOrDefault(); // If we found a matching preset, let's set it on the session if (!string.IsNullOrEmpty(preset)) { session.SessionPreset = preset; } } var input = AVCaptureDeviceInput.FromDevice(captureDevice); if (input == null) { Console.WriteLine("No input - this won't work on the simulator, try a physical device"); if (overlayView != null) { this.AddSubview(overlayView); this.BringSubviewToFront(overlayView); } return(false); } else { session.AddInput(input); } var startedAVPreviewLayerAlloc = DateTime.UtcNow; previewLayer = new AVCaptureVideoPreviewLayer(session); var totalAVPreviewLayerAlloc = DateTime.UtcNow - startedAVPreviewLayerAlloc; Console.WriteLine("PERF: Alloc AVCaptureVideoPreviewLayer took {0} ms.", totalAVPreviewLayerAlloc.TotalMilliseconds); //Framerate set here (15 fps) if (UIDevice.CurrentDevice.CheckSystemVersion(7, 0)) { var perf1 = PerformanceCounter.Start(); NSError lockForConfigErr = null; captureDevice.LockForConfiguration(out lockForConfigErr); if (lockForConfigErr == null) { captureDevice.ActiveVideoMinFrameDuration = new CMTime(1, 10); captureDevice.UnlockForConfiguration(); } PerformanceCounter.Stop(perf1, "PERF: ActiveVideoMinFrameDuration Took {0} ms"); } else { previewLayer.Connection.VideoMinFrameDuration = new CMTime(1, 10); } var perf2 = PerformanceCounter.Start(); #if __UNIFIED__ previewLayer.VideoGravity = AVLayerVideoGravity.ResizeAspectFill; #else previewLayer.LayerVideoGravity = AVLayerVideoGravity.ResizeAspectFill; #endif previewLayer.Frame = new CGRect(0, 0, this.Frame.Width, this.Frame.Height); previewLayer.Position = new CGPoint(this.Layer.Bounds.Width / 2, (this.Layer.Bounds.Height / 2)); layerView = new UIView(new CGRect(0, 0, this.Frame.Width, this.Frame.Height)); layerView.AutoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleHeight; layerView.Layer.AddSublayer(previewLayer); this.AddSubview(layerView); ResizePreview(UIApplication.SharedApplication.StatusBarOrientation); if (overlayView != null) { this.AddSubview(overlayView); this.BringSubviewToFront(overlayView); //overlayView.LayoutSubviews (); } PerformanceCounter.Stop(perf2, "PERF: Setting up layers took {0} ms"); var perf3 = PerformanceCounter.Start(); session.StartRunning(); PerformanceCounter.Stop(perf3, "PERF: session.StartRunning() took {0} ms"); var perf4 = PerformanceCounter.Start(); var videoSettings = NSDictionary.FromObjectAndKey(new NSNumber((int)CVPixelFormatType.CV32BGRA), CVPixelBuffer.PixelFormatTypeKey); // create a VideoDataOutput and add it to the sesion output = new AVCaptureVideoDataOutput { WeakVideoSettings = videoSettings }; // configure the output queue = new DispatchQueue("ZxingScannerView"); // (Guid.NewGuid().ToString()); var barcodeReader = new BarcodeReader(null, (img) => { var src = new RGBLuminanceSource(img); //, bmp.Width, bmp.Height); //Don't try and rotate properly if we're autorotating anyway if (ScanningOptions.AutoRotate.HasValue && ScanningOptions.AutoRotate.Value) { return(src); } var tmpInterfaceOrientation = UIInterfaceOrientation.Portrait; InvokeOnMainThread(() => tmpInterfaceOrientation = UIApplication.SharedApplication.StatusBarOrientation); switch (tmpInterfaceOrientation) { case UIInterfaceOrientation.Portrait: return(src.rotateCounterClockwise().rotateCounterClockwise().rotateCounterClockwise()); case UIInterfaceOrientation.PortraitUpsideDown: return(src.rotateCounterClockwise().rotateCounterClockwise().rotateCounterClockwise()); case UIInterfaceOrientation.LandscapeLeft: return(src); case UIInterfaceOrientation.LandscapeRight: return(src); } return(src); }, null, null); //(p, w, h, f) => new RGBLuminanceSource(p, w, h, RGBLuminanceSource.BitmapFormat.Unknown)); if (ScanningOptions.TryHarder.HasValue) { Console.WriteLine("TRY_HARDER: " + ScanningOptions.TryHarder.Value); barcodeReader.Options.TryHarder = ScanningOptions.TryHarder.Value; } if (ScanningOptions.PureBarcode.HasValue) { barcodeReader.Options.PureBarcode = ScanningOptions.PureBarcode.Value; } if (ScanningOptions.AutoRotate.HasValue) { Console.WriteLine("AUTO_ROTATE: " + ScanningOptions.AutoRotate.Value); barcodeReader.AutoRotate = ScanningOptions.AutoRotate.Value; } if (!string.IsNullOrEmpty(ScanningOptions.CharacterSet)) { barcodeReader.Options.CharacterSet = ScanningOptions.CharacterSet; } if (ScanningOptions.TryInverted.HasValue) { barcodeReader.TryInverted = ScanningOptions.TryInverted.Value; } if (ScanningOptions.PossibleFormats != null && ScanningOptions.PossibleFormats.Count > 0) { barcodeReader.Options.PossibleFormats = new List <BarcodeFormat>(); foreach (var pf in ScanningOptions.PossibleFormats) { barcodeReader.Options.PossibleFormats.Add(pf); } } outputRecorder = new OutputRecorder(ScanningOptions, img => { if (!IsAnalyzing) { return; } try { //var sw = new System.Diagnostics.Stopwatch(); //sw.Start(); var rs = barcodeReader.Decode(img); //sw.Stop(); //Console.WriteLine("Decode Time: {0} ms", sw.ElapsedMilliseconds); if (rs != null) { resultCallback(rs); } } catch (Exception ex) { Console.WriteLine("DECODE FAILED: " + ex); } }); output.AlwaysDiscardsLateVideoFrames = true; output.SetSampleBufferDelegate(outputRecorder, queue); PerformanceCounter.Stop(perf4, "PERF: SetupCamera Finished. Took {0} ms."); session.AddOutput(output); //session.StartRunning (); var perf5 = PerformanceCounter.Start(); NSError err = null; if (captureDevice.LockForConfiguration(out err)) { if (captureDevice.IsFocusModeSupported(AVCaptureFocusMode.ContinuousAutoFocus)) { captureDevice.FocusMode = AVCaptureFocusMode.ContinuousAutoFocus; } else if (captureDevice.IsFocusModeSupported(AVCaptureFocusMode.AutoFocus)) { captureDevice.FocusMode = AVCaptureFocusMode.AutoFocus; } if (captureDevice.IsExposureModeSupported(AVCaptureExposureMode.ContinuousAutoExposure)) { captureDevice.ExposureMode = AVCaptureExposureMode.ContinuousAutoExposure; } else if (captureDevice.IsExposureModeSupported(AVCaptureExposureMode.AutoExpose)) { captureDevice.ExposureMode = AVCaptureExposureMode.AutoExpose; } if (captureDevice.IsWhiteBalanceModeSupported(AVCaptureWhiteBalanceMode.ContinuousAutoWhiteBalance)) { captureDevice.WhiteBalanceMode = AVCaptureWhiteBalanceMode.ContinuousAutoWhiteBalance; } else if (captureDevice.IsWhiteBalanceModeSupported(AVCaptureWhiteBalanceMode.AutoWhiteBalance)) { captureDevice.WhiteBalanceMode = AVCaptureWhiteBalanceMode.AutoWhiteBalance; } if (UIDevice.CurrentDevice.CheckSystemVersion(7, 0) && captureDevice.AutoFocusRangeRestrictionSupported) { captureDevice.AutoFocusRangeRestriction = AVCaptureAutoFocusRangeRestriction.Near; } if (captureDevice.FocusPointOfInterestSupported) { captureDevice.FocusPointOfInterest = new PointF(0.5f, 0.5f); } if (captureDevice.ExposurePointOfInterestSupported) { captureDevice.ExposurePointOfInterest = new PointF(0.5f, 0.5f); } captureDevice.UnlockForConfiguration(); } else { Console.WriteLine("Failed to Lock for Config: " + err.Description); } PerformanceCounter.Stop(perf5, "PERF: Setup Focus in {0} ms."); return(true); }
private void timer1_Tick(object sender, EventArgs e) { if (pictureBox1.Image != null) { BarcodeReader reader = new BarcodeReader(); Result result = reader.Decode((Bitmap)pictureBox1.Image); if (result != null) { if (nhan.Equals("main")) { String caulenh = "select TenKH from KhachHang where MaKh='" + result.Text.ToString().Trim() + "'"; SqlDataAdapter sqldata = new SqlDataAdapter(caulenh, ketnoi); DataTable dt = new DataTable(); sqldata.Fill(dt); if (dt.Rows.Count == 1) { gui = result.Text.ToString().Trim(); textBox1.Text = dt.Rows[0]["TenKH"].ToString(); //textBox1.Text = result.Text.ToString().Trim(); timer1.Stop(); if (captureDevice.IsRunning) { captureDevice.Stop(); } } else { MessageBox.Show("Không Tìm Thấy Mã Khách Hàng Vui Lòng Thử Lại !", "" + "Lỗi truy xuất!"); timer1.Stop(); if (captureDevice.IsRunning) { captureDevice.Stop(); } this.Hide(); } } else if (nhan.Equals("login")) { String caulenh = "select * from ThuNgan where MaNV='" + result.Text.ToString().Trim() + "'"; SqlDataAdapter sqldata = new SqlDataAdapter(caulenh, ketnoi); DataTable dt = new DataTable(); sqldata.Fill(dt); if (dt.Rows.Count == 1) { //gui = result.Text.ToString().Trim(); //textBox1.Text = dt.Rows[0]["TenKH"].ToString(); //textBox1.Text = result.Text.ToString().Trim(); Hierarchy hie = new Hierarchy(); hie.setH(result.Text.ToString().Trim()); this.Hide(); main mn = new main(); mn.maThuNgan = hie.getH(); mn.ShowNameThuNgan(); timer1.Stop(); if (captureDevice.IsRunning) { captureDevice.Stop(); } mn.ShowDialog(); } else { MessageBox.Show("Không nhận dạng được thẻ"); timer1.Stop(); if (captureDevice.IsRunning) { captureDevice.Stop(); } this.Hide(); Login lg = new Login(); lg.ShowDialog(); } } } } }
private void timer1_Tick(object sender, EventArgs e) { string v = "varun", a = "ayushi", s = "shubhum", ak = "akshat"; int t = 12345, i = 123456, b = 1111, so = 8888; BarcodeReader Reader = new BarcodeReader(); Result result = Reader.Decode((Bitmap)pictureBox4.Image); try { string decoded = result.ToString().Trim(); textBox1.Text = decoded; /* SqlConnectionStringBuilder connectionStringBuilder = new SqlConnectionStringBuilder(); * connectionStringBuilder.DataSource = "."; * connectionStringBuilder.InitialCatalog = "TEMP"; * connectionStringBuilder.IntegratedSecurity = true; * SqlConnection con = new SqlConnection("Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=Paytm;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False"); * SqlCommand cmd = new SqlCommand("select name,qrcode form payqr where qrcode= @qrc",con); * cmd.Parameters.AddWithValue("@qrc",textBox1.Text); * con.Open(); * string value =cmd.ExecuteScalar()as string; * con.Close(); * if (textBox1.Text.Equals(value))*/ if (textBox1.Text == Convert.ToString(t)) { timer1.Stop(); button4.Enabled = true; textBox1.Text = decoded; textBox3.Text = v; args = v; args1 = textBox2.Text; args2 = textBox1.Text; Success pyn = new Success(); pyn.Show(); this.Hide(); } if (textBox1.Text == Convert.ToString(i)) { timer1.Stop(); button4.Enabled = true; textBox1.Text = decoded; textBox3.Text = a; args = a; args1 = textBox2.Text; args2 = textBox1.Text; Success pyn = new Success(); pyn.Show(); this.Hide(); } if (textBox1.Text == Convert.ToString(b)) { timer1.Stop(); button4.Enabled = true; textBox1.Text = decoded; textBox3.Text = s; args = s; args1 = textBox2.Text; args2 = textBox1.Text; Success pyn = new Success(); pyn.Show(); this.Hide(); } if (textBox1.Text == Convert.ToString(so)) { timer1.Stop(); button4.Enabled = true; textBox1.Text = decoded; textBox3.Text = ak; args = ak; args1 = textBox2.Text; args2 = textBox1.Text; Success pyn = new Success(); pyn.Show(); this.Hide(); } } catch (Exception ex) { } }
public void OnPreviewFrame(byte [] bytes, Android.Hardware.Camera camera) { if ((DateTime.Now - lastPreviewAnalysis).TotalMilliseconds < options.DelayBetweenAnalyzingFrames) { return; } try { /* OLD Android Code * //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); */ var cameraParameters = camera.GetParameters(); var img = new YuvImage(bytes, ImageFormatType.Nv21, cameraParameters.PreviewSize.Width, cameraParameters.PreviewSize.Height, null); var dataRect = GetFramingRectInPreview(); //var barcodeReader = new BarcodeReader(null, p => new PlanarYUVLuminanceSource(img.GetYuvData(), img.Width, img.Height, dataRect.Left, dataRect.Top, // dataRect.Width(), dataRect.Height(), false), null, null) //{ // AutoRotate = true, // TryHarder = true, //}; var barcodeReader = new BarcodeReader(null, null, null, (p, w, h, f) => new PlanarYUVLuminanceSource(p, w, h, 0, 0, w, h, false)) //new PlanarYUVLuminanceSource(p, w, h, dataRect.Left, dataRect.Top, dataRect.Width(), dataRect.Height(), false)) { AutoRotate = true, TryHarder = false }; if (this.options.PureBarcode.HasValue && this.options.PureBarcode.Value) { barcodeReader.PureBarcode = this.options.PureBarcode.Value; } if (this.options.PossibleFormats != null && this.options.PossibleFormats.Count > 0) { barcodeReader.PossibleFormats = this.options.PossibleFormats; } var result = barcodeReader.Decode(img.GetYuvData(), img.Width, img.Height, RGBLuminanceSource.BitmapFormat.Unknown); 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; } }
/// <summary> /// Decode the secret field /// </summary> private void DecodeSecretCode() { Uri uri; Match match; if (Regex.IsMatch(secretCodeField.Text, "https?://.*") && Uri.TryCreate(secretCodeField.Text, UriKind.Absolute, out uri)) { try { var request = (HttpWebRequest)WebRequest.Create(uri); request.AllowAutoRedirect = true; request.Timeout = 20000; request.UserAgent = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; Trident/4.0)"; using (var response = (HttpWebResponse)request.GetResponse()) { if (response.StatusCode == HttpStatusCode.OK && response.ContentType.StartsWith("image/", StringComparison.OrdinalIgnoreCase)) { using (var bitmap = (Bitmap)Image.FromStream(response.GetResponseStream())) { IBarcodeReader reader = new BarcodeReader(); var result = reader.Decode(bitmap); if (result != null && string.IsNullOrEmpty(result.Text) == false) { secretCodeField.Text = HttpUtility.UrlDecode(result.Text); } } } } } catch (Exception ex) { WinAuthForm.ErrorDialog(Owner, "Cannot load QR code image from " + secretCodeField.Text, ex); return; } } match = Regex.Match(secretCodeField.Text, @"otpauth://([^/]+)/([^?]+)\?(.*)", RegexOptions.IgnoreCase); if (match.Success) { var authtype = match.Groups[1].Value.ToLower(); var label = match.Groups[2].Value; if (authtype == HOTP) { counterBasedRadio.Checked = true; } else if (authtype == TOTP) { timeBasedRadio.Checked = true; counterField.Text = string.Empty; } var qs = WinAuthHelper.ParseQueryString(match.Groups[3].Value); if (qs["counter"] != null) { long counter; if (long.TryParse(qs["counter"], out counter)) { counterField.Text = counter.ToString(); } } var issuer = qs["issuer"]; if (string.IsNullOrEmpty(issuer) == false) { label = issuer + (string.IsNullOrEmpty(label) == false ? " (" + label + ")" : string.Empty); } nameField.Text = label; int period; if (int.TryParse(qs["period"], out period) && period > 0) { intervalField.Text = period.ToString(); } int digits; if (int.TryParse(qs["digits"], out digits) && digits > 0) { digitsField.Text = digits.ToString(); } Authenticator.HMACTypes hmac; if (Enum.TryParse(qs["algorithm"], true, out hmac)) { hashField.SelectedItem = hmac.ToString(); } } }
public bool Start(HostControl hostControl) { watcher.EnableRaisingEvents = true; tokenSource = new CancellationTokenSource(); Task.Run(() => { Match match; Result result; HashSet <string> listOfImages = new HashSet <string>(); int prevNumber = -1; while (!tokenSource.IsCancellationRequested) { if (workToDo.Wait(Timeout)) { workToDo.Reset(); match = validator.Match(eventArg.Name); if (match.Success) { var imageNumber = int.Parse(match.Groups[1].Value); if (prevNumber == -1 || imageNumber - prevNumber == 1) { try { Task.Delay(TimeSpan.FromMilliseconds(100)).Wait(); fileSynchronizer.Wait(); using (var imageStream = new FileStream(eventArg.FullPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) using (var image = new Bitmap(imageStream)) { result = barcodeReader.Decode(image); } fileSynchronizer.Set(); prevNumber = imageNumber; listOfImages.Add(eventArg.FullPath); if (result != null) { InitTask(listOfImages); prevNumber = -1; } } catch (IOException ex) when(ex.Message.Contains("because it is being used by another process")) { Console.WriteLine(ex.Message); } } else { InitTask(listOfImages); prevNumber = imageNumber; listOfImages.Add(eventArg.FullPath); } } else { File.Delete(eventArg.FullPath); } } else { if (listOfImages.Count > 0) { InitTask(listOfImages); } prevNumber = -1; } } }, tokenSource.Token); return(true); }
/// <summary> /// Verify and create the authenticator if needed /// </summary> /// <returns>true is successful</returns> private bool verifyAuthenticator(string privatekey) { if (string.IsNullOrEmpty(privatekey)) { return(false); } Authenticator.Name = nameField.Text; var digits = Authenticator.AuthenticatorData != null ? Authenticator.AuthenticatorData.CodeDigits : WinAuth.Authenticator.DEFAULT_CODE_DIGITS; if (string.IsNullOrEmpty(digitsField.Text) || int.TryParse(digitsField.Text, out digits) == false || digits <= 0) { return(false); } var hmac = WinAuth.Authenticator.HMACTypes.SHA1; Enum.TryParse((string)hashField.SelectedItem, out hmac); var authtype = timeBasedRadio.Checked ? TOTP : HOTP; var period = 0; if (string.IsNullOrEmpty(intervalField.Text) || int.TryParse(intervalField.Text, out period) == false || period <= 0) { return(false); } long counter = 0; // if this is a URL, pull it down Uri uri; Match match; if (Regex.IsMatch(privatekey, "https?://.*") && Uri.TryCreate(privatekey, UriKind.Absolute, out uri)) { try { var request = (HttpWebRequest)WebRequest.Create(uri); request.AllowAutoRedirect = true; request.Timeout = 20000; request.UserAgent = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; Trident/4.0)"; using (var response = (HttpWebResponse)request.GetResponse()) { if (response.StatusCode == HttpStatusCode.OK && response.ContentType.StartsWith("image/", StringComparison.OrdinalIgnoreCase)) { using (var bitmap = (Bitmap)Image.FromStream(response.GetResponseStream())) { IBarcodeReader reader = new BarcodeReader(); var result = reader.Decode(bitmap); if (result != null) { privatekey = HttpUtility.UrlDecode(result.Text); } } } } } catch (Exception ex) { WinAuthForm.ErrorDialog(Owner, "Cannot load QR code image from " + privatekey, ex); return(false); } } else if ((match = Regex.Match(privatekey, @"data:image/([^;]+);base64,(.*)", RegexOptions.IgnoreCase)) .Success) { var imagedata = Convert.FromBase64String(match.Groups[2].Value); using (var ms = new MemoryStream(imagedata)) { using (var bitmap = (Bitmap)Image.FromStream(ms)) { IBarcodeReader reader = new BarcodeReader(); var result = reader.Decode(bitmap); if (result != null) { privatekey = HttpUtility.UrlDecode(result.Text); } } } } else if (IsValidFile(privatekey)) { // assume this is the image file using (var bitmap = (Bitmap)Image.FromFile(privatekey)) { IBarcodeReader reader = new BarcodeReader(); var result = reader.Decode(bitmap); if (result != null) { privatekey = result.Text; } } } string issuer = null; string serial = null; // check for otpauth://, e.g. "otpauth://totp/[email protected]?secret=IHZJDKAEEC774BMUK3GX6SA" match = Regex.Match(privatekey, @"otpauth://([^/]+)/([^?]+)\?(.*)", RegexOptions.IgnoreCase); if (match.Success) { authtype = match.Groups[1].Value.ToLower(); var label = match.Groups[2].Value; var p = label.IndexOf(":"); if (p != -1) { issuer = label.Substring(0, p); label = label.Substring(p + 1); } var qs = WinAuthHelper.ParseQueryString(match.Groups[3].Value); privatekey = qs["secret"] ?? privatekey; int querydigits; if (int.TryParse(qs["digits"], out querydigits) && querydigits != 0) { digits = querydigits; } if (qs["counter"] != null) { long.TryParse(qs["counter"], out counter); } issuer = qs["issuer"]; if (string.IsNullOrEmpty(issuer) == false) { label = issuer + (string.IsNullOrEmpty(label) == false ? " (" + label + ")" : string.Empty); } serial = qs["serial"]; if (string.IsNullOrEmpty(label) == false) { Authenticator.Name = nameField.Text = label; } var periods = qs["period"]; if (string.IsNullOrEmpty(periods) == false) { int.TryParse(periods, out period); } if (qs["algorithm"] != null) { if (Enum.TryParse(qs["algorithm"], true, out hmac)) { hashField.SelectedItem = hmac.ToString(); } } } // just get the hex chars privatekey = Regex.Replace(privatekey, @"[^0-9a-z]", "", RegexOptions.IgnoreCase); if (privatekey.Length == 0) { WinAuthForm.ErrorDialog(Owner, "The secret code is not valid"); return(false); } try { Authenticator auth; if (authtype == TOTP) { if (string.Compare(issuer, "BattleNet", true) == 0) { if (string.IsNullOrEmpty(serial)) { throw new ApplicationException("Battle.net Authenticator does not have a serial"); } serial = serial.ToUpper(); if (Regex.IsMatch(serial, @"^[A-Z]{2}-?[\d]{4}-?[\d]{4}-?[\d]{4}$") == false) { throw new ApplicationException("Invalid serial for Battle.net Authenticator"); } auth = new BattleNetAuthenticator(); ((BattleNetAuthenticator)auth).SecretKey = Base32.getInstance().Decode(privatekey); ((BattleNetAuthenticator)auth).Serial = serial; issuer = string.Empty; } else if (issuer == "Steam") { auth = new SteamAuthenticator(); ((SteamAuthenticator)auth).SecretKey = Base32.getInstance().Decode(privatekey); ((SteamAuthenticator)auth).Serial = string.Empty; ((SteamAuthenticator)auth).DeviceId = string.Empty; //((SteamAuthenticator)auth).RevocationCode = string.Empty; ((SteamAuthenticator)auth).SteamData = string.Empty; Authenticator.Skin = null; issuer = string.Empty; } else { auth = new GoogleAuthenticator(); ((GoogleAuthenticator)auth).Enroll(privatekey); } timer.Enabled = true; codeProgress.Visible = true; timeBasedRadio.Checked = true; } else if (authtype == HOTP) { auth = new HOTPAuthenticator(); if (counterField.Text.Trim().Length != 0) { long.TryParse(counterField.Text.Trim(), out counter); } ((HOTPAuthenticator)auth).Enroll(privatekey, counter); // start with the next code timer.Enabled = false; codeProgress.Visible = false; counterBasedRadio.Checked = true; } else { WinAuthForm.ErrorDialog(Owner, "Only TOTP or HOTP authenticators are supported"); return(false); } auth.HMACType = hmac; auth.CodeDigits = digits; auth.Period = period; Authenticator.AuthenticatorData = auth; if (digits > 5) { codeField.SpaceOut = digits / 2; } else { codeField.SpaceOut = 0; } //string key = Base32.getInstance().Encode(this.Authenticator.AuthenticatorData.SecretKey); codeField.Text = auth.CurrentCode; codeProgress.Maximum = period; if (!(auth is HOTPAuthenticator) && auth.ServerTimeDiff == 0L && SyncErrorWarned == false) { SyncErrorWarned = true; MessageBox.Show(this, string.Format(strings.AuthenticatorSyncError, "Google"), WinAuthMain.APPLICATION_TITLE, MessageBoxButtons.OK, MessageBoxIcon.Warning); } } catch (Exception irre) { WinAuthForm.ErrorDialog(Owner, "Unable to create the authenticator. The secret code is probably invalid.", irre); return(false); } return(true); }
private async Task MessageReceivedAsync(IDialogContext context, IAwaitable <IMessageActivity> result) { var message = await result; var msg = context.MakeMessage(); msg.Type = ActivityTypes.Typing; await context.PostAsync(msg); var storageAccount = CloudStorageAccount.Parse(ConfigurationManager.AppSettings["AzureWebJobsStorage"]); var tableClient = storageAccount.CreateCloudTableClient(); CloudTable eventTable = tableClient.GetTableReference("Event"); eventTable.CreateIfNotExists(); DateTime thisDay = DateTime.Today; String today = FormatDate(thisDay.ToString("d")); EventEntity eventEntity = null; string codeEntered = ""; if (message.Attachments.FirstOrDefault() != null) { string destinationContainer = "qrcode"; CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient(); var blobContainer = blobClient.GetContainerReference(destinationContainer); blobContainer.CreateIfNotExists(); String newFileName = ""; var a = message.Attachments.FirstOrDefault(); try { using (HttpClient httpClient = new HttpClient()) { var responseMessage = await httpClient.GetAsync(a.ContentUrl); var contentLenghtBytes = responseMessage.Content.Headers.ContentLength; var fileByte = await httpClient.GetByteArrayAsync(a.ContentUrl); newFileName = context.UserData.GetValue <string>(ContextConstants.UserId) + "_" + DateTime.Now.ToString("MMddyyyy-hhmmss") + "_" + "qrcode"; var barcodeReader = new BarcodeReader(); var memoryStream = new MemoryStream(fileByte); string sourceUrl = a.ContentUrl; var barcodeBitmap = (Bitmap)Bitmap.FromStream(memoryStream); var barcodeResult = barcodeReader.Decode(barcodeBitmap); codeEntered = barcodeResult.Text; eventEntity = GetEvent(barcodeResult.Text); memoryStream.Close(); } } catch (Exception e) { Debug.WriteLine(e.ToString()); } } else { codeEntered = message.Text; eventEntity = GetEvent(message.Text); } //Check database if (eventEntity != null) { var eventName = eventEntity.EventName; CloudTable attendanceTable = tableClient.GetTableReference("Attendance"); attendanceTable.CreateIfNotExists(); String filterA = TableQuery.GenerateFilterCondition("SurveyCode", QueryComparisons.Equal, eventEntity.SurveyCode); String filterB = TableQuery.GenerateFilterCondition("RowKey", QueryComparisons.Equal, context.UserData.GetValue <string>(ContextConstants.UserId)); String filterD = TableQuery.GenerateFilterCondition("PartitionKey", QueryComparisons.Equal, eventEntity.RowKey); TableQuery <AttendanceEntity> query = new TableQuery <AttendanceEntity>().Where(TableQuery.CombineFilters(filterA, TableOperators.And, filterB)); TableQuery <AttendanceEntity> todayQuery = new TableQuery <AttendanceEntity>().Where(TableQuery.CombineFilters(TableQuery.CombineFilters(filterA, TableOperators.And, filterB), TableOperators.And, filterD)); var results = attendanceTable.ExecuteQuery(query); var todayResults = attendanceTable.ExecuteQuery(todayQuery); Boolean notDone = true; //Survey Code if (codeEntered == eventEntity.SurveyCode) { if (results != null) { foreach (AttendanceEntity a in results) { if (a.Survey == true) { notDone = false; await context.PostAsync("You have already completed the survey for " + "'" + eventName + "'!"); await context.PostAsync(msg); await context.PostAsync("Talk to me again if you require my assistance."); context.Done(this); } } if (notDone && !ValidPeriod(eventEntity.SurveyEndDate, eventEntity.SurveyEndTime, eventEntity.EventStartDate)) { await context.PostAsync("Sorry, this code is not yet ready for use or have already expired!"); await context.PostAsync(msg); await context.PostAsync("Talk to me again if you require my assistance."); context.Done(this); } } context.UserData.SetValue(ContextConstants.Status, "3"); context.UserData.SetValue(ContextConstants.Survey, eventEntity.Survey); //Attendance Code 1 } else if (codeEntered == eventEntity.AttendanceCode1) { if (todayResults != null) { foreach (AttendanceEntity a in todayResults) { if (a.Morning == true) { notDone = false; await context.PostAsync("You have already registered this attendance for " + "'" + eventName + "'" + " today!"); await context.PostAsync(msg); await context.PostAsync("Talk to me again if you require my assistance."); context.Done(this); } } if (notDone && !ValidTime(eventEntity.AttendanceCode1StartTime, eventEntity.AttendanceCode1EndTime, eventEntity.Day, eventEntity.EventStartDate, eventEntity.EventEndDate)) { await context.PostAsync("Sorry, this code is not yet ready for use or have already expired!"); await context.PostAsync(msg); await context.PostAsync("Talk to me again if you require my assistance."); context.Done(this); } } context.UserData.SetValue(ContextConstants.Status, "1"); }//Attendance code 2 else if (codeEntered == eventEntity.AttendanceCode2) { if (todayResults != null) { foreach (AttendanceEntity a in todayResults) { if (a.Afternoon == true) { notDone = false; await context.PostAsync("You have already registered this attendance for " + "'" + eventName + "'" + " today!"); await context.PostAsync(msg); await context.PostAsync("Talk to me again if you require my assistance."); context.Done(this); } } if (notDone && !ValidTime(eventEntity.AttendanceCode2StartTime, eventEntity.AttendanceCode2EndTime, eventEntity.Day, eventEntity.EventStartDate, eventEntity.EventEndDate)) { await context.PostAsync("Sorry, this code is not yet ready for use or have already expired!"); await context.PostAsync(msg); await context.PostAsync("Talk to me again if you require my assistance."); context.Done(this); } } context.UserData.SetValue(ContextConstants.Status, "2"); } context.UserData.SetValue(ContextConstants.EventCode, eventEntity.RowKey); context.UserData.SetValue(ContextConstants.SurveyCode, eventEntity.SurveyCode); context.UserData.SetValue(ContextConstants.Anonymous, eventEntity.Anonymous); context.UserData.SetValue(ContextConstants.EventName, eventName); context.UserData.SetValue(ContextConstants.Today, today); context.UserData.SetValue(ContextConstants.Description, eventEntity.Description); context.Done(true); } else { await context.PostAsync("I'm sorry, I think you have keyed in the wrong workshop code or have sent an invalid QR Code, let's do this again."); context.Wait(this.MessageReceivedAsync); } }
protected override void OnCreate(Bundle bundle) { base.OnCreate(bundle); // Somewhere in your app, call the initialization code: MobileBarcodeScanner.Initialize(Application); // Set our view from the "main" layout resource SetContentView(Resource.Layout.Main); //Create a new instance of our Scanner scanner = new MobileBarcodeScanner(); // Get our button from the layout resource, // and attach an event to it Button button = FindViewById <Button>(Resource.Id.myButton); button.Click += delegate { _imageView = FindViewById <ImageView>(Resource.Id.imageView1); //BitmapFactory.Options options = new BitmapFactory.Options //{ // InJustDecodeBounds = false //}; //// The result will be null because InJustDecodeBounds == true. //Bitmap bitmapToDisplay = await BitmapFactory.DecodeResourceAsync(Resources, Resource.Drawable.download1); //_imageView.SetImageBitmap(bitmapToDisplay); _imageView.SetImageBitmap( decodeSampledBitmapFromResource(Resources, Resource.Drawable.qrcode, 375, 375)); }; Button buttonScan = FindViewById <Button>(Resource.Id.buttonScan); //buttonScan.Click += async delegate { //var scanner = new ZXing.Mobile.MobileBarcodeScanner(); //var result = await scanner.Scan(); //if (result != null) // Console.WriteLine("Scanned Barcode: " + result.Text); //}; buttonScan.Click += delegate { //var fullName = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Images", "download.png"); String path = System.Environment.CurrentDirectory; BitmapFactory.Options options = new BitmapFactory.Options { InPreferredConfig = Bitmap.Config.Argb8888 }; //BitmapFactory.Options options = new BitmapFactory.Options //{ // InJustDecodeBounds = true //}; // The result will be null because InJustDecodeBounds == true. //Bitmap bitmap = await BitmapFactory.DecodeResourceAsync(Resources, Resource.Drawable.download1, options); Bitmap bitmap = decodeSampledBitmapFromResource(Resources, Resource.Drawable.qrcode, 375, 375); // var imageHeight = options.OutHeight; //var imageWidth = options.OutWidth; var imageHeight = (int)bitmap.GetBitmapInfo().Height; var imageWidth = (int)bitmap.GetBitmapInfo().Width; //using (var stream = new MemoryStream()) //{ // bitmap.Compress(Bitmap.CompressFormat.Png, 0, stream); // bitmapData = stream.ToArray(); //} int size = (int)bitmap.RowBytes * (int)bitmap.GetBitmapInfo().Height; Java.Nio.ByteBuffer byteBuffer = Java.Nio.ByteBuffer.Allocate(size); bitmap.CopyPixelsToBuffer(byteBuffer); byte[] byteArray = new byte[byteBuffer.Remaining()]; var imageBytes = byteBuffer.Get(byteArray); LuminanceSource source = new ZXing.RGBLuminanceSource(byteArray, (int)imageWidth, (int)imageHeight); var barcodeReader = new BarcodeReader(); barcodeReader.Options.TryHarder = true; //barcodeReader.Options.ReturnCodabarStartEnd = true; //barcodeReader.Options.PureBarcode = true; //barcodeReader.Options.PossibleFormats = new List<BarcodeFormat>(); //barcodeReader.Options.PossibleFormats.Add(BarcodeFormat.QR_CODE); ZXing.Result result = barcodeReader.Decode(source); var result2 = barcodeReader.DecodeMultiple(source); ZXing.Result result3 = barcodeReader.Decode(byteArray, (int)imageWidth, (int)imageHeight, RGBLuminanceSource.BitmapFormat.RGB24); ZXing.Result result4 = barcodeReader.Decode(source); HybridBinarizer hb = new HybridBinarizer(source); var a = hb.createBinarizer(source); BinaryBitmap bBitmap = new BinaryBitmap(a); MultiFormatReader reader1 = new MultiFormatReader(); var r = reader1.decodeWithState(bBitmap); int[] intarray = new int[((int)imageHeight * (int)imageWidth)]; bitmap.GetPixels(intarray, 0, (int)bitmap.GetBitmapInfo().Width, 0, 0, (int)imageWidth, (int)imageHeight); LuminanceSource source5 = new RGBLuminanceSource(byteArray, (int)imageWidth, (int)imageHeight); BinaryBitmap bitmap3 = new BinaryBitmap(new HybridBinarizer(source)); ZXing.Reader reader = new DataMatrixReader(); //....doing the actually reading ZXing.Result result10 = reader.decode(bitmap3); //InputStream is = this.Resources.OpenRawResource(Resource.Id.imageView1); //Bitmap originalBitmap = BitmapFactory.decodeStream(is); //UIImage //var barcodeBitmap = (Bitmap)Bitmap.FromFile(@"C:\Users\jeremy\Desktop\qrimage.bmp"); }; Button buttonScan2 = FindViewById <Button>(Resource.Id.buttonScan2); buttonScan2.Click += async delegate { //Tell our scanner to activiyt use the default overlay scanner.UseCustomOverlay = false; //We can customize the top and bottom text of the default overlay scanner.TopText = "Hold the camera up to the barcode\nAbout 6 inches away"; scanner.BottomText = "Wait for the barcode to automatically scan!"; //Start scanning var result = await scanner.Scan(); // Handler for the result returned by the scanner. HandleScanResult(result); }; }
private void Decode(Bitmap image, bool tryMultipleBarcodes, IList <BarcodeFormat> possibleFormats) { resultPoints.Clear(); lastResults.Clear(); txtContent.Text = String.Empty; var timerStart = DateTime.Now.Ticks; Result[] results = null; var previousFormats = barcodeReader.Options.PossibleFormats; if (possibleFormats != null) { barcodeReader.Options.PossibleFormats = possibleFormats; } if (tryMultipleBarcodes) { results = barcodeReader.DecodeMultiple(image); } else { var result = barcodeReader.Decode(image); if (result != null) { results = new[] { result }; } } var timerStop = DateTime.Now.Ticks; barcodeReader.Options.PossibleFormats = previousFormats; if (results == null) { txtContent.Text = "No barcode recognized"; } labDuration.Text = new TimeSpan(timerStop - timerStart).ToString(); if (results != null) { foreach (var result in results) { if (result.ResultPoints.Length > 0) { var rect = new Rectangle((int)result.ResultPoints[0].X, (int)result.ResultPoints[0].Y, 1, 1); foreach (var point in result.ResultPoints) { if (point.X < rect.Left) { rect = new Rectangle((int)point.X, rect.Y, rect.Width + rect.X - (int)point.X, rect.Height); } if (point.X > rect.Right) { rect = new Rectangle(rect.X, rect.Y, rect.Width + (int)point.X - rect.X, rect.Height); } if (point.Y < rect.Top) { rect = new Rectangle(rect.X, (int)point.Y, rect.Width, rect.Height + rect.Y - (int)point.Y); } if (point.Y > rect.Bottom) { rect = new Rectangle(rect.X, rect.Y, rect.Width, rect.Height + (int)point.Y - rect.Y); } } using (var g = picBarcode.CreateGraphics()) { g.DrawRectangle(Pens.Green, rect); } } } } }
//scann the picture every x seconds private async void Timer_Tick(object sender, object e) { timer.Stop(); textBlockSessionInfo.Text = "point @ QR code"; ImageEncodingProperties imgFormat = ImageEncodingProperties.CreateJpeg(); // create storage file in local app storage StorageFile file = await ApplicationData.Current.LocalFolder.CreateFileAsync( "temp.jpg", CreationCollisionOption.GenerateUniqueName); //await camera.AutoFocus(); // take photo await camera.captureMgr.CapturePhotoToStorageFileAsync(imgFormat, file); // Get photo as a BitmapImage BitmapImage bmpImage = new BitmapImage(new Uri(file.Path)); bmpImage.CreateOptions = BitmapCreateOptions.IgnoreImageCache; WriteableBitmap wrb; ZXing.BarcodeReader br; Result res; using (IRandomAccessStream fileStream = await file.OpenAsync(FileAccessMode.Read)) { wrb = await Windows.UI.Xaml.Media.Imaging.BitmapFactory.New(1, 1).FromStream(fileStream); } br = new BarcodeReader { PossibleFormats = new BarcodeFormat[] { BarcodeFormat.QR_CODE } }; br.AutoRotate = true; br.Options.TryHarder = true; res = br.Decode(wrb.ToByteArray(), wrb.PixelWidth, wrb.PixelWidth, RGBLuminanceSource.BitmapFormat.RGBA32); if (res != null) { try { qrdata = Newtonsoft.Json.JsonConvert.DeserializeObject <QRCodeData>(res.Text); textBoxSessionId.Text = qrdata.uuid; textBlockSessionInfo.Text = qrdata.text; textBlockSessionInfoExtra.Text = res.Text; await camera.captureMgr.StopPreviewAsync(); capturePreview.Visibility = Visibility.Collapsed; } catch (Exception jsonEx) { textBoxSessionId.Text = "error " + jsonEx.Message; timer.Start(); } } else { timer.Start(); } }
public void OnPreviewFrame(byte [] bytes, Android.Hardware.Camera camera) { //Check and see if we're still processing a previous frame if (processingTask != null && !processingTask.IsCompleted) { return; } if ((DateTime.UtcNow - lastPreviewAnalysis).TotalMilliseconds < options.DelayBetweenAnalyzingFrames) { return; } var cameraParameters = camera.GetParameters(); var width = cameraParameters.PreviewSize.Width; var height = cameraParameters.PreviewSize.Height; //var img = new YuvImage(bytes, ImageFormatType.Nv21, cameraParameters.PreviewSize.Width, cameraParameters.PreviewSize.Height, null); lastPreviewAnalysis = DateTime.UtcNow; processingTask = Task.Factory.StartNew(() => { try { if (barcodeReader == null) { barcodeReader = new BarcodeReader(null, null, null, (p, w, h, f) => new PlanarYUVLuminanceSource(p, w, h, 0, 0, w, h, false)); //new PlanarYUVLuminanceSource(p, w, h, dataRect.Left, dataRect.Top, dataRect.Width(), dataRect.Height(), false)) if (this.options.TryHarder.HasValue) { barcodeReader.Options.TryHarder = this.options.TryHarder.Value; } if (this.options.PureBarcode.HasValue) { barcodeReader.Options.PureBarcode = this.options.PureBarcode.Value; } if (!string.IsNullOrEmpty(this.options.CharacterSet)) { barcodeReader.Options.CharacterSet = this.options.CharacterSet; } if (this.options.TryInverted.HasValue) { barcodeReader.TryInverted = this.options.TryInverted.Value; } if (this.options.PossibleFormats != null && this.options.PossibleFormats.Count > 0) { barcodeReader.Options.PossibleFormats = new List <BarcodeFormat> (); foreach (var pf in this.options.PossibleFormats) { barcodeReader.Options.PossibleFormats.Add(pf); } } } bool rotate = false; int newWidth = width; int newHeight = height; var cDegrees = getCameraDisplayOrientation(this.activity); if (cDegrees == 90 || cDegrees == 270) { rotate = true; newWidth = height; newHeight = width; } var start = PerformanceCounter.Start(); if (rotate) { bytes = rotateCounterClockwise(bytes, width, height); } var result = barcodeReader.Decode(bytes, newWidth, newHeight, RGBLuminanceSource.BitmapFormat.Unknown); PerformanceCounter.Stop(start, "Decode Time: {0} ms (width: " + width + ", height: " + height + ", degrees: " + cDegrees + ", rotate: " + rotate + ")"); if (result == null || string.IsNullOrEmpty(result.Text)) { return; } Android.Util.Log.Debug("ZXing.Mobile", "Barcode Found: " + result.Text); //扫描完成后,并不立即停止扫描,为了实现连续扫描的功能(注意这时扫描成功后,一定要手动停止扫描) //ShutdownCamera (); callback(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; } }); }
bool SetupCaptureSession() { // configure the capture session for low resolution, change this if your code // can cope with more data or volume session = new AVCaptureSession() { SessionPreset = AVCaptureSession.Preset640x480 }; // create a device input and attach it to the session // var captureDevice = AVCaptureDevice.DefaultDeviceWithMediaType (AVMediaType.Video); AVCaptureDevice captureDevice = null; var devices = AVCaptureDevice.DevicesWithMediaType(AVMediaType.Video); foreach (var device in devices) { captureDevice = device; if (options.UseFrontCameraIfAvailable.HasValue && options.UseFrontCameraIfAvailable.Value && device.Position == AVCaptureDevicePosition.Front) { break; //Front camera successfully set } else if (device.Position == AVCaptureDevicePosition.Back && (!options.UseFrontCameraIfAvailable.HasValue || !options.UseFrontCameraIfAvailable.Value)) { break; //Back camera succesfully set } } if (captureDevice == null) { Console.WriteLine("No captureDevice - this won't work on the simulator, try a physical device"); if (overlayView != null) { this.AddSubview(overlayView); this.BringSubviewToFront(overlayView); } return(false); } var input = AVCaptureDeviceInput.FromDevice(captureDevice); if (input == null) { Console.WriteLine("No input - this won't work on the simulator, try a physical device"); if (overlayView != null) { this.AddSubview(overlayView); this.BringSubviewToFront(overlayView); } return(false); } else { session.AddInput(input); } previewLayer = new AVCaptureVideoPreviewLayer(session); //Framerate set here (15 fps) if (previewLayer.RespondsToSelector(new Selector("connection"))) { previewLayer.Connection.VideoMinFrameDuration = new CMTime(1, 10); } previewLayer.LayerVideoGravity = AVLayerVideoGravity.ResizeAspectFill; previewLayer.Frame = new RectangleF(0, 0, this.Frame.Width, this.Frame.Height); previewLayer.Position = new PointF(this.Layer.Bounds.Width / 2, (this.Layer.Bounds.Height / 2)); layerView = new UIView(new RectangleF(0, 0, this.Frame.Width, this.Frame.Height)); layerView.AutoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleHeight; layerView.Layer.AddSublayer(previewLayer); this.AddSubview(layerView); ResizePreview(UIApplication.SharedApplication.StatusBarOrientation); if (overlayView != null) { this.AddSubview(overlayView); this.BringSubviewToFront(overlayView); //overlayView.LayoutSubviews (); } session.StartRunning(); Console.WriteLine("RUNNING!!!"); // create a VideoDataOutput and add it to the sesion output = new AVCaptureVideoDataOutput() { //videoSettings VideoSettings = new AVVideoSettings(CVPixelFormatType.CV32BGRA), }; // configure the output queue = new MonoTouch.CoreFoundation.DispatchQueue("ZxingScannerView"); // (Guid.NewGuid().ToString()); var barcodeReader = new BarcodeReader(null, (img) => { var src = new RGBLuminanceSource(img); //, bmp.Width, bmp.Height); //Don't try and rotate properly if we're autorotating anyway if (ScanningOptions.AutoRotate.HasValue && ScanningOptions.AutoRotate.Value) { return(src); } var tmpInterfaceOrientation = UIInterfaceOrientation.Portrait; InvokeOnMainThread(() => tmpInterfaceOrientation = UIApplication.SharedApplication.StatusBarOrientation); switch (tmpInterfaceOrientation) { case UIInterfaceOrientation.Portrait: return(src.rotateCounterClockwise().rotateCounterClockwise().rotateCounterClockwise()); case UIInterfaceOrientation.PortraitUpsideDown: return(src.rotateCounterClockwise().rotateCounterClockwise().rotateCounterClockwise()); case UIInterfaceOrientation.LandscapeLeft: return(src); case UIInterfaceOrientation.LandscapeRight: return(src); } return(src); }, null, null); //(p, w, h, f) => new RGBLuminanceSource(p, w, h, RGBLuminanceSource.BitmapFormat.Unknown)); if (ScanningOptions.TryHarder.HasValue) { Console.WriteLine("TRY_HARDER: " + ScanningOptions.TryHarder.Value); barcodeReader.Options.TryHarder = ScanningOptions.TryHarder.Value; } if (ScanningOptions.PureBarcode.HasValue) { barcodeReader.Options.PureBarcode = ScanningOptions.PureBarcode.Value; } if (ScanningOptions.AutoRotate.HasValue) { Console.WriteLine("AUTO_ROTATE: " + ScanningOptions.AutoRotate.Value); barcodeReader.AutoRotate = ScanningOptions.AutoRotate.Value; } if (!string.IsNullOrEmpty(ScanningOptions.CharacterSet)) { barcodeReader.Options.CharacterSet = ScanningOptions.CharacterSet; } if (ScanningOptions.TryInverted.HasValue) { barcodeReader.TryInverted = ScanningOptions.TryInverted.Value; } if (ScanningOptions.PossibleFormats != null && ScanningOptions.PossibleFormats.Count > 0) { barcodeReader.Options.PossibleFormats = new List <BarcodeFormat>(); foreach (var pf in ScanningOptions.PossibleFormats) { barcodeReader.Options.PossibleFormats.Add(pf); } } outputRecorder = new OutputRecorder(ScanningOptions, img => { if (!IsAnalyzing) { return; } try { var started = DateTime.Now; var rs = barcodeReader.Decode(img); var total = DateTime.Now - started; Console.WriteLine("Decode Time: " + total.TotalMilliseconds + " ms"); if (rs != null) { resultCallback(rs); } } catch (Exception ex) { Console.WriteLine("DECODE FAILED: " + ex); } }); output.AlwaysDiscardsLateVideoFrames = true; output.SetSampleBufferDelegate(outputRecorder, queue); Console.WriteLine("SetupCamera Finished"); session.AddOutput(output); //session.StartRunning (); if (captureDevice.IsFocusModeSupported(AVCaptureFocusMode.ModeContinuousAutoFocus)) { NSError err = null; if (captureDevice.LockForConfiguration(out err)) { captureDevice.FocusMode = AVCaptureFocusMode.ModeContinuousAutoFocus; if (captureDevice.FocusPointOfInterestSupported) { captureDevice.FocusPointOfInterest = new PointF(0.5f, 0.5f); } captureDevice.UnlockForConfiguration(); } else { Console.WriteLine("Failed to Lock for Config: " + err.Description); } } return(true); }
///<summary> ///解码 ///</summary> ///<paramname="pictureBox1"></param> public void Decode(PictureBox pictureBox1) { BarcodeReader reader = new BarcodeReader(); Result result = reader.Decode((Bitmap)pictureBox1.Image); }
/// <summary> /// 解析二维码图片 /// </summary> /// <param name="writeableBmp">图片</param> /// <returns></returns> private async Task ScanBitmap(WriteableBitmap writeableBmp) { try { var barcodeReader = new BarcodeReader { AutoRotate = true, Options = new ZXing.Common.DecodingOptions { TryHarder = true } }; await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { _result = barcodeReader.Decode(writeableBmp); }); if (_result != null) { Debug.WriteLine(@"[INFO]扫描到二维码:{result} ->" + _result.Text); await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { string ban = Regex.Match(_result.Text, @"^http://bangumi.bilibili.com/anime/(.*?)$").Groups[1].Value; if (ban.Length != 0) { //args.Handled = true; MessageCenter.SendNavigateTo(NavigateMode.Info, typeof(BanInfoPage), ban.Replace("/", "")); this.Frame.GoBack(); return; } string ban2 = Regex.Match(_result.Text, @"^http://www.bilibili.com/bangumi/i/(.*?)$").Groups[1].Value; if (ban2.Length != 0) { //args.Handled = true; MessageCenter.SendNavigateTo(NavigateMode.Info, typeof(BanInfoPage), ban2.Replace("/", "")); this.Frame.GoBack(); // this.Frame.Navigate(typeof(BanInfoPage), ban2.Replace("/", "")); return; } //bilibili://?av=4284663 string ban3 = Regex.Match(_result.Text, @"^bilibili://?av=(.*?)$").Groups[1].Value; if (ban3.Length != 0) { //args.Handled = true; MessageCenter.SendNavigateTo(NavigateMode.Info, typeof(VideoViewPage), ban3.Replace("/", "")); this.Frame.GoBack(); //this.Frame.Navigate(typeof(VideoViewPage), ban3.Replace("/", "")); return; } string ban4 = Regex.Match(_result.Text + "/", @"space.bilibili.com/(.*?)/").Groups[1].Value; if (ban4.Length != 0) { //args.Handled = true; MessageCenter.SendNavigateTo(NavigateMode.Info, typeof(UserInfoPage), ban4.Replace("/", "")); this.Frame.GoBack(); //this.Frame.Navigate(typeof(VideoViewPage), ban3.Replace("/", "")); return; } string ban5 = Regex.Match(_result.Text + "/", @"oauthKey=(.*?)/").Groups[1].Value; if (ban5.Length != 0) { MessageCenter.SendNavigateTo(NavigateMode.Info, typeof(WebPage), "https://passport.bilibili.com/qrcode/h5/login?oauthKey=" + ban5.Replace("/", "")); this.Frame.GoBack(); //if (!ApiHelper.IsLogin()) //{ // await new MessageDialog("手机需先登录!").ShowAsync(); // return; //} ////args.Handled = true; //pr_Laod.Visibility = Visibility.Visible; //LoginStatus dts = await ApiHelper.QRLogin(ban5.Replace("/", "")); //if (dts==LoginStatus.Succeed) //{ // this.Frame.GoBack(); //} //else //{ // await new MessageDialog("登录失败").ShowAsync(); //} //pr_Laod.Visibility = Visibility.Collapsed; //MessageCenter.SendNavigateTo(NavigateMode.Play, typeof(UserInfoPage), ban5.Replace("/", "")); //this.Frame.Navigate(typeof(VideoViewPage), ban3.Replace("/", "")); return; } //text .Text= args.Uri.AbsoluteUri; string live = Regex.Match(_result.Text, @"^bilibili://live/(.*?)$").Groups[1].Value; if (live.Length != 0) { MessageCenter.SendNavigateTo(NavigateMode.Play, typeof(LiveRoomPage), live); return; } string live2 = Regex.Match(_result.Text + "a", @"live.bilibili.com/(.*?)a").Groups[1].Value; if (live2.Length != 0) { MessageCenter.SendNavigateTo(NavigateMode.Play, typeof(LiveRoomPage), live2.Replace("a", "")); return; } if (Regex.IsMatch(_result.Text, "/video/av(.*)?[/|+](.*)?")) { string a = Regex.Match(_result.Text, "/video/av(.*)?[/|+](.*)?").Groups[1].Value; //this.Frame.Navigate(typeof(VideoViewPage), a); MessageCenter.SendNavigateTo(NavigateMode.Info, typeof(VideoViewPage), a); this.Frame.GoBack(); return; } tbkResult.Text = "无法识别的类型"; }); } } catch (Exception) { } }
bool SetupCaptureSession () { // configure the capture session for low resolution, change this if your code // can cope with more data or volume session = new AVCaptureSession () { SessionPreset = AVCaptureSession.Preset640x480 }; // create a device input and attach it to the session var captureDevice = AVCaptureDevice.DefaultDeviceWithMediaType (AVMediaType.Video); if (captureDevice == null){ Console.WriteLine ("No captureDevice - this won't work on the simulator, try a physical device"); return false; } var input = AVCaptureDeviceInput.FromDevice (captureDevice); if (input == null){ Console.WriteLine ("No input - this won't work on the simulator, try a physical device"); return false; } else session.AddInput (input); previewLayer = new AVCaptureVideoPreviewLayer(session); //Framerate set here (15 fps) if (previewLayer.RespondsToSelector(new Selector("connection"))) previewLayer.Connection.VideoMinFrameDuration = new CMTime(1, 10); previewLayer.LayerVideoGravity = AVLayerVideoGravity.ResizeAspectFill; previewLayer.Frame = this.Frame; previewLayer.Position = new PointF(this.Layer.Bounds.Width / 2, (this.Layer.Bounds.Height / 2)); layerView = new UIView(this.Frame); layerView.AutoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleHeight; layerView.Layer.AddSublayer(previewLayer); this.AddSubview(layerView); ResizePreview(UIApplication.SharedApplication.StatusBarOrientation); if (overlayView != null) { this.AddSubview (overlayView); this.BringSubviewToFront (overlayView); //overlayView.LayoutSubviews (); } session.StartRunning (); Console.WriteLine ("RUNNING!!!"); // create a VideoDataOutput and add it to the sesion output = new AVCaptureVideoDataOutput () { //videoSettings VideoSettings = new AVVideoSettings (CVPixelFormatType.CV32BGRA), }; // configure the output queue = new MonoTouch.CoreFoundation.DispatchQueue("ZxingScannerView"); // (Guid.NewGuid().ToString()); var barcodeReader = new BarcodeReader(null, (img) => { var src = new RGBLuminanceSource(img); //, bmp.Width, bmp.Height); //Don't try and rotate properly if we're autorotating anyway if (options.AutoRotate.HasValue && options.AutoRotate.Value) return src; switch (UIDevice.CurrentDevice.Orientation) { case UIDeviceOrientation.Portrait: return src.rotateCounterClockwise().rotateCounterClockwise().rotateCounterClockwise(); case UIDeviceOrientation.PortraitUpsideDown: return src.rotateCounterClockwise().rotateCounterClockwise().rotateCounterClockwise(); case UIDeviceOrientation.LandscapeLeft: return src; case UIDeviceOrientation.LandscapeRight: return src; } return src; }, null, null); //(p, w, h, f) => new RGBLuminanceSource(p, w, h, RGBLuminanceSource.BitmapFormat.Unknown)); if (this.options.TryHarder.HasValue) { Console.WriteLine("TRY_HARDER: " + this.options.TryHarder.Value); barcodeReader.Options.TryHarder = this.options.TryHarder.Value; } if (this.options.PureBarcode.HasValue) barcodeReader.Options.PureBarcode = this.options.PureBarcode.Value; if (this.options.AutoRotate.HasValue) { Console.WriteLine("AUTO_ROTATE: " + this.options.AutoRotate.Value); barcodeReader.AutoRotate = this.options.AutoRotate.Value; } if (!string.IsNullOrEmpty (this.options.CharacterSet)) barcodeReader.Options.CharacterSet = this.options.CharacterSet; if (this.options.TryInverted.HasValue) barcodeReader.TryInverted = this.options.TryInverted.Value; if (this.options.PossibleFormats != null && this.options.PossibleFormats.Count > 0) { barcodeReader.Options.PossibleFormats = new List<BarcodeFormat>(); foreach (var pf in this.options.PossibleFormats) barcodeReader.Options.PossibleFormats.Add(pf); } outputRecorder = new OutputRecorder (this.options, img => { try { var started = DateTime.Now; var rs = barcodeReader.Decode(img); var total = DateTime.Now - started; Console.WriteLine("Decode Time: " + total.TotalMilliseconds + " ms"); if (rs != null) resultCallback(rs); } catch (Exception ex) { Console.WriteLine("DECODE FAILED: " + ex); } }); output.AlwaysDiscardsLateVideoFrames = true; output.SetSampleBufferDelegate (outputRecorder, queue); Console.WriteLine("SetupCamera Finished"); session.AddOutput (output); //session.StartRunning (); if (captureDevice.IsFocusModeSupported(AVCaptureFocusMode.ModeContinuousAutoFocus)) { NSError err = null; if (captureDevice.LockForConfiguration(out err)) { captureDevice.FocusMode = AVCaptureFocusMode.ModeContinuousAutoFocus; if (captureDevice.FocusPointOfInterestSupported) captureDevice.FocusPointOfInterest = new PointF(0.5f, 0.5f); captureDevice.UnlockForConfiguration(); } else Console.WriteLine("Failed to Lock for Config: " + err.Description); } return true; }
/// <summary> /// Verify and create the authenticator if needed /// </summary> /// <returns>true is successful</returns> private bool verifyAuthenticator(string privatekey) { if (string.IsNullOrEmpty(privatekey)) { return(false); } Authenticator.Name = nameField.Text; var authtype = "totp"; // if this is a URL, pull it down Uri uri; Match match; if (Regex.IsMatch(privatekey, "https?://.*") && Uri.TryCreate(privatekey, UriKind.Absolute, out uri)) { try { var request = (HttpWebRequest)WebRequest.Create(uri); request.AllowAutoRedirect = true; request.Timeout = 20000; request.UserAgent = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; Trident/4.0)"; using (var response = (HttpWebResponse)request.GetResponse()) { if (response.StatusCode == HttpStatusCode.OK && response.ContentType.StartsWith("image/", StringComparison.OrdinalIgnoreCase)) { using (var bitmap = (Bitmap)Image.FromStream(response.GetResponseStream())) { IBarcodeReader reader = new BarcodeReader(); var result = reader.Decode(bitmap); if (result != null) { privatekey = HttpUtility.UrlDecode(result.Text); } } } } } catch (Exception ex) { WinAuthForm.ErrorDialog(Owner, "Cannot load QR code image from " + privatekey, ex); return(false); } } else if ((match = Regex.Match(privatekey, @"data:image/([^;]+);base64,(.*)", RegexOptions.IgnoreCase)) .Success) { var imagedata = Convert.FromBase64String(match.Groups[2].Value); using (var ms = new MemoryStream(imagedata)) { using (var bitmap = (Bitmap)Image.FromStream(ms)) { IBarcodeReader reader = new BarcodeReader(); var result = reader.Decode(bitmap); if (result != null) { privatekey = HttpUtility.UrlDecode(result.Text); } } } } else if (IsValidFile(privatekey)) { // assume this is the image file using (var bitmap = (Bitmap)Image.FromFile(privatekey)) { IBarcodeReader reader = new BarcodeReader(); var result = reader.Decode(bitmap); if (result != null) { privatekey = result.Text; } } } // check for otpauth://, e.g. "otpauth://totp/[email protected]?secret=IHZJDKAEEC774BMUK3GX6SA" match = Regex.Match(privatekey, @"otpauth://([^/]+)/([^?]+)\?(.*)", RegexOptions.IgnoreCase); if (match.Success) { authtype = match.Groups[1].Value; // @todo we only handle totp (not hotp) if (string.Compare(authtype, "totp", true) != 0) { WinAuthForm.ErrorDialog(Owner, "Only time-based (TOTP) authenticators are supported when adding a Google Authenticator. Use the general \"Add Authenticator\" for counter-based (HOTP) authenticators."); return(false); } var label = match.Groups[2].Value; if (string.IsNullOrEmpty(label) == false) { Authenticator.Name = nameField.Text = label; } var qs = WinAuthHelper.ParseQueryString(match.Groups[3].Value); privatekey = qs["secret"] ?? privatekey; } // just get the hex chars privatekey = Regex.Replace(privatekey, @"[^0-9a-z]", "", RegexOptions.IgnoreCase); if (privatekey.Length == 0) { WinAuthForm.ErrorDialog(Owner, "The secret code is not valid"); return(false); } try { var authenticator = new MicrosoftAuthenticator(); authenticator.Enroll(privatekey); Authenticator.AuthenticatorData = authenticator; Authenticator.Name = nameField.Text; codeField.Text = authenticator.CurrentCode; newAuthenticatorProgress.Visible = true; newAuthenticatorTimer.Enabled = true; } catch (Exception ex) { WinAuthForm.ErrorDialog(Owner, "Unable to create the authenticator: " + ex.Message, ex); return(false); } return(true); }
public void test_Random_Encoding_Decoding_Cycles_Up_To_1000() { int bigEnough = 256; byte[] data = new byte[256]; Random random = new Random(2344); for (int i = 0; i < 1000; i++) { random.NextBytes(data); //string content = "U/QcYPdz4MTR2nD2+vv88mZVnLA9/h+EGrEu3mwRIP65DlM6vLwlAwv/Ztd5LkHsio3UEJ29C1XUl0ZGRAFYv7pxPeyowjWqL5ilPZhICutvQlTePBBg+wP+ZiR2378Jp6YcB/FVRMdXKuAEGM29i41a1gKseYKpEEHpqlwRNE/Zm5bxKwL5Gv2NhxIvXOM1QNqWGwm9XC0jcvawbJprRfaRK3w3y2CKYbwEH/FwerRds2mBehhFHD5ozbgLSa1iIkIbnjBn/XV6DLpNuD08s/hCUrgx6crdSw89z/2nfxcOov2vVNuE9rbzB25e+GQBLBq/yfb1MTh3PlMhKS530w=="; string content = Convert.ToBase64String(data); BarcodeWriter writer = new BarcodeWriter { Format = BarcodeFormat.QR_CODE, Options = new EncodingOptions { Height = bigEnough, Width = bigEnough } }; Bitmap bmp = writer.Write(content); var reader = new BarcodeReader { Options = new DecodingOptions { PureBarcode = true, PossibleFormats = new List<BarcodeFormat> {BarcodeFormat.QR_CODE} } }; var decodedResult = reader.Decode(bmp); Assert.IsNotNull(decodedResult); Assert.AreEqual(content, decodedResult.Text); } }
private void timer_Tick(object sender, EventArgs e) { BarcodeReader Reader = new BarcodeReader(); Result result = Reader.Decode((Bitmap)pb_ScanQR.Image); try { decoded = result.ToString().Trim(); if (decoded != "") { timer.Stop(); MessageBox.Show("Success"); if (gikan == "book") { Book bk = new Book(decoded); bk.Show(); this.Close(); } else if (gikan == "index-borrow") { Borrow br = new Borrow(decoded, ""); br.Show(); this.Close(); } else if (gikan == "borrowform") { Borrow br = new Borrow(Z, decoded); br.Show(); this.Close(); } else if (gikan == "return") { //Return r = new Return(decoded); //r.Show(); //this.Close(); } else if (gikan == "borrower_bk") { Borrower br = new Borrower(decoded, "borrower_bk"); br.Show(); this.Close(); } else if (gikan == "borrower_brwr") { Borrower br = new Borrower(decoded, "borrower_brwr"); br.Show(); this.Close(); } else if (gikan == "userinfo") { UserInformation ui = new UserInformation(decoded); ui.Show(); this.Close(); } else if (gikan == "inactiveusers") { UnapprovedAccounts ua = new UnapprovedAccounts(decoded); ua.Show(); this.Close(); } else if (gikan == "attendance") { AttendanceMonitoring am = new AttendanceMonitoring(decoded); am.Show(); this.Close(); } else { MessageBox.Show("Invalid Destination"); } } } catch (Exception ex) { } }