This implementation can detect and decode QR Codes in an image. Sean Owen
Inheritance: Reader
Beispiel #1
0
        static void barcode_decode(string path)
        {
            ImageConverter converter = new ImageConverter();

            var reader = new ZXing.QrCode.QRCodeReader();
            //ZXing.BinaryBitmap
            var dest = (Bitmap)Bitmap.FromFile(path);
            var bb   = (byte[])converter.ConvertTo(dest, typeof(byte[]));
            // ;
            // BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
            var source = new BitmapLuminanceSource(dest);
            // LuminanceSource source = new RGBLuminanceSource(bb,dest.Width,dest.Height, RGBLuminanceSource.BitmapFormat.RGB32);
            HybridBinarizer binarizer = new HybridBinarizer(source);
            BinaryBitmap    binBitmap = new BinaryBitmap(binarizer);
            QRCodeReader    qrr       = new QRCodeReader();
            var             result    = qrr.decode(binBitmap);

            if (result != null)
            {
                var text = result.Text;
                Console.WriteLine(text);
            }
            else
            {
                Console.WriteLine("Err");
            }
        }
        private void OnPhotoCameraInitialized(object sender, CameraOperationCompletedEventArgs e)
        {
            var width = Convert.ToInt32(_photoCamera.PreviewResolution.Width);
            var height = Convert.ToInt32(_photoCamera.PreviewResolution.Height);

            _luminance = new PhotoCameraLuminanceSource(width, height);
            _reader = new QRCodeReader();

            Dispatcher.BeginInvoke(() =>
            {
                _previewTransform.Rotation = _photoCamera.Orientation;
                _timer.Start();
            });
        }
Beispiel #3
0
        /// <summary>
        /// This method detects a code in a "pure" image -- that is, pure monochrome image
        /// which contains only an unrotated, unskewed, image of a code, with some white border
        /// around it. This is a specialized method that works exceptionally fast in this special
        /// case.
        ///
        /// <seealso cref="ZXing.Datamatrix.DataMatrixReader.extractPureBits(BitMatrix)" />
        /// </summary>
        private static BitMatrix extractPureBits(BitMatrix image)
        {
            int[] leftTopBlack     = image.getTopLeftOnBit();
            int[] rightBottomBlack = image.getBottomRightOnBit();
            if (leftTopBlack == null || rightBottomBlack == null)
            {
                return(null);
            }

            float moduleSize;

            if (!QRCodeReader.moduleSize(leftTopBlack, image, out moduleSize))
            {
                return(null);
            }

            int top    = leftTopBlack[1];
            int bottom = rightBottomBlack[1];
            int left   = leftTopBlack[0];
            int right  = rightBottomBlack[0];

            // Sanity check!
            if (left >= right || top >= bottom)
            {
                return(null);
            }

            if (bottom - top != right - left)
            {
                // Special case, where bottom-right module wasn't black so we found something else in the last row
                // Assume it's a square, so use height as the width
                right = left + (bottom - top);
            }

            int matrixWidth  = (int)Math.Round((right - left + 1) / moduleSize);
            int matrixHeight = (int)Math.Round((bottom - top + 1) / moduleSize);

            if (matrixWidth <= 0 || matrixHeight <= 0)
            {
                return(null);
            }
            if (matrixHeight != matrixWidth)
            {
                // Only possibly decode square regions
                return(null);
            }

            // Push in the "border" by half the module width so that we start
            // sampling in the middle of the module. Just in case the image is a
            // little off, this will help recover.
            int nudge = (int)(moduleSize / 2.0f);

            top  += nudge;
            left += nudge;

            // But careful that this does not sample off the edge
            // "right" is the farthest-right valid pixel location -- right+1 is not necessarily
            // This is positive by how much the inner x loop below would be too large
            int nudgedTooFarRight = left + (int)((matrixWidth - 1) * moduleSize) - right;

            if (nudgedTooFarRight > 0)
            {
                if (nudgedTooFarRight > nudge)
                {
                    // Neither way fits; abort
                    return(null);
                }
                left -= nudgedTooFarRight;
            }
            // See logic above
            int nudgedTooFarDown = top + (int)((matrixHeight - 1) * moduleSize) - bottom;

            if (nudgedTooFarDown > 0)
            {
                if (nudgedTooFarDown > nudge)
                {
                    // Neither way fits; abort
                    return(null);
                }
                top -= nudgedTooFarDown;
            }

            // Now just read off the bits
            BitMatrix bits = new BitMatrix(matrixWidth, matrixHeight);

            for (int y = 0; y < matrixHeight; y++)
            {
                int iOffset = top + (int)(y * moduleSize);
                for (int x = 0; x < matrixWidth; x++)
                {
                    if (image[left + (int)(x * moduleSize), iOffset])
                    {
                        bits[x, y] = true;
                    }
                }
            }
            return(bits);
        }
        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."));
        }
Beispiel #5
0
        /// <summary>
        /// This method detects a code in a "pure" image -- that is, pure monochrome image
        /// which contains only an unrotated, unskewed, image of a code, with some white border
        /// around it. This is a specialized method that works exceptionally fast in this special
        /// case.
        ///
        /// <seealso cref="ZXing.PDF417.PDF417Reader.extractPureBits(BitMatrix)" />
        /// <seealso cref="ZXing.Datamatrix.DataMatrixReader.extractPureBits(BitMatrix)" />
        /// </summary>
        private static BitMatrix extractPureBits(BitMatrix image)
        {
            int[] leftTopBlack     = image.getTopLeftOnBit();
            int[] rightBottomBlack = image.getBottomRightOnBit();
            if (leftTopBlack == null || rightBottomBlack == null)
            {
                return(null);
            }

            float moduleSize;

            if (!QRCodeReader.moduleSize(leftTopBlack, image, out moduleSize))
            {
                return(null);
            }

            int top    = leftTopBlack[1];
            int bottom = rightBottomBlack[1];
            int left   = leftTopBlack[0];
            int right  = rightBottomBlack[0];

            if (bottom - top != right - left)
            {
                // Special case, where bottom-right module wasn't black so we found something else in the last row
                // Assume it's a square, so use height as the width
                right = left + (bottom - top);
            }

            int matrixWidth  = (int)Math.Round((right - left + 1) / moduleSize);
            int matrixHeight = (int)Math.Round((bottom - top + 1) / moduleSize);

            if (matrixWidth <= 0 || matrixHeight <= 0)
            {
                return(null);
            }
            if (matrixHeight != matrixWidth)
            {
                // Only possibly decode square regions
                return(null);
            }

            // Push in the "border" by half the module width so that we start
            // sampling in the middle of the module. Just in case the image is a
            // little off, this will help recover.
            int nudge = (int)(moduleSize / 2.0f);

            top  += nudge;
            left += nudge;

            // Now just read off the bits
            BitMatrix bits = new BitMatrix(matrixWidth, matrixHeight);

            for (int y = 0; y < matrixHeight; y++)
            {
                int iOffset = top + (int)(y * moduleSize);
                for (int x = 0; x < matrixWidth; x++)
                {
                    if (image[left + (int)(x * moduleSize), iOffset])
                    {
                        bits[x, y] = true;
                    }
                }
            }
            return(bits);
        }
        /// <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 ) );
            }
        }
Beispiel #7
0
    private void FindQRCode(PhotoCaptureFrame photoCaptureFrame)
    {
//#if NETFX_CORE
        RGBLuminanceSource source = new RGBLuminanceSource(_sourceTexture.GetRawTextureData(), _sourceTexture.width, _sourceTexture.height);
        BinaryBitmap       bitmap = new BinaryBitmap(new HybridBinarizer(source));

        ZXing.QrCode.QRCodeReader qrCodeReader = new ZXing.QrCode.QRCodeReader();
        qrResult = qrCodeReader.decode(bitmap);



        if (qrResult != null)
        {
            //GameObject.Find("/Graph/Canvas/GraphTitle").GetComponent<Text>().text = qrResult.Text;

            #region marker code
            if (false)
            {
                Vector2[] resultPoints = new Vector2[qrResult.ResultPoints.Length];
                for (int i = 0; i < resultPoints.Length; i++)
                {
                    resultPoints[i] = new Vector2(qrResult.ResultPoints[i].X, qrResult.ResultPoints[i].Y);
                    _markers[i].transform.position = MarkerPosition(resultPoints[i]);
                    //_markers[i].GetComponent<Renderer>().enabled = true;
                }

                // Average the 2 diagonal points to get an estimate of the QR code center
                Vector2 qrCenter = (resultPoints[0] + resultPoints[2]) / 2.0f;
                _markers[3].transform.position = MarkerPosition(qrCenter);
                //_markers[3].GetComponent<Renderer>().enabled = true;

                Matrix4x4 cameraToWorldMatrix;
                Matrix4x4 projectionMatrix;
                if (!photoCaptureFrame.TryGetCameraToWorldMatrix(out cameraToWorldMatrix))
                {
                    cameraToWorldMatrix = Camera.main.cameraToWorldMatrix;
                    Debug.Log("Failed to get view matrix from photo");
                }

                if (!photoCaptureFrame.TryGetProjectionMatrix(out projectionMatrix))
                {
                    projectionMatrix = Camera.main.projectionMatrix;
                    Debug.Log("Failed to get view matrix from photo");
                }

                Vector3 normalizedPos  = Normalize(qrCenter);
                Vector3 cameraSpacePos = UnProjectVector(projectionMatrix, normalizedPos);

                Vector3 origin = cameraToWorldMatrix * new Vector4(0, 0, 0, 1);
                Vector3 worldPos;
                _debugRay  = ImageToWorld(photoCaptureFrame, qrCenter, out worldPos);
                QRPosotion = worldPos;

                float qrProportion = Vector2.Distance(resultPoints[0], resultPoints[1]) / _sourceTexture.height;
                float halfHeight   = (cornerDistance / qrProportion) / 2.0f;
                float halfFOV      = verticalFOV / 2.0f;
                _distance = halfHeight / Mathf.Tan(halfFOV * Mathf.Deg2Rad);
            }
            #endregion

            Debug.Log(string.Format("QR Text: {0}", qrResult.Text));
            qrResultText = qrResult.Text;

            var segments = qrResultText.Split('|');
            switch (segments[0])
            {
            case "auth":
                if (segments.Length != 3)
                {
                    Debug.Log("ERROR: invalid auth QR Code expected 3 segments got: " + segments.Length);
                    break;
                }
                AzureStorageConstants.Account   = segments[1];
                AzureStorageConstants.KeyString = segments[2];
                Debug.Log("Set Auth correctly");
                var click = GameObject.Find("MetalClick");
                click.GetComponent <AudioSource>().Play();
                this.StopReading();
                break;

            case "graph":
                if (segments.Length != 4)
                {
                    Debug.Log("ERROR: invalid auth QR Code expected 4 segments got: " + segments.Length);
                    break;
                }
                var timestamp = segments[1];
                AzureStorageConstants.container = segments[2];
                var blob = segments[3];
                //blob = "iris.hgd";

                if (!renderedQR.ContainsKey(timestamp))
                {
                    renderedQR.Add(timestamp, true);
                    Graph.createGraph(blob);
                    Debug.Log("rendering graph");
                    var scan = GameObject.Find("BeepScan");
                    scan.GetComponent <AudioSource>().Play();
                    this.StopReading();
                }
                break;
            }
        }
        else
        {
            //for (int i = 0; i < _markers.Length; i++)
            //{
            //    _markers[i].GetComponent<Renderer>().enabled = false;
            //}

            //Debug.Log("No QR code found");
        }
//#endif
    }
Beispiel #8
-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 { }
        }