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


		CodeReader.reset();

		return CodeReader.decode(bitMap);
	}
Example #2
0
        private static void imageWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            // scanning for a barcode
            var wbmp = (WriteableBitmap)e.Argument;

            var luminiance = new RGBLuminanceSource(wbmp, wbmp.PixelWidth, wbmp.PixelHeight);
            var binarizer = new HybridBinarizer(luminiance);
            var binBitmap = new BinaryBitmap(binarizer);
            var reader = new MultiFormatReader();
            e.Result = reader.decode(binBitmap);
        }
        /// <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]
        }
Example #4
0
 private void ScanPreviewBuffer()
 {
     try
     {
         _photoCamera.GetPreviewBufferY(_luminance.PreviewBufferY);
         var binarizer = new HybridBinarizer(_luminance);
         var binBitmap = new BinaryBitmap(binarizer);
         var result = _reader.decode(binBitmap);
         Dispatcher.BeginInvoke(() => DisplayResult(result.Text));
     }
     catch
     {
     }
 }
Example #5
0
        public BinaryBitmap GetBinaryBitmap(string imageName)
        {
            var fullName = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Images", imageName);

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

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

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

            var i = new BinaryBitmap(bin);

            return(i);
        }
Example #6
0
        public bool DetectQRCode()
        {
            var qrReader = new QRCodeMultiReader();

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

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

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

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

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

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

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

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

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

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

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

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

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

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

                return true;
            }

            return false;
        }
        private void ScanPreviewBuffer()
        {
            if (_photoCamera == null) return;
            if (!_initialized) return;

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

                var result = _reader.decode(binBitmap);
                if (result != null)
                    OnDecodingCompleted(result);
            }
            catch (Exception)
            {
                // If decoding fails it will throw a ReaderException
                // and we're not interested in doing anything with it
            }
        }
        /// <summary>
        /// Function for just fetching the QR-Codes in the WebCamTexture-Image.
        /// It stores the Data in a QrCodeData-Object.
        /// It uses the "pixels" field as the image-source, since we can not
        /// access the Unity-API from another thread than the main-thread.
        /// </summary>
        private void DecodeQr()
        {
            while (_runThread)
            {
                // waiting.
                if (_pixels != null)
                {
                    // Create a BitMatrix from the Color32[] of the camear image, so that XZing can detect QR-codes.
                    LuminanceSource lum = new Color32LuminanceSource(_pixels, GlobalState.Instance.CamWidth, GlobalState.Instance.CamHeight);
                    HybridBinarizer bin = new HybridBinarizer(lum);
                    BinaryBitmap binBip = new BinaryBitmap(bin);
                    BitMatrix matrix = binBip.BlackMatrix;

                    Detector detector = new Detector(matrix);
                    DetectorResult result = detector.detect();
                    _qrCodeCollection.UpdateData(result);
                }
            }
        }
        /// <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>
        /// 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 ) );
            }
        }
Example #11
-1
        private void btnSave_Click(object sender, EventArgs e)
        {
            var reader = new MultiFormatReader();
            var img = (Bitmap)Bitmap.FromFile(pictureBox1.ImageLocation);

            BitmapLuminanceSource ls = new BitmapLuminanceSource(img);
            var binarizer = new HybridBinarizer(ls);
            BinaryBitmap binaryBitmap = new BinaryBitmap(binarizer);
            var result = reader.decode(binaryBitmap);
            richTextBox1.Text = result.Text.Trim();
        }
Example #12
-1
        public void Decode()
        {
            Bitmap bitmap = new Bitmap(@"text.png");
            try
            {
                MemoryStream memoryStream = new MemoryStream();
                bitmap.Save(memoryStream, ImageFormat.Bmp);

                byte[] byteArray = memoryStream.GetBuffer();

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

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

            }
            catch { }
        }