private static string decodeBarcodeText(System.Drawing.Bitmap barcodeBitmap) { var source = new BitmapLuminanceSource(barcodeBitmap); // using http://zxingnet.codeplex.com/ // PM> Install-Package ZXing.Net var reader = new BarcodeReader(null, null, ls => new GlobalHistogramBinarizer(ls)) { AutoRotate = true, TryInverted = true, Options = new DecodingOptions { TryHarder = true, //PureBarcode = true, /*PossibleFormats = new List<BarcodeFormat> { BarcodeFormat.CODE_128 //BarcodeFormat.EAN_8, //BarcodeFormat.CODE_39, //BarcodeFormat.UPC_A }*/ } }; //var newhint = new KeyValuePair<DecodeHintType, object>(DecodeHintType.ALLOWED_EAN_EXTENSIONS, new Object()); //reader.Options.Hints.Add(newhint); var result = reader.Decode(source); if (result == null) { Console.WriteLine("Decode failed."); return string.Empty; } Console.WriteLine("BarcodeFormat: {0}", result.BarcodeFormat); Console.WriteLine("Result: {0}", result.Text); var writer = new BarcodeWriter { Format = result.BarcodeFormat, Options = { Width = 200, Height = 50, Margin = 4}, Renderer = new ZXing.Rendering.BitmapRenderer() }; var barcodeImage = writer.Write(result.Text); Cv2.ImShow("BarcodeWriter", barcodeImage.ToMat()); return result.Text; }
private Result decode(Uri uri, string originalInput, IDictionary<DecodeHintType, object> hints) { Bitmap image; try { image = (Bitmap) Bitmap.FromFile(uri.LocalPath); } catch (Exception) { throw new FileNotFoundException("Resource not found: " + uri); } using (image) { LuminanceSource source; if (config.Crop == null) { source = new BitmapLuminanceSource(image); } else { int[] crop = config.Crop; source = new BitmapLuminanceSource(image).crop(crop[0], crop[1], crop[2], crop[3]); } BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source)); if (config.DumpBlackPoint) { dumpBlackPoint(uri, image, bitmap, source); } Result result = new MultiFormatReader().decode(bitmap, hints); if (result != null) { if (config.Brief) { Console.Out.WriteLine(uri + ": Success"); } else { ParsedResult parsedResult = ResultParser.parseResult(result); var resultString = originalInput + " (format: " + result.BarcodeFormat + ", type: " + parsedResult.Type + "):" + Environment.NewLine; for (int i = 0; i < result.ResultPoints.Length; i++) { ResultPoint rp = result.ResultPoints[i]; Console.Out.WriteLine(" Point " + i + ": (" + rp.X + ',' + rp.Y + ')'); } resultString += "Raw result:" + Environment.NewLine + result.Text + Environment.NewLine; resultString += "Parsed result:" + Environment.NewLine + parsedResult.DisplayResult + Environment.NewLine; Console.Out.WriteLine(resultString); ResultString = resultString; } } else { var resultString = originalInput + ": No barcode found"; Console.Out.WriteLine(resultString); ResultString = resultString; } return result; } }
public bool DetectQRCode() { var qrReader = new QRCodeMultiReader(); var qrReaderHints = new Dictionary<DecodeHintType, object>() { { DecodeHintType.TRY_HARDER, true } }; var qrImageSource = new BitmapLuminanceSource((Bitmap)Image); var qrBinarizer = new HybridBinarizer(qrImageSource); var qrBinaryBitmap = new BinaryBitmap(qrBinarizer); try { qrCodeResult = qrReader.decodeMultiple(qrBinaryBitmap, qrReaderHints)?.FirstOrDefault(); qrCodeResultScale = 1F; } catch (ReaderException) { // QR Detection Failed qrCodeResult = null; } if (qrCodeResult == null) { var sizePoints = PdfiumDocument.PageSizes[PageIndex]; // Try at 175% using (var image = PdfiumDocument.Render(PageIndex, (int)(sizePoints.Width * 1.75), (int)(sizePoints.Height * 1.75), 72F, 72F, false)) { qrImageSource = new BitmapLuminanceSource((Bitmap)image); // Try Entire Image qrBinarizer = new HybridBinarizer(qrImageSource); qrBinaryBitmap = new BinaryBitmap(qrBinarizer); try { qrCodeResult = qrReader.decodeMultiple(qrBinaryBitmap, qrReaderHints)?.FirstOrDefault(); qrCodeResultScale = 1.75F; } catch (ReaderException) { // QR Detection Failed qrCodeResult = null; } } if (qrCodeResult == null) { // Try at 200% using (var image = PdfiumDocument.Render(PageIndex, (int)(sizePoints.Width * 2), (int)(sizePoints.Height * 2), 72F, 72F, false)) { qrImageSource = new BitmapLuminanceSource((Bitmap)image); // Try Entire Image qrBinarizer = new HybridBinarizer(qrImageSource); qrBinaryBitmap = new BinaryBitmap(qrBinarizer); try { qrCodeResult = qrReader.decodeMultiple(qrBinaryBitmap, qrReaderHints)?.FirstOrDefault(); qrCodeResultScale = 2F; } catch (ReaderException) { // QR Detection Failed qrCodeResult = null; } } } } if (qrCodeResult != null) { // Detect Rotation var rotationAngle = Math.Atan2( qrCodeResult.ResultPoints[2].Y - qrCodeResult.ResultPoints[1].Y, qrCodeResult.ResultPoints[2].X - qrCodeResult.ResultPoints[1].X) * 180 / Math.PI; if (rotationAngle <= 45 || rotationAngle > 315) { detectedRotation = RotateFlipType.RotateNoneFlipNone; } else if (rotationAngle <= 135) { detectedRotation = RotateFlipType.Rotate270FlipNone; } else if (rotationAngle <= 225) { detectedRotation = RotateFlipType.Rotate180FlipNone; } else { detectedRotation = RotateFlipType.Rotate90FlipNone; } // Reset Thumbnail if (renderedThumbnail != null) { renderedThumbnail.Dispose(); renderedThumbnail = null; } // Try binary encoding (from v2) if (qrCodeResult.ResultMetadata.ContainsKey(ResultMetadataType.BYTE_SEGMENTS)) { var byteSegments = (List<byte[]>)qrCodeResult.ResultMetadata[ResultMetadataType.BYTE_SEGMENTS]; var qrBytes = byteSegments[0]; if (DocumentUniqueIdentifier.IsDocumentUniqueIdentifier(qrBytes)) { Identifier = DocumentUniqueIdentifier.Parse(Database, qrBytes); } } // Fall back to v1 if (Identifier == null) { Identifier = DocumentUniqueIdentifier.Parse(Database, qrCodeResult.Text); } return true; } return false; }
private void ScanQRCodeItem_Click(object sender, EventArgs e) { foreach (Screen screen in Screen.AllScreens) { using (Bitmap fullImage = new Bitmap(screen.Bounds.Width, screen.Bounds.Height)) { using (Graphics g = Graphics.FromImage(fullImage)) { g.CopyFromScreen(screen.Bounds.X, screen.Bounds.Y, 0, 0, fullImage.Size, CopyPixelOperation.SourceCopy); } int maxTry = 10; for (int i = 0; i < maxTry; i++) { int marginLeft = (int)((double)fullImage.Width * i / 2.5 / maxTry); int marginTop = (int)((double)fullImage.Height * i / 2.5 / maxTry); Rectangle cropRect = new Rectangle(marginLeft, marginTop, fullImage.Width - marginLeft * 2, fullImage.Height - marginTop * 2); Bitmap target = new Bitmap(screen.Bounds.Width, screen.Bounds.Height); double imageScale = (double)screen.Bounds.Width / (double)cropRect.Width; using (Graphics g = Graphics.FromImage(target)) { g.DrawImage(fullImage, new Rectangle(0, 0, target.Width, target.Height), cropRect, GraphicsUnit.Pixel); } var source = new BitmapLuminanceSource(target); var bitmap = new BinaryBitmap(new HybridBinarizer(source)); QRCodeReader reader = new QRCodeReader(); var result = reader.decode(bitmap); if (result != null) { var success = controller.AddServerBySSURL(result.Text); QRCodeSplashForm splash = new QRCodeSplashForm(); if (success) { splash.FormClosed += splash_FormClosed; } else if (result.Text.StartsWith("http://") || result.Text.StartsWith("https://")) { _urlToOpen = result.Text; splash.FormClosed += openURLFromQRCode; } else { MessageBox.Show(I18N.GetString("Failed to decode QRCode")); return; } double minX = Int32.MaxValue, minY = Int32.MaxValue, maxX = 0, maxY = 0; foreach (ResultPoint point in result.ResultPoints) { minX = Math.Min(minX, point.X); minY = Math.Min(minY, point.Y); maxX = Math.Max(maxX, point.X); maxY = Math.Max(maxY, point.Y); } minX /= imageScale; minY /= imageScale; maxX /= imageScale; maxY /= imageScale; // make it 20% larger double margin = (maxX - minX) * 0.20f; minX += -margin + marginLeft; maxX += margin + marginLeft; minY += -margin + marginTop; maxY += margin + marginTop; splash.Location = new Point(screen.Bounds.X, screen.Bounds.Y); // we need a panel because a window has a minimal size // TODO: test on high DPI splash.TargetRect = new Rectangle((int)minX + screen.Bounds.X, (int)minY + screen.Bounds.Y, (int)maxX - (int)minX, (int)maxY - (int)minY); splash.Size = new Size(fullImage.Width, fullImage.Height); splash.Show(); return; } } } } MessageBox.Show(I18N.GetString("No QRCode found. Try to zoom in or move it to the center of the screen.")); }
/// <summary> /// Найти штрихкод code128 и его ограничивающий п/у /// </summary> /// <param name="fileName">Имя файла с картинкой png, jpeg</param> public static BarcodeResult ScanCode128(Image img, string debugFileName = null) { BarcodeResult barcodeResult = null; Bitmap bmp = new Bitmap(img); // create a barcode reader instance var reader = new BarcodeReader(); reader.Options.ReturnCodabarStartEnd = true; reader.Options.TryHarder = true; reader.Options.PossibleFormats = new BarcodeFormat[] { BarcodeFormat.CODE_128 }; reader.AutoRotate = true; // Сейчас код ищет только один штрихкод. // Найти несколько штрихкодов можно с помощью метода DecodeMultiple, но по умолчанию возвращаются только разные штрихкоды. // Если мы хотим получить положение одного и того же штрихкода вставленного несколько раз, то нужно будет переписывать метод DecodeMultiple. // Есть ещё проблема с разноповернутыми штрихкодами если их несколько, то распознаются только однонаправленные, // возможно стоит вручную поворачивать и перезапускать алгоритм. // int scannerOrientation = 0; var result = reader.Decode(bmp); if (result != null) { barcodeResult = new BarcodeResult(); barcodeResult.Code = result.Text; barcodeResult.Type = BarcodeType.ToString(result.BarcodeFormat); try { var orient = result.ResultMetadata[ResultMetadataType.ORIENTATION]; scannerOrientation = (int)orient; // only vertical/horizontal } catch (Exception /*ex*/) { } if (result.ResultPoints.Length >= 2) { // var luminanceSource = new ZXing.BitmapLuminanceSource(bmp); var binarizer = new ZXing.Common.HybridBinarizer(luminanceSource); var bitMatrix = binarizer.BlackMatrix; // result.ResultPoints - точкии линии сканера, для которой был распознан штрих код // для barcode128 эти точки находятся внутри штрихкода видимо за start и stop элементами. // нам нужно получить по этим точкам ограничивающий п/у для всего штрихкода // но это точки в координатах повернутого листа на scannerOrientation градусов, // поэтому преобразуем их в начальную и конечную координату сканера в координатак картинки img Point[] scanLine = GetScanLine(result.ResultPoints, scannerOrientation, img.Width, img.Height, bitMatrix); // Возьмем конечную точку скан линии int x = scanLine[1].X; int y = scanLine[1].Y; // Вычислим магический белый квадрат - предположительное место штрихкода. // Искать будет с точки x,y, возвращает 4 точки, типа ограничивающего штрих код белую п/у. // Использующийся алгоритм не до конца понятен, возвращает п/у содержащий одну, несколько полосок, или весь штрих код. // Поэтому единственная полезная информация которая может быть извлечена высота штрихкода (координаты одной вертикальной полосы) var whiterectDetector = ZXing.Common.Detector.WhiteRectangleDetector.Create(bitMatrix, 1, x, y); var whiteRect = whiterectDetector.detect(); if (whiteRect == null) { return(barcodeResult); // не удалось вычислить ограничивающий п/у. } // Посчитаем длину первой черной полоски после правой конечной точки scan линии. int blackLineWidth = CalcBlackLineWidth(bitMatrix, scanLine); // Вычислим по имеющимся данным ограничивающий п/у для штрихкода int dx = blackLineWidth * 3; // 3 полоски по бокам добавим (для 128 баркода) ResultPoint[] barcodeRect = GetBarCodeRect(scanLine, whiteRect, dx); // Вычислим п/у для создания штрихкода и его ориентацию(поворот). // (п/у без поворота, от левой нижней точки и его угол поворота в градусах) //barcodeResult.Left = (int)barcodeRect[1].X; //barcodeResult.Bottom = (int)barcodeRect[1].Y; //barcodeResult.Right = barcodeResult.Left + (int)ResultPoint.distance(barcodeRect[0], barcodeRect[2]); //barcodeResult.Top = barcodeResult.Bottom - (int)ResultPoint.distance(barcodeRect[0], barcodeRect[1]); barcodeResult.Left = (int)barcodeRect[0].X; barcodeResult.Top = (int)barcodeRect[0].Y; barcodeResult.Right = barcodeResult.Left + (int)ResultPoint.distance(barcodeRect[0], barcodeRect[2]); barcodeResult.Bottom = barcodeResult.Top + (int)ResultPoint.distance(barcodeRect[0], barcodeRect[1]); /* } * else if (scannerOrientation == 180) * { * barcodeResult.Left = (int)barcodeRect[0].X; * barcodeResult.Bottom = (int)barcodeRect[0].Y; * barcodeResult.Right = barcodeResult.Left + (int)ResultPoint.distance(barcodeRect[0], barcodeRect[2]); * barcodeResult.Top = barcodeResult.Bottom - (int)ResultPoint.distance(barcodeRect[0], barcodeRect[1]); * }*/ //barcodeResult.Orientation = -Orientation(barcodeRect[0], barcodeRect[2]); barcodeResult.Orientation = Orientation(barcodeRect[0], barcodeRect[2]); if (!string.IsNullOrEmpty(debugFileName)) { // Закрасим область белым, чтобы можно было ещё искать barcode var g = Graphics.FromImage(img); g.FillPolygon(new SolidBrush(Color.Pink), ToDrawingRect(barcodeRect)); DebugSaveImage(debugFileName, img, barcodeRect, whiteRect, scanLine); } } } return(barcodeResult); }
/// <summary> /// uses the IBarcodeReaderGeneric implementation and the <see cref="BitmapLuminanceSource"/> class for decoding /// </summary> /// <param name="reader"></param> /// <param name="image"></param> /// <returns></returns> public static Result[] DecodeMultiple(this IBarcodeReaderGeneric reader, Bitmap image) { var luminanceSource = new BitmapLuminanceSource(image); return(reader.DecodeMultiple(luminanceSource)); }
public IndexModule() { Get["/"] = parameters => { return View["index"]; }; Get["/upload"] = parameters => { return View["upload"]; }; Get["/certificate"] = parameters => { return View["cert"]; }; Get["/result"] = parameters => { string enhancedQRCodePath = Path.Combine("data", "qrdata") + @"\" + "EnhancedqrImage.bmp"; Bitmap QRcodeImage = new Bitmap(Bitmap.FromFile(enhancedQRCodePath)); Rectangle cropArea = new Rectangle(); cropArea.Width = 357; cropArea.Height = 392; cropArea.X = (QRcodeImage.Width - cropArea.Width) / 2; cropArea.Y = (QRcodeImage.Height - cropArea.Height) / 2; Bitmap bmpCrop = QRcodeImage.Clone(cropArea, QRcodeImage.PixelFormat); string rawFPImage = Path.Combine("data", "qrdata") + @"\" + "fingerprint.bmp"; bmpCrop.Save(rawFPImage); LuminanceSource source = new BitmapLuminanceSource(QRcodeImage); BinaryBitmap newbitmap = new BinaryBitmap(new HybridBinarizer(source)); Result result = new MultiFormatReader().decodeWithState(newbitmap); if (result.Text != requestTime) { return Response.AsJson(new { Result = "Authentication failure" }); } else { //Write your code here!(next time!) //return Response.AsJson(new { Result = result.Text }); } return Response.AsImage(rawFPImage); }; Get["/securityUpload"] = parameters => { return View["secert"]; }; Post["/severification"] = parameters => { var file = this.Request.Files.ElementAt<HttpFile>(0); string uploadPath = Path.Combine("data", "test", file.Name); if (!Directory.Exists(Path.Combine("data", "test"))) Directory.CreateDirectory(Path.Combine("data", "test")); using (var fileStream = new FileStream(uploadPath, FileMode.Create)) { file.Value.CopyTo(fileStream); } string QRcodePath = Path.Combine("data", "qrdata") + @"\" + "qrImage.bmp"; Bitmap fpImage = new Bitmap(Bitmap.FromFile(uploadPath)); Bitmap RawQRImage = new Bitmap(Bitmap.FromFile(QRcodePath)); Bitmap QRImage = new Bitmap(RawQRImage.Width, RawQRImage.Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb); using (Graphics g = Graphics.FromImage(QRImage)) { g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality; g.DrawImage(RawQRImage, 0, 0); } int middleImgW = Math.Min((int)(realSize.Width / 3.5), fpImage.Width); int middleImgH = Math.Min((int)(realSize.Height / 3.5), fpImage.Height); int middleImgL = (QRImage.Width - middleImgW) / 2; int middleImgT = (QRImage.Height - middleImgH) / 2; System.Drawing.Graphics MyGraphic = System.Drawing.Graphics.FromImage(QRImage); MyGraphic.FillRectangle(Brushes.White, middleImgL, middleImgT, middleImgW, middleImgH); MyGraphic.DrawImage(fpImage, middleImgL, middleImgT, middleImgW, middleImgH); string enhancedQRCodePath = Path.Combine("data", "qrdata") + @"\" + "EnhancedqrImage.bmp"; QRImage.Save(enhancedQRCodePath); return Response.AsImage(enhancedQRCodePath); }; Get["/barcode"] = parameters => { BarcodeWriter writer = new BarcodeWriter(); writer.Format = BarcodeFormat.QR_CODE; writer.Options = new QrCodeEncodingOptions { DisableECI = true, CharacterSet = "UTF-8", Width = 1840, Height = 1840, ErrorCorrection = ErrorCorrectionLevel.H }; requestTime = DateTime.Now.ToString(); Bitmap qrImage = writer.Write(requestTime); string path = Path.Combine("data", "qrdata"); if (!Directory.Exists(path)) Directory.CreateDirectory(path); string imagePath = path + @"\" + "qrImage.bmp"; qrImage.Save(imagePath); return Response.AsImage(imagePath); }; Post["/verification"] = parameters => { string userId = (string)this.Request.Form.userId; List<Model.Fingerprint> fingerprints = SqlHelper.getImages(userId); var file = this.Request.Files.ElementAt<HttpFile>(0); string uploadPath = Path.Combine("data", "test", file.Name); if (!Directory.Exists(Path.Combine("data", "test"))) Directory.CreateDirectory(Path.Combine("data", "test")); using (var fileStream = new FileStream(uploadPath, FileMode.Create)) { file.Value.CopyTo(fileStream); } SourceAFIS.Simple.Fingerprint fp1 = new SourceAFIS.Simple.Fingerprint(); fp1.AsBitmap = new Bitmap(Bitmap.FromFile(uploadPath)); Person person1 = new Person(); person1.Fingerprints.Add(fp1); Afis.Extract(person1); List<MatchResult> results = new List<MatchResult>(); foreach (var fp in fingerprints) { SourceAFIS.Simple.Fingerprint fp2 = new SourceAFIS.Simple.Fingerprint(); fp2.AsBitmap = new Bitmap(Bitmap.FromFile(fp.fpPath)); Person person2 = new Person(); person2.Fingerprints.Add(fp2); Afis.Extract(person2); MatchResult result = new MatchResult(); result.fingerprint = fp.fpName + fp.sampleNumber.ToString(); result.score = Afis.Verify(person1, person2); results.Add(result); } return Response.AsJson<List<MatchResult>>(results); }; Post["/upload"] = parameters => { User user = new User(); Model.Fingerprint fp1 = new Model.Fingerprint(); Model.Fingerprint fp2 = new Model.Fingerprint(); Model.Fingerprint fp3 = new Model.Fingerprint(); Model.Fingerprint fp4 = new Model.Fingerprint(); Model.Fingerprint fp5 = new Model.Fingerprint(); user.userId = (string)this.Request.Form.id; user.userName = (string)this.Request.Form.name; fp1.fpName = (string)this.Request.Form.fpname1; fp2.fpName = (string)this.Request.Form.fpname2; fp3.fpName = (string)this.Request.Form.fpname3; fp4.fpName = (string)this.Request.Form.fpname4; fp5.fpName = (string)this.Request.Form.fpname5; fp1.sampleNumber = (int)this.Request.Form.samplenumber1; fp2.sampleNumber = (int)this.Request.Form.samplenumber2; fp3.sampleNumber = (int)this.Request.Form.samplenumber3; fp4.sampleNumber = (int)this.Request.Form.samplenumber4; fp5.sampleNumber = (int)this.Request.Form.samplenumber5; fp1.userID = user.userId; fp2.userID = user.userId; fp3.userID = user.userId; fp4.userID = user.userId; fp5.userID = user.userId; fp1.fpID = fp1.userID + fp1.fpName + fp1.sampleNumber.ToString(); fp2.fpID = fp1.userID + fp2.fpName + fp2.sampleNumber.ToString(); fp3.fpID = fp3.userID + fp3.fpName + fp3.sampleNumber.ToString(); fp4.fpID = fp4.userID + fp4.fpName + fp4.sampleNumber.ToString(); fp5.fpID = fp5.userID + fp5.fpName + fp5.sampleNumber.ToString(); var file1 = this.Request.Files.ElementAt<HttpFile>(0); var file2 = this.Request.Files.ElementAt<HttpFile>(1); var file3 = this.Request.Files.ElementAt<HttpFile>(2); var file4 = this.Request.Files.ElementAt<HttpFile>(3); var file5 = this.Request.Files.ElementAt<HttpFile>(4); fp1.fpPath = @"data\" + user.userName + @"\" + fp1.fpID + file1.Name.Substring(file1.Name.Length -4, 4); fp2.fpPath = @"data\" + user.userName + @"\" + fp2.fpID + file2.Name.Substring(file2.Name.Length - 4, 4); fp3.fpPath = @"data\" + user.userName + @"\" + fp3.fpID + file3.Name.Substring(file3.Name.Length - 4, 4); fp4.fpPath = @"data\" + user.userName + @"\" + fp4.fpID + file4.Name.Substring(file4.Name.Length - 4, 4); fp5.fpPath = @"data\" + user.userName + @"\" + fp5.fpID + file5.Name.Substring(file5.Name.Length - 4, 4); //fp1.fpPath = Path.Combine("data", user.userName, fp1.fpID + file1.Name.Substring(file1.Name.Length - 4, 4)); if (!Directory.Exists(Path.Combine("data", user.userName))) Directory.CreateDirectory(Path.Combine("data", user.userName)); using (var fileStream = new FileStream(fp1.fpPath, FileMode.Create)) { file1.Value.CopyTo(fileStream); } using (var fileStream = new FileStream(fp2.fpPath, FileMode.Create)) { file2.Value.CopyTo(fileStream); } using (var fileStream = new FileStream(fp3.fpPath, FileMode.Create)) { file3.Value.CopyTo(fileStream); } using (var fileStream = new FileStream(fp4.fpPath, FileMode.Create)) { file4.Value.CopyTo(fileStream); } using (var fileStream = new FileStream(fp5.fpPath, FileMode.Create)) { file5.Value.CopyTo(fileStream); } if (!SqlHelper.isExistUser(user)) SqlHelper.insertToUser(user); int i1 = SqlHelper.insertToFingerprint(fp1); int i2 = SqlHelper.insertToFingerprint(fp2); int i3 = SqlHelper.insertToFingerprint(fp3); int i4 = SqlHelper.insertToFingerprint(fp4); int i5 = SqlHelper.insertToFingerprint(fp5); if (i1!=0 && i2!=0 && i3!=0 && i4!=0 && i5!=0) return Response.AsJson(new { Result = "Insert Sucess" }); else return Response.AsJson(new { Result = "Insert Failed" }); }; Get["/getUser"] = parameters => { string myconn = "Database='fingerprint';Data Source=localhost;User ID=lich;Password=123456;CharSet=utf8;"; string mysql = "SELECT * from user"; MySqlConnection myconnection = new MySqlConnection(myconn); myconnection.Open(); MySqlCommand mycommand = new MySqlCommand(mysql, myconnection); MySqlDataReader myreader = mycommand.ExecuteReader(); List<User> userList = new List<User>(); while (myreader.Read()) { User user = new User(); user.userId = myreader.GetString(0); user.userName = myreader.GetString(1); userList.Add(user); } myreader.Close(); myconnection.Close(); return Response.AsJson<List<User>>(userList); }; Get["/inserttest"] = parameters => { User user = new User(); user.userId = "13T2001"; user.userName = "******"; int i = SqlHelper.insertToUser(user); if (i != 0) return Response.AsJson(new { Result = "Insert Sucess" }); else return Response.AsJson(new { Result = "Insert Failed" }); }; }
private Result[] decodeMulti(Uri uri, IDictionary<DecodeHintType, object> hints) { Bitmap image; try { image = (Bitmap)Bitmap.FromFile(uri.LocalPath); } catch (Exception) { throw new FileNotFoundException("Resource not found: " + uri); } LuminanceSource source; if (config.Crop == null) { source = new BitmapLuminanceSource(image); } else { int[] crop = config.Crop; source = new BitmapLuminanceSource(image).crop(crop[0], crop[1], crop[2], crop[3]); } BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source)); if (config.DumpBlackPoint) { dumpBlackPoint(uri, image, bitmap); } MultiFormatReader multiFormatReader = new MultiFormatReader(); GenericMultipleBarcodeReader reader = new GenericMultipleBarcodeReader( multiFormatReader); Result[] results = reader.decodeMultiple(bitmap, hints); if (results != null && results.Length > 0) { if (config.Brief) { Console.Out.WriteLine(uri + ": Success"); } else { foreach (var result in results) { ParsedResult parsedResult = ResultParser.parseResult(result); Console.Out.WriteLine(uri + " (format: " + result.BarcodeFormat + ", type: " + parsedResult.Type + "):\nRaw result:\n" + result.Text + "\nParsed result:\n" + parsedResult.DisplayResult); Console.Out.WriteLine("Found " + result.ResultPoints.Length + " result points."); for (int i = 0; i < result.ResultPoints.Length; i++) { ResultPoint rp = result.ResultPoints[i]; Console.Out.WriteLine(" Point " + i + ": (" + rp.X + ',' + rp.Y + ')'); } } } return results; } else { Console.Out.WriteLine(uri + ": No barcode found"); } return null; }
private Result decode(Uri uri, Bitmap image, string originalInput, IDictionary<DecodeHintType, object> hints) { LuminanceSource source; if (config.Crop == null) { source = new BitmapLuminanceSource(image); } else { int[] crop = config.Crop; source = new BitmapLuminanceSource(image).crop(crop[0], crop[1], crop[2], crop[3]); } if (config.DumpBlackPoint) { BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source)); dumpBlackPoint(uri, image, bitmap, source); } var reader = new BarcodeReader {AutoRotate = config.AutoRotate}; foreach (var entry in hints) reader.Options.Hints.Add(entry.Key, entry.Value); Result result = reader.Decode(source); if (result != null) { if (config.Brief) { Console.Out.WriteLine(uri + ": Success"); } else { ParsedResult parsedResult = ResultParser.parseResult(result); var resultString = originalInput + " (format: " + result.BarcodeFormat + ", type: " + parsedResult.Type + "):" + Environment.NewLine; for (int i = 0; i < result.ResultPoints.Length; i++) { ResultPoint rp = result.ResultPoints[i]; Console.Out.WriteLine(" Point " + i + ": (" + rp.X + ',' + rp.Y + ')'); } resultString += "Raw result:" + Environment.NewLine + result.Text + Environment.NewLine; resultString += "Parsed result:" + Environment.NewLine + parsedResult.DisplayResult + Environment.NewLine; Console.Out.WriteLine(resultString); ResultString = resultString; } } else { var resultString = originalInput + ": No barcode found"; Console.Out.WriteLine(resultString); ResultString = resultString; } return result; }
private void btnSave_Click(object sender, EventArgs e) { var reader = new MultiFormatReader(); var img = (Bitmap)Bitmap.FromFile(pictureBox1.ImageLocation); BitmapLuminanceSource ls = new BitmapLuminanceSource(img); var binarizer = new HybridBinarizer(ls); BinaryBitmap binaryBitmap = new BinaryBitmap(binarizer); var result = reader.decode(binaryBitmap); richTextBox1.Text = result.Text.Trim(); }
public static String MultiDecode(Bitmap bitmap) { // convert if (bitmap == null) { return null; } LuminanceSource luminanceSource = new BitmapLuminanceSource(bitmap); BinaryBitmap binaryBitmap = new BinaryBitmap(new HybridBinarizer(luminanceSource)); // decode ZXing.Result result = (new MultiFormatReader()).decode(binaryBitmap); if (result == null) { return null; } String text = result.Text; return text; }