public RGBLuminanceSource(byte[] d, int W, int H, RGBLuminanceSource.BitmapFormat format) : base(W, H) { __width = W; __height = H; int width = W; int height = H; // In order to measure pure decoding speed, we convert the entire image to a greyscale array // up front, which is the same as the Y channel of the YUVLuminanceSource in the real app. luminances = new byte[width * height]; for (int y = 0; y < height; y++) { int offset = y * width; for (int x = 0; x < width; x++) { int b = d[offset * 4 + x * 4]; int g = d[offset * 4 + x * 4 + 1]; int r = d[offset * 4 + x * 4 + 2]; if (r == g && g == b) { // Image is already greyscale, so pick any channel. luminances[offset + x] = (byte)r; } else { // Calculate luminance cheaply, favoring green. luminances[offset + x] = (byte)((r + g + g + b) >> 2); } } } }
private static void imageWorker_DoWork(object sender, DoWorkEventArgs e) { // scanning for a barcode var wbmp = (WriteableBitmap)e.Argument; var luminiance = new RGBLuminanceSource(wbmp, wbmp.PixelWidth, wbmp.PixelHeight); var binarizer = new HybridBinarizer(luminiance); var binBitmap = new BinaryBitmap(binarizer); var reader = new MultiFormatReader(); e.Result = reader.decode(binBitmap); }
/// <summary> /// برسی وجود کد QR در تصویر /// </summary> /// <param name="bitmapByteArray">تصویر مورد نظر در قالب آرایه ای از <c>byte</c></param> /// <param name="width">عرض تصویر به پیکسل</param> /// <param name="height">طور تصویر به پیکسل</param> /// <returns>نتیجه برسی</returns> public bool ContainsQRCode(byte[] bitmapByteArray, int width, int height) { ///[Checking picture for QR Code] ZXing.LuminanceSource source = new ZXing.RGBLuminanceSource(bitmapByteArray, width, height); ZXing.Common.HybridBinarizer binarizer = new ZXing.Common.HybridBinarizer(source); ZXing.BinaryBitmap binBitmap = new ZXing.BinaryBitmap(binarizer); ZXing.Common.BitMatrix bitMatrix = binBitmap.BlackMatrix; ZXing.Multi.QrCode.Internal.MultiDetector detector = new ZXing.Multi.QrCode.Internal.MultiDetector(bitMatrix); return(detector.detect() != null); ///[Checking picture for QR Code] }
// Source: http://www.codeproject.com/Questions/441372/zxing-QRCode-Encoding-and-Decoding-in-csharp private String qrReader(Bitmap image) { byte[] byteImage = ImageToByte(image); try { ZXing.LuminanceSource source = new ZXing.RGBLuminanceSource(byteImage, image.Width, image.Height); var binarizer = new HybridBinarizer(source); var binBitmap = new BinaryBitmap(binarizer); return(reader.decode(binBitmap).Text); } catch { return(string.Empty); } }
public Dictionary <string, ResultPoint[]> findQrCodeText(Reader decoder, Bitmap bitmap) { var rgb = new ZXing.RGBLuminanceSource(GetRGBValues(bitmap), bitmap.Width, bitmap.Height); var hybrid = new HybridBinarizer(rgb); BinaryBitmap binBitmap = new BinaryBitmap(hybrid); Dictionary <string, ResultPoint[]> decodedString = new Dictionary <string, ResultPoint[]>(); Result res = decoder.decode(binBitmap, null); if (res != null) { decodedString.Add(res.Text, res.ResultPoints); } return(decodedString); }
//Interesting method //public static string decodeQRImage(string path) //{ // Bitmap bMap = BitmapFactory.DecodeFile(path); // string decoded = null; // int[] intArray = new int[bMap.Width * bMap.Height]; // Java.IO.InputStream ist = getResources().openRawResource(R.drawable.balloons); // byte[] data = new byte[ist.Available()]; // bMap.GetPixels(intArray, 0, bMap.Width, 0, 0, bMap.Width, bMap.Height); // LuminanceSource source = new RGBLuminanceSource(data, bMap.Width, bMap.Height); // BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source)); // Reader reader = new QRCodeReader(); // ZXing.Result result = reader.decode(bitmap); // decoded = result.Text; // return decoded; //} // Something I am trying to get image scanning private void ReadBarcode() { try { var imageBytes = GetImage("file:///android_asset/QR_Code_Test.jpg"); var width = GetWidth("file:///android_asset/QR_Code_Test.jpg"); var height = GetHeight("file:///android_asset/QR_Code_Test.jpg"); LuminanceSource source = new ZXing.RGBLuminanceSource(imageBytes, (int)width, (int)height); HybridBinarizer hb = new HybridBinarizer(source); var a = hb.createBinarizer(source); BinaryBitmap bBitmap = new BinaryBitmap(a); BarcodeReader reader = new BarcodeReader(); reader.Options.TryHarder = true; MultiFormatReader reader1 = new MultiFormatReader(); try { var r = reader1.decodeWithState(bBitmap); var result = reader.Decode(source); var result2 = reader.DecodeMultiple(source); if (result != null) { return; } return; } catch (Java.Lang.Exception ex) { //HandleError("ReadBarcode Error: ", ex.Message); } } catch (Java.Lang.Exception ex) { //HandleError("ReadBarcode Error: ", ex.Message); } }
private async Task<Result> DetectBarcodeAsync() { var width = (int)PreviewResolution.Width; var height = (int)PreviewResolution.Height; var rotation = PhotoCaptureDevice.SensorRotationInDegrees; LuminanceSource luminanceSource = null; PhotoCaptureDevice.GetPreviewBufferY(_previewBuffer); luminanceSource = new RGBLuminanceSource(_previewBuffer, width, height, RGBLuminanceSource.BitmapFormat.Gray8); var result = _barcodeReader.Decode(luminanceSource); if (result == null) { // ok, one try with rotation by 90 degrees if ((Orientation & PageOrientation.Portrait) == PageOrientation.Portrait) { // if we are in potrait orientation it's better to rotate clockwise // to get it in the right direction luminanceSource = new RGBLuminanceSource(RotateClockwise(_previewBuffer, width, height), height, width, RGBLuminanceSource.BitmapFormat.Gray8); } else { // in landscape we try counter clockwise until we know it better luminanceSource = luminanceSource.rotateCounterClockwise(); } result = _barcodeReader.Decode(luminanceSource); } return result; }
public Result Decode(byte[] rawRGB, int width, int height, RGBLuminanceSource.BitmapFormat format) { throw new NotImplementedException(); }
private void Worker() { if(_multiFormatReader == null) { _multiFormatReader = this.Options.BuildMultiFormatReader(); //_multiFormatReader = new MultiFormatReader { // Hints = new Hashtable { // { DecodeHintType.POSSIBLE_FORMATS, new ArrayList { // BarcodeFormat.UPC_A, BarcodeFormat.UPC_E , BarcodeFormat.CODE_128, // BarcodeFormat.CODE_39, BarcodeFormat.EAN_13, BarcodeFormat.EAN_8 // } } // } // }; } if (wasStopped) return; using (var ap = new NSAutoreleasePool()) { try { // Capturing screen image using (var screenImage = CGImage.ScreenImage.WithImageInRect(picFrame)) //.WithImageInRect(picFrame)) { using (var _theScreenImage = UIImage.FromImage(screenImage)) using (var srcbitmap = new Bitmap(_theScreenImage)) { LuminanceSource source = null; BinaryBitmap bitmap = null; try { //Console.WriteLine(screenImage.Width.ToString() + " x " + screenImage.Height.ToString()); //var cropY = (int)((screenImage.Height * 0.4) / 2); source = new RGBLuminanceSource(srcbitmap, screenImage.Width, screenImage.Height); //.crop(0, cropY, 0, screenImage.Height - cropY - cropY); //Console.WriteLine(source.Width + " x " + source.Height); bitmap = new BinaryBitmap(new HybridBinarizer(source)); try { var result = _multiFormatReader.decodeWithState(bitmap); // //var result = _multiFormatReader.decodeWithState (bitmap); //srcbitmap.Dispose(); if(result != null && result.Text!=null) { //BeepOrVibrate(); _parentViewController.BarCodeScanned(result); } } catch (ReaderException) { } /* com.google.zxing.common.BitArray row = new com.google.zxing.common.BitArray(screenImage.Width); int middle = screenImage.Height >> 1; int rowStep = System.Math.Max(1, screenImage.Height >> (4)); for (int x = 0; x < 9; x++) { // Scanning from the middle out. Determine which row we're looking at next: int rowStepsAboveOrBelow = (x + 1) >> 1; bool isAbove = (x & 0x01) == 0; // i.e. is x even? int rowNumber = middle + rowStep * (isAbove?rowStepsAboveOrBelow:- rowStepsAboveOrBelow); if (rowNumber < 0 || rowNumber >= screenImage.Height) { // Oops, if we run off the top or bottom, stop break; } // Estimate black point for this row and load it: try { row = bitmap.getBlackRow(rowNumber, row); var resultb = _multiFormatReader.decodeRow(rowNumber, row, hints); if(resultb.Text!=null) { Console.WriteLine("SCANNED"); BeepOrVibrate(); _parentViewController.BarCodeScanned(resultb); break; } else { continue; } } catch (ReaderException re) { continue; } } */ // var result = _barcodeReader.decodeWithState(bitmap); // // if(result.Text!=null) // { // _multiFormatOneDReader = null; // BeepOrVibrate(); // _parentViewController.BarCodeScanned(result); // } } catch (Exception ex) { Console.WriteLine(ex.Message); } finally { if(bitmap!=null) bitmap = null; if(source!=null) source = null; // if(srcbitmap!=null) // srcbitmap = null; //if (_theScreenImage != null) // _theScreenImage = null; } } } } catch { } } GC.Collect(); //Console.WriteLine("Done."); }
public void CheckBarCode() { try { using(var bbImage = new System.Drawing.Bitmap (codeImage)){ Reader barReader = new ZXing.QrCode.QRCodeReader(); //Reader barReader = new MultiFormatReader (); LuminanceSource source = new RGBLuminanceSource (bbImage, (int)codeImage.Size.Width, (int)codeImage.Size.Height); BinaryBitmap bb = new BinaryBitmap (new HybridBinarizer (source)); Result res = barReader.decode (bb); InvokeOnMainThread (() => { codeImage.Dispose(); if (res != null) { //result has the string from the image //AppDelegate.main.decryptVC.txtScanResult.Text = res.Text; AppDelegate.main.decryptVC.ProcessScannedCode(res.Text); } else { //no valid code found; } numRuns++; barChecking = false; }); } } catch (Exception e) { barChecking = false; Console.WriteLine (e); } }
public override void DidOutputSampleBuffer (AVCaptureOutput captureOutput, CMSampleBuffer sampleBuffer, AVCaptureConnection connection) { try { if (!gotResult) { LuminanceSource luminance; //connection.VideoOrientation = AVCaptureVideoOrientation.Portrait; using (var pixelBuffer = sampleBuffer.GetImageBuffer () as CVPixelBuffer) { if (bytes == null) bytes = new byte [pixelBuffer.Height * pixelBuffer.BytesPerRow]; pixelBuffer.Lock (0); Marshal.Copy (pixelBuffer.BaseAddress, bytes, 0, bytes.Length); luminance = new RGBLuminanceSource (bytes, pixelBuffer.Width, pixelBuffer.Height); pixelBuffer.Unlock (0); } var binarized = new BinaryBitmap (new HybridBinarizer (luminance)); var result = reader.decodeWithState (binarized); //parent.session.StopRunning (); gotResult = true; if (parent.Scan != null) parent.Scan (result); } } catch (ReaderException) { // ignore this exception; it happens every time there is a failed scan } catch (Exception e) { // TODO: this one is unexpected.. log or otherwise handle it throw; } finally { try { // lamest thing, but seems that this throws :( sampleBuffer.Dispose (); } catch { } } }
/// <summary> /// 读取二维码信息 /// </summary> /// <param name="strBarcodeImgPath">二维码的存放路径</param> /// <returns>二维码信息</returns> public static string ReadBarcode(string strBarcodeImgPath) { var img = Image.FromFile(strBarcodeImgPath); var bmap = new Bitmap(img); var ms = new MemoryStream(); bmap.Save(ms, ImageFormat.Bmp); var bytes = ms.GetBuffer(); LuminanceSource source = new RGBLuminanceSource(bytes, bmap.Width, bmap.Height); var bitmap = new BinaryBitmap(new HybridBinarizer(source)); var result = new MultiFormatReader().decode(bitmap); return result.Text; }
/// <summary> /// Scans the camera's preview buffer for a QR code. /// </summary> private void ScanPreviewBuffer() { int width = (int) _camera.PreviewResolution.Width; int height = (int) _camera.PreviewResolution.Height; byte[] pixelData = new byte[width * height]; _camera.GetPreviewBufferY( pixelData ); var luminance = new RGBLuminanceSource( pixelData, width, height, RGBLuminanceSource.BitmapFormat.Gray8 ); var binarizer = new HybridBinarizer( luminance ); var bitmap = new BinaryBitmap( binarizer ); var result = new QRCodeReader().decode( bitmap ); if ( result != null ) { Dispatcher.BeginInvoke( () => ProcessResult( result ) ); } }
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); }; }
public void Decode() { Bitmap bitmap = new Bitmap(@"text.png"); try { MemoryStream memoryStream = new MemoryStream(); bitmap.Save(memoryStream, ImageFormat.Bmp); byte[] byteArray = memoryStream.GetBuffer(); ZXing.LuminanceSource source = new RGBLuminanceSource(byteArray, bitmap.Width, bitmap.Height); var binarizer = new HybridBinarizer(source); var binBitmap = new BinaryBitmap(binarizer); QRCodeReader qrCodeReader = new QRCodeReader(); Result str = qrCodeReader.decode(binBitmap); Assert.AreEqual(str, "Hello World!"); } catch { } }