コード例 #1
0
ファイル: UCSignInOut.cs プロジェクト: 16101163/SP-Repo
        //private void splitContainer1_Panel1_Paint(object sender, PaintEventArgs e)
        //{

        //}

        private void timer1_Tick(object sender, EventArgs e)
        {
            QRCodeReader Scanner = new QRCodeReader();

            if (pictureBox1.Image != null)
            {
                byte[]          mybyte = (byte[])new ImageConverter().ConvertTo(pictureBox1.Image, Type.GetType("Byte"));
                LuminanceSource source = new RGBLuminanceSource(mybyte, pictureBox1.Image.Width, pictureBox1.Image.Height);
                var             bin    = new HybridBinarizer(source);
                var             binBit = new BinaryBitmap(bin);
                Result          result = Scanner.decode(binBit);

                try
                {
                    string decoded = result.ToString().Trim();
                    if (decoded == "Hello")
                    {
                        MessageBox.Show(decoded);
                        timer1.Stop();
                    }



                    //splitContainer1.Panel2.Enabled = true;
                    //textBox1.Text = decoded;
                }
                catch (Exception ex)
                {
                }
            }
        }
コード例 #2
0
ファイル: FormMainZX.cs プロジェクト: tomyqg/MyCShapeStudy
        //解码
        private void btnDecode_Click(object sender, EventArgs e)
        {
            try
            {
                //创建解码器
                MultiFormatReader reader = new MultiFormatReader();
                Bitmap            bitmap = (Bitmap)Bitmap.FromFile(decodePath);
                if (bitmap == null)
                {
                    return;
                }

                LuminanceSource ls = new RGBLuminanceSource(bitmap, bitmap.Width, bitmap.Height);
                BinaryBitmap    bb = new BinaryBitmap(new HybridBinarizer(ls));

                //注意编码对应 : UTF-8
                Hashtable hints = new Hashtable();
                hints.Add(EncodeHintType.CHARACTER_SET, "UTF-8");
                Result result = reader.decode(bb, hints);
                txtMsgDecode.Text = result.Text;
                labShow.Text      = "解码成功!";
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
コード例 #3
0
        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);
        }
コード例 #4
0
ファイル: Form1.cs プロジェクト: yh821/QRCode
        /// <summary>
        /// 解码操作
        /// </summary>
        private void button3_Click(object sender, EventArgs e)
        {
            lbshow.Text = "";
            if (pictureBox2.Image == null)
            {
                lbshow.Text = "未导入图片!";
                return;
            }

            try
            {
                //构建解码器
                com.google.zxing.MultiFormatReader mutiReader = new com.google.zxing.MultiFormatReader();
                Bitmap img = (Bitmap)pictureBox2.Image; //(Bitmap)Bitmap.FromFile(opFilePath);
                com.google.zxing.LuminanceSource ls = new RGBLuminanceSource(img, img.Width, img.Height);
                com.google.zxing.BinaryBitmap    bb = new com.google.zxing.BinaryBitmap(new com.google.zxing.common.HybridBinarizer(ls));

                //注意  必须是Utf-8编码
                Hashtable hints = new Hashtable();
                hints.Add(com.google.zxing.EncodeHintType.CHARACTER_SET, "UTF-8");
                com.google.zxing.Result r = mutiReader.decode(bb, hints);
                txtmsg2.Text = r.Text;
                lbshow.Text  = "解码成功!";
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
コード例 #5
0
        BinaryBitmap GetBitmapFromVideo(PhotoCamera cam)
        {
            BinaryBitmap binaryBitmap = null;

            try
            {
                // Update buffer size
                var pixelWidth  = (int)_cam.PreviewResolution.Width;
                var pixelHeight = (int)_cam.PreviewResolution.Height;

                if (_buffer == null || _buffer.Length != (pixelWidth * pixelHeight))
                {
                    _buffer = new byte[pixelWidth * pixelHeight];
                }

                _cam.GetPreviewBufferY(_buffer);

                var luminance = new RGBLuminanceSource(_buffer, pixelWidth, pixelHeight, true);
                var binarizer = new com.google.zxing.common.HybridBinarizer(luminance);

                binaryBitmap = new BinaryBitmap(binarizer);
            }
            catch
            {
            }

            return(binaryBitmap);
        }
コード例 #6
0
        private void button6_Click(object sender, EventArgs e)
        {
            if (pbSlika.Image == null)
            {
                MessageBox.Show("Niste uslikali ništa!");
                return;
            }
            btnStop_Click(null, null);
            dekodirao = false;
            try
            {
                Bitmap             img2    = (Bitmap)pbCamera.Image;
                Reader             reader  = new MultiFormatReader();
                RGBLuminanceSource source1 = new RGBLuminanceSource(img2, img2.Width, img2.Height);
                BinaryBitmap       bitmap  = new BinaryBitmap(new HybridBinarizer(source1));

                Result result = reader.decode(bitmap);
                if (!dekodirao)
                {
                    dekodirao = true;
                    MessageBox.Show("Dekodirao sam: " + result.Text);
                }
                //BarCodeDetectTimer.Stop();
            }
            catch (Exception e1)
            {
                MessageBox.Show("GRESKA: (vjerovatno je slika lose kvalitete, probaj rotirati) - nisam uspio prepoznati sliku");
            }
        }
コード例 #7
0
ファイル: KwQRCodeReader.cs プロジェクト: xxdoc/BCTest
        private Result ProcessQRReader(Bitmap image)
        {
            image = preProcessImage(image);
            //image = new Bitmap("d:\\AMA_QR.bmp");
            LuminanceSource ls      = new RGBLuminanceSource(image, image.Width, image.Height);
            Binarizer       hb      = new HybridBinarizer(ls);
            Result          result  = null;
            BinaryBitmap    bbitmap = new BinaryBitmap(hb);

            try
            {
                result = reader.decode(bbitmap);
            }
            catch (ReaderException rex)
            {
                Console.WriteLine(rex.Message);
                if (counter == 0)
                {
                    image   = paddingImage(image, 20);
                    counter = 1;
                    return(ProcessQRReader(image));
                }
                else
                {
                    counter = 0;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            counter = 0;
            return(result);
        }
コード例 #8
0
        void skenirajSliku()
        {
            try
            {
                Bitmap             img2    = (Bitmap)pbCamera.Image;
                Reader             reader  = new MultiFormatReader();
                RGBLuminanceSource source1 = new RGBLuminanceSource(img2, img2.Width, img2.Height);
                BinaryBitmap       bitmap  = new BinaryBitmap(new HybridBinarizer(source1));

                Result result = reader.decode(bitmap);
                if (!dekodirao)
                {
                    dekodirao = true;
                    btnStop_Click(null, null);
                    MessageBox.Show("Dekodirao sam: " + result.Text);
                }
                else
                {
                    btnStop_Click(null, null);
                }
            }
            catch (Exception e1)
            {
                Console.WriteLine("GRESKA: (vjerovatno je slika lose kvalitete, probaj rotirati) - tj. nisam uspio prepoznati sliku");
            }
        }
コード例 #9
0
        void AddQR(Bitmap bmp)
        {
            LuminanceSource source = new RGBLuminanceSource(bmp, bmp.Width, bmp.Height);
            BinaryBitmap    bin    = new BinaryBitmap(new HybridBinarizer(source));

            Result res = qrReader.decode(bin);

            StatusL.Text = "QR 読み取り成功";
            string ret = res.Text.Sanitize();

            foreach (QR QR in QRs)
            {
                if (QR.RawShapeData == ret)
                {
                    StatusL.Text = "QR 読み取り済み";
                    return;
                }
            }

            QRInputT.Text = ret;

            QR qr = new QR(ret);

            QRs.Add(qr);

            foreach (Shape s in qr.Shapes)
            {
                AddShape(s);
            }

            if (qr.IsFrameAvailable)
            {
                AddShape(qr.Frame, "Frame", Pens.BurlyWood, Brushes.BurlyWood);
            }
        }
コード例 #10
0
        protected void btnDecode_Click(object sender, EventArgs e)
        {
            if (Convert.ToString(Session["isDefaultImage"]) == "IsDefault")
            {
                lblErrorDecode.Text      = "Upload QR Code First!";
                lblErrorDecode.ForeColor = System.Drawing.Color.Red;
                return;
            }
            property.path = Server.MapPath("~/Images/QR_Codes/" + "img.bmp");
            System.Drawing.Image image = System.Drawing.Image.FromStream(new MemoryStream(File.ReadAllBytes(property.path)));
            Bitmap bitMap = new Bitmap(image);

            try
            {
                com.google.zxing.LuminanceSource source = new RGBLuminanceSource(bitMap, bitMap.Width, bitMap.Height);
                var                     binarizer       = new com.google.zxing.common.HybridBinarizer(source);
                var                     binBitmap       = new com.google.zxing.BinaryBitmap(binarizer);
                QRCodeReader            qrCodeReader    = new QRCodeReader();
                com.google.zxing.Result str             = qrCodeReader.decode(binBitmap);

                txtDecodedOriginalInfo.Text = str.ToString();

                lblErrorDecode.Text      = "Successfully Decoded!";
                lblErrorDecode.ForeColor = System.Drawing.Color.Green;
            }
            catch
            {
            }
        }
コード例 #11
0
    public void ReadQRCode(Color[] clist, int width, int height, Action <string> OnOk = null)
    {
        byte[] bcolor = new byte[width * height * 3];

        for (int y = 0; y < height; y++)
        {
            int offset = y * width;
            for (int x = 0; x < width; x++)
            {
                bcolor[offset * 3 + x * 3]     = (byte)(clist[x * height + y].r * 255);
                bcolor[offset * 3 + x * 3 + 1] = (byte)(clist[x * height + y].g * 255);
                bcolor[offset * 3 + x * 3 + 2] = (byte)(clist[x * height + y].b * 255);
            }
        }

        Loom.RunAsync(() =>
        {
            try
            {
                QRCodeReader qrreader      = new QRCodeReader();
                RGBLuminanceSource scource = new RGBLuminanceSource(bcolor, width, height);
                HybridBinarizer binarizer  = new HybridBinarizer(scource);
                BinaryBitmap bitmap        = new BinaryBitmap(binarizer);
                Result result = qrreader.decode(bitmap);
                Loom.QueueOnMainThread(() => { OnOk(result.Text); });
            }
            catch (Exception ex)
            {
            }
        });
    }
コード例 #12
0
        private bool checkForFalsePositives(WriteableBitmap image, float rotationInDegrees)
#endif
        {
            var rotatedImage = rotateImage(image, rotationInDegrees);
            var source       = new RGBLuminanceSource(rotatedImage);
            var bitmap       = new BinaryBitmap(new HybridBinarizer(source));
            var result       = getReader().decode(bitmap);

            if (result != null)
            {
                Console.WriteLine("Found false positive: '{0}' with format '{1}' (rotation: {2})\n",
                                  result.Text, result.BarcodeFormat, (int)rotationInDegrees);
                return(false);
            }

            // Try "try harder" getMode
            var hints = new Dictionary <DecodeHintType, Object>();

            hints[DecodeHintType.TRY_HARDER] = true;
            result = getReader().decode(bitmap, hints);
            if (result != null)
            {
                Console.WriteLine("Try harder found false positive: '{0}' with format '{1}' (rotation: {2})\n",
                                  result.Text, result.BarcodeFormat, (int)rotationInDegrees);
                return(false);
            }
            return(true);
        }
コード例 #13
0
        private bool Zxing()
        {
            LuminanceSource source = new RGBLuminanceSource(img, img.Width, img.Height);

            com.google.zxing.BinaryBitmap bitmap1 = new com.google.zxing.BinaryBitmap(new HybridBinarizer(source));
            Result result;

            try
            {
                result = new MultiFormatReader().decode(bitmap1);
                Camera.Stop();
                scanTimer.Stop();
                System.Windows.Application.Current.Dispatcher.BeginInvoke(new Action(() =>
                {
                    epStatus.Visibility   = Visibility.Visible;
                    imgScan.Visibility    = Visibility.Collapsed;
                    QRCodeInfo qRCodeInfo = new QRCodeInfo(this, result.Text);
                    qRCodeInfo.Show();
                }));
                return(true);
            }
            catch
            {
                return(false);
            }
        }
コード例 #14
0
        private bool Zxing()
        {
            LuminanceSource source = new RGBLuminanceSource(img, img.Width, img.Height);

            com.google.zxing.BinaryBitmap bitmap1 = new com.google.zxing.BinaryBitmap(new HybridBinarizer(source));
            Result result;

            try
            {
                result    = new MultiFormatReader().decode(bitmap1);
                isScaning = false;
                scanTimer.Stop();
                System.Windows.Application.Current.Dispatcher.BeginInvoke(new Action(() =>
                {
                    btnScan.Content = "Scan";
                    tbQRCode.Text   = result.Text;
                }));

                return(true);
            }
            catch
            {
                return(false);
            }
        }
コード例 #15
0
        public String getQRCodeData(Bitmap bitmap)
        {
            LuminanceSource source       = new RGBLuminanceSource(bitmap, bitmap.Width, bitmap.Height);
            BinaryBitmap    binaryBitmap = new BinaryBitmap(new HybridBinarizer(source));

            return(this.reader.decode(binaryBitmap).Text);
        }
コード例 #16
0
        private async Task <string> ReadImageAsync(byte[] data)
        {
            try
            {
                var bitmap = new BitmapImage();
                using (var stream = new InMemoryRandomAccessStream())
                {
                    await stream.WriteAsync(data.AsBuffer());

                    stream.Seek(0);
                    await bitmap.SetSourceAsync(stream);
                }

                var source    = new RGBLuminanceSource(data, bitmap.PixelWidth, bitmap.PixelHeight);
                var reader    = new ZXing.QrCode.QRCodeReader();
                var binarizer = new HybridBinarizer(source);
                var bitmapx   = new BinaryBitmap(binarizer);
                var result    = reader.decode(bitmapx);

                return(result.Text);
            }
            catch (Exception ex)
            {
                return(string.Empty);
            }
        }
コード例 #17
0
        private void btn_File_Click(object sender, System.EventArgs e)
        {
            string         sRes = "";
            OpenFileDialog ofn  = new OpenFileDialog();

            if (ofn.ShowDialog() == DialogResult.OK)
            {
                try {
                    Reader barcodeReader =
                        new com.google.zxing.MultiFormatReader();
                    System.Drawing.Bitmap srcbitmap =
                        new System.Drawing.Bitmap(ofn.FileName.ToString());                                         // Make a copy of the image in the Bitmap variable
                    //make a grey bitmap of it
                    bmp_util util = new bmp_util();
                    srcbitmap = util.ConvertToGrayscale(srcbitmap);

                    RGBLuminanceSource source =
                        new RGBLuminanceSource(srcbitmap, srcbitmap.Width, srcbitmap.Height);
                    com.google.zxing.BinaryBitmap bitmap =
                        new com.google.zxing.BinaryBitmap(new HybridBinarizer(source));
                    com.google.zxing.Result result = barcodeReader.decode(bitmap);
                    System.Console.WriteLine(result.Text);
                    sRes = result.Text;
                }
                catch (com.google.zxing.ReaderException zex) {
                    sRes = zex.Message;
                    System.Console.WriteLine(zex.Message);
                }
                catch (Exception ex) {
                    sRes = ex.Message;
                    System.Console.WriteLine(ex.Message);
                }
                tb.Text = sRes;
            }
        }
コード例 #18
0
        public void RGBLuminanceSource_Should_Work_With_BitmapImage()
        {
            var pixelFormats = new []
            {
                PixelFormats.Bgr24,
                PixelFormats.Bgr32,
                PixelFormats.Bgra32,
                PixelFormats.Rgb24,
                //PixelFormats.Bgr565, // conversion isn't accurate to compare it directly to RGB24
                //PixelFormats.Bgr555, // conversion isn't accurate to compare it directly to RGB24
                PixelFormats.Gray8,
            };

            foreach (var pixelFormat in pixelFormats)
            {
                BitmapSource bitmapImage = new BitmapImage(new Uri(samplePicRelPath, UriKind.RelativeOrAbsolute));
                if (bitmapImage.Format != pixelFormat)
                {
                    bitmapImage = new FormatConvertedBitmap(bitmapImage, pixelFormat, null, 0);
                }
                var rgbLuminanceSource       = new RGBLuminanceSource(bitmapImage);
                var rgbLuminanceSourceResult = rgbLuminanceSource.ToString();
                Assert.That(samplePicRelResult.Equals(rgbLuminanceSourceResult));
            }
        }
コード例 #19
0
        public static string Decode(string path)
        {
            Image           img    = Image.FromFile(path);
            Bitmap          bmap   = new Bitmap(img);
            LuminanceSource source = new RGBLuminanceSource(bmap, bmap.Width, bmap.Height);

            com.google.zxing.BinaryBitmap bitmap = new com.google.zxing.BinaryBitmap(new com.google.zxing.common.HybridBinarizer(source));
            return(new MultiFormatReader().decode(bitmap).Text);
        }
コード例 #20
0
        private void button3_Click(object sender, EventArgs e)
        {
            if (this.pictureBox1.Image == null)
            {
                return;
            }
            Image  img = this.pictureBox1.Image;
            Bitmap bmap;

            try
            {
                bmap = new Bitmap(img);
            }
            catch (System.IO.IOException ioe)
            {
                MessageBox.Show(ioe.ToString());
                return;
            }
            if (bmap == null)
            {
                MessageBox.Show("无法解析该图像!");
                return;
            }
            LuminanceSource source = new RGBLuminanceSource(bmap, bmap.Width, bmap.Height);

            com.google.zxing.BinaryBitmap bitmap = new com.google.zxing.BinaryBitmap(new HybridBinarizer(source));
            Result result;

            try
            {
                result = new MultiFormatReader().decode(bitmap);
            }
            catch (ReaderException re)
            {
                MessageBox.Show("解码出现异常,可能不支持此编码!", "提示");
                //MessageBox.Show(re.ToString());
                return;
            }
            this.textBox1.Text = result.Text;
            if (result.BarcodeFormat == BarcodeFormat.DATAMATRIX)
            {
                this.lblFormat.Text = "Datamatrix";
            }
            else if (result.BarcodeFormat == BarcodeFormat.PDF417)
            {
                this.lblFormat.Text = "PDF417";
            }
            else if (result.BarcodeFormat == BarcodeFormat.QR_CODE)
            {
                this.lblFormat.Text = "QR Code";
            }
            else
            {
                this.lblFormat.Text = "未知格式";
            }
        }
コード例 #21
0
        /// <summary>
        /// https://stackoverflow.com/a/32135865
        /// </summary>
        /// <param name="bitmap"></param>
        /// <returns></returns>
        private BinaryBitmap ConvertBitmapToBytes(Bitmap bitmap)
        {
            int[] intArr = new int[bitmap.Width * bitmap.Height];
            bitmap.GetPixels(intArr, 0, bitmap.Width, 0, 0, bitmap.Width, bitmap.Height);
            byte[]          bytes        = ConvertIntArrToByteArr(intArr);
            LuminanceSource source       = new RGBLuminanceSource(bytes, bitmap.Width, bitmap.Height);
            BinaryBitmap    binaryBitmap = new BinaryBitmap(new HybridBinarizer(source));

            return(binaryBitmap);
        }
コード例 #22
0
ファイル: MDecoder.cs プロジェクト: kaiwen1007/PKRentalViewer
        public string findQrCodeText(com.google.zxing.Reader decoder, Bitmap bitmap)
        {
            var rgb    = new RGBLuminanceSource(bitmap, bitmap.Width, bitmap.Height);
            var hybrid = new com.google.zxing.common.HybridBinarizer(rgb);

            com.google.zxing.BinaryBitmap binBitmap = new com.google.zxing.BinaryBitmap(hybrid);
            string decodedString = decoder.decode(binBitmap, null).Text;

            return(decodedString);
        }
コード例 #23
0
        private static byte[] ParseQR(Image q)
        {
            var bitmap    = new Bitmap(q);
            var img       = new RGBLuminanceSource(bitmap, bitmap.Width, bitmap.Height);
            var hybrid    = new HybridBinarizer(img);
            var binaryMap = new BinaryBitmap(hybrid);
            var reader    = new QRCodeReader().Decode(binaryMap, null);

            return(Array.ConvertAll(reader.RawBytes, a => (byte)a));
        }
コード例 #24
0
ファイル: QrReader.cs プロジェクト: miroslavpokorny/smap
        public QrReaderData ReadQrCode(string filePath)
        {
            var barcodeReader = new BarcodeReader();

            var bitmap = Image.FromFile(filePath) as Bitmap;

            if (bitmap == null)
            {
                throw new NullReferenceException("bitmap should not be null");
            }
            bitmap = bitmap.Clone(new Rectangle(0, 0, bitmap.Width / 5, bitmap.Height / 8), PixelFormat.Format24bppRgb);

            var bitmapSource = new RGBLuminanceSource(ImageHelper.ImageToByteArray(bitmap), bitmap.Width, bitmap.Height);
            var result       = barcodeReader.Decode(bitmapSource);

            var readMetaData = new MetaData();

            readMetaData.Parse(Decoder.DecodeBase64(result.Text));

            var maxY = 0;
            var minY = bitmap.Height;

            foreach (var resultResultPoint in result.ResultPoints)
            {
                if (resultResultPoint.Y > maxY)
                {
                    maxY = (int)resultResultPoint.Y;
                }
                if (resultResultPoint.Y < minY)
                {
                    minY = (int)resultResultPoint.Y;
                }
            }

            var points = result.ResultPoints.ToList();

            points.Sort((a, b) => a.X <b.X ? -1 : a.X> b.X ? 1 : a.Y <b.Y ? -1 : a.Y> b.Y ? 1 : 0);

            var upperLeftPoint = points[0];
            var lowerLeftPoint = points[1];

            if (upperLeftPoint.Y > lowerLeftPoint.Y)
            {
                var tmp = upperLeftPoint;
                upperLeftPoint = lowerLeftPoint;
                lowerLeftPoint = tmp;
            }

            return(new QrReaderData
            {
                MetaData = readMetaData,
                QrCodeBottomPositionY = maxY + (maxY - minY) / 4,
                PageRotation = (Math.Abs(upperLeftPoint.X - lowerLeftPoint.X) < 0.001 ? 0 : upperLeftPoint.X < lowerLeftPoint.X ? -1 : 1) * Math.Tan(Math.Abs(upperLeftPoint.X - lowerLeftPoint.X) / Math.Abs(upperLeftPoint.Y - lowerLeftPoint.Y)) * (180 / Math.PI)
            });
        }
コード例 #25
0
        public byte[] parseQR(Image q)
        {
            Bitmap       bitmap    = new Bitmap(q);
            var          img       = new RGBLuminanceSource(bitmap, bitmap.Width, bitmap.Height);
            var          hybrid    = new HybridBinarizer(img);
            BinaryBitmap binaryMap = new BinaryBitmap(hybrid);
            var          reader    = new QRCodeReader().decode(binaryMap, null);

            byte[] data = Array.ConvertAll(reader.RawBytes, (a) => (byte)(a));
            return(data);
        }
コード例 #26
0
        private void PumpYFrames()
        {
            byte[] array = new byte[307200];
            bool   flag  = false;

            while (this._pumpYFrames)
            {
                BarcodeScanner._pauseFramesEvent.WaitOne();
                if (this._isScanning)
                {
                    try
                    {
                        this._cam.GetPreviewBufferY(array);
                        flag = true;
                    }
                    catch
                    {
                        flag = false;
                    }
                    if (flag)
                    {
                        DateTime           now = DateTime.Now;
                        RGBLuminanceSource rGBLuminanceSource = new RGBLuminanceSource(array, 640, 480, false);
                        if (this._scanType == CodeType.OneDCodes || this._scanType == CodeType.UPC || this._scanType == CodeType.ITF || this._scanType == CodeType.EAN || this._scanType == CodeType.Code128 || this._scanType == CodeType.Code39)
                        {
                            rGBLuminanceSource.rotateCounterClockwise();
                        }
                        HybridBinarizer binarizer = new HybridBinarizer(rGBLuminanceSource);
                        BinaryBitmap    image     = new BinaryBitmap(binarizer);
                        Reader          reader    = this.GetReader(this._scanType);
                        try
                        {
                            Result   results   = reader.decode(image, this._hintDictionary);
                            TimeSpan timeSpent = DateTime.Now.Subtract(now);
                            Deployment.Current.Dispatcher.BeginInvoke(delegate
                            {
                                this.ProcessScan(results, timeSpent, this.ScanType);
                                if (this.StopOnSuccess)
                                {
                                    this.IsScanning = false;
                                }
                            }
                                                                      );
                            BarcodeScanner._pauseFramesEvent.Set();
                        }
                        catch
                        {
                            BarcodeScanner._pauseFramesEvent.Set();
                        }
                    }
                }
            }
        }
コード例 #27
0
        public static string Decode(byte[] bytes, int width, int height, BitmapFormat format)
        {
            var          source   = new RGBLuminanceSource(bytes, width, height, format);
            BinaryBitmap bitmap   = new BinaryBitmap(new HybridBinarizer(source));
            Result       qrResult = new MultiFormatReader().decode(bitmap);

            if (qrResult != null)
            {
                return(qrResult.Text);
            }
            return(string.Empty);
        }
コード例 #28
0
        /// <summary>
        /// 识别二维码
        /// </summary>
        /// <param name="b"></param>
        /// <returns></returns>
        private string DistinguishQrImage(Bitmap bm)
        {
            if (bm == null)
            {
                throw new Exception("bitmap is null");
            }
            var source = new RGBLuminanceSource(bm, bm.Width, bm.Height);
            var bbm    = new BinaryBitmap(new HybridBinarizer(source));
            var result = new MultiFormatReader().decode(bbm);

            return(result.Text);
        }
コード例 #29
0
        public async Task <BinaryBitmap> GetBinaryBitmap(string path, CancellationToken token)
        {
            var bitmap   = BitmapFactory.DecodeFile(path);
            var rgbBytes = await Task.Run(() => GetRgbBytesFaster(bitmap, token));

            ResetToReuse();

            var rgbLuminanceSource = new RGBLuminanceSource(rgbBytes, bitmap.Width, bitmap.Height);
            var binarizer          = new HybridBinarizer(rgbLuminanceSource);
            var binaryBitmap       = new BinaryBitmap(binarizer);

            return(binaryBitmap);
        }
コード例 #30
0
        public string GetDecodedValue(byte[] image)
        {
            if (image == null || image.Length == 0)
            {
                return(String.Empty);
            }

            ZXing.Result result = null;

            try
            {
                //Create Bitamp Object, Specifying the Size
                BitmapFactory.Options opts = new BitmapFactory.Options
                {
                    InSampleSize = 2
                };
                Bitmap bitmap = BitmapFactory.DecodeByteArray(image, 0, image.Length, opts);

                //Get RGB by 3rd Demention
                byte[]          rgbBytes = ImageService.GetRgbBytes(bitmap);
                LuminanceSource source   = new RGBLuminanceSource(rgbBytes, bitmap.Width, bitmap.Height);
                BinaryBitmap    bb       = new BinaryBitmap(new HybridBinarizer(source));

                //Read QR Code
                var reader = new MultiFormatReader();
                IDictionary <DecodeHintType, object> hints = new Dictionary <DecodeHintType, object>
                {
                    { ZXing.DecodeHintType.PURE_BARCODE, true },
                    { ZXing.DecodeHintType.POSSIBLE_FORMATS, new List <BarcodeFormat>()
                      {
                          BarcodeFormat.QR_CODE
                      } },                                                                                             //無くても動作します。
                    { ZXing.DecodeHintType.TRY_HARDER, true }
                };
                reader.Hints = hints;
                result       = reader.decode(bb);
            }
            catch (Exception ex)
            {
                // fall thru, it means there is no QR code in image
                Console.WriteLine("あっはーんwwwwww", ex);
                throw;
            }

            if (result != null)
            {
                return(result.Text);
            }
            return(String.Empty);
        }
コード例 #31
0
        void captureSource_CaptureImageCompleted(object sender, CaptureImageCompletedEventArgs e)
        {
            com.google.zxing.qrcode.QRCodeReader qrRead = new com.google.zxing.qrcode.QRCodeReader();
            //This is like a platform neutral way of identifying colors in an image
            RGBLuminanceSource luminiance = new RGBLuminanceSource(e.Result, e.Result.PixelWidth, e.Result.PixelHeight);
            //The next 2 things are used to change color to black and white to be read by the reader
            com.google.zxing.common.HybridBinarizer binarizer = new com.google.zxing.common.HybridBinarizer(luminiance);
            com.google.zxing.BinaryBitmap binBitmap = new com.google.zxing.BinaryBitmap(binarizer);
            com.google.zxing.Result results = default(com.google.zxing.Result);
            try
            {
                //barcode found
                results = qrRead.decode(binBitmap);

                capturedBarcodes.Items.Insert(0, new ScannedImage(results.Text, e.Result));
                capturedBarcodes.SelectedIndex = 0;
                mediaElement1.Stop();
                mediaElement1.Play();

                ImageBrush brush = new ImageBrush();
                brush.ImageSource = e.Result;
                capturedImage.Fill = brush;
            }
            catch (com.google.zxing.ReaderException)
            {
                //no barcode found
                if (captureSource.State == CaptureState.Started)
                {
                    captureSource.CaptureImageAsync();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                StartButton_Click(this, new RoutedEventArgs());
            }

            try
            {
                BarcodeRead(this, new CustomEventHandler() { Barcode = results.Text });
            }
            catch (Exception)
            {
                //no javascript event attached
            }
        }
コード例 #32
0
        /// <summary>
        /// To scan the Image and return the Barcode Data on it
        /// </summary>
        /// <returns>String</returns>
        public string getBarcodeData()
        {
            string barcode;
            
            WriteableBitmap wbmp = new WriteableBitmap(ImageSource);

            RGBLuminanceSource lum = new RGBLuminanceSource(wbmp, wbmp.PixelWidth, wbmp.PixelHeight);
            HybridBinarizer binarizer = new HybridBinarizer(lum);
            BinaryBitmap binBmp = new BinaryBitmap(binarizer);

            try
            {
                Result res = OneDreader.decode(binBmp);
                barcode = res.Text;
                return barcode;
            }
            catch { }
            try
            {
                Result res = QRreader.decode(binBmp);
                barcode = res.Text;
                return barcode;
            }
            catch { }

            try
            {
                Result res = Matreader.decode(binBmp);
                barcode = res.Text;
                return barcode;
            }
            catch { }
            try
            {
                Result res = pdfReader.decode(binBmp);
                barcode = res.Text;
                return barcode;
            }
            catch { }

            return barcode = "No Barcode Found"; //If no matching found
        }
コード例 #33
0
	void Update()
	{
		if (!e_DeviceController.isPlaying  ) {
			return;
		}

		if (e_DeviceController.isPlaying && !decoding)
		{
			orginalc = e_DeviceController.cameraTexture.GetPixels32();
			W = e_DeviceController.cameraTexture.width;
			H = e_DeviceController.cameraTexture.height;
			WxH = W * H;
			targetbyte = new byte[ WxH ];
			z = 0;

			// convert the image color data
			for(int y = H - 1; y >= 0; y--) {
				for(int x = 0; x < W; x++) {
				//	targetbyte[z++] = (byte)( (((int)orginalc[y * W + x].r)+ ((int)orginalc[y * W + x].g) + ((int)orginalc[y * W + x].b))/3);

					targetbyte[z++]  = (byte)(((int)orginalc[y * W + x].r)<<16 | ((int)orginalc[y * W + x].g)<<8 | ((int)orginalc[y * W + x].b));
				}
			}

			Loom.RunAsync(() =>
			              {
				try
				{
					RGBLuminanceSource luminancesource = new RGBLuminanceSource(targetbyte, W, H, true);
					var bitmap = new BinaryBitmap(new HybridBinarizer(luminancesource.rotateCounterClockwise()));
					Result data;
					var reader = new MultiFormatReader();
		
					data = reader.decode(bitmap);
					if (data != null)
					{
						{
							decoding = true;
							dataText = data.Text;
						}
					}
					else 
					{
						for(int y = 0; y != targetbyte.Length; y++) {
							targetbyte[y] = (byte) ( 0xff - (targetbyte[y] &  0xff));
						}

						luminancesource = new RGBLuminanceSource(targetbyte, W, H, true);
						bitmap = new BinaryBitmap(new HybridBinarizer(luminancesource));

						data = reader.decode(bitmap);
						if (data != null)
						{
							{
								decoding = true;
								dataText = data.Text;
							}
						}
					}
				}
				catch (Exception e)
				{
					decoding = false;
				}
			});	
		}
		if(decoding)
		{
			if(tempDecodeing != decoding)
			{
				e_QRScanFinished(dataText);//triger the  sanfinished event;
			}
			tempDecodeing = decoding;
		}
	}
コード例 #34
0
ファイル: Program.cs プロジェクト: akoesnan/PraLoup
        static void Main(string[] args)
        {
            var b = BarcodeFormat.QrCode;
            var g = Guid.NewGuid().ToString();
            string t = "data=" + g;
            ByteMatrix bt = barcodeWriter.Encode(t, b, 150, 150);
            Image i = ConvertByteMatrixToImage(bt);
            i.Save(".\\"+g+".png", ImageFormat.Png);

            Bitmap bitmap = new Bitmap(i);

            Result rawResult;
            RGBLuminanceSource r = new RGBLuminanceSource(bitmap, 150, 150);
            GlobalHistogramBinarizer x = new GlobalHistogramBinarizer(r);
            BinaryBitmap bitmap2 = new BinaryBitmap(x);
            var hints = new System.Collections.Hashtable();
            //hints.Add(DecodeHintType.PossibleFormats, BarcodeFormat.QrCode);
            int count = 0;
            {
                try
                {
                    rawResult = barcodeReader.Decode(bitmap2, hints);
                    if (rawResult != null)
                    {
                        count++;
                        var y = rawResult.Text;
                        var z = rawResult.BarcodeFormat.ToString();
                    }
                }
                catch (ReaderException e)
                {
                    return;
                }
            }
        }
コード例 #35
0
        /// <summary>
        /// To scan the Image and return the Barcode format on it.
        /// </summary>
        /// <returns>String</returns>
        public string getBarcodeFormat()
        {
            string format;
            WriteableBitmap wbmp = new WriteableBitmap(ImageSource);

            RGBLuminanceSource lum = new RGBLuminanceSource(wbmp, wbmp.PixelWidth, wbmp.PixelHeight);
            HybridBinarizer binarizer = new HybridBinarizer(lum);
            BinaryBitmap binBmp = new BinaryBitmap(binarizer);

            try
            {
                Result res = OneDreader.decode(binBmp);
                format = res.BarcodeFormat.ToString();
                return format;
            }
            catch { }
            try
            {
                Result res = QRreader.decode(binBmp);
                format = res.BarcodeFormat.ToString();
                return format;
            }
            catch { }

            try
            {
                Result res = Matreader.decode(binBmp);
                format = res.BarcodeFormat.ToString();
                return format;
            }
            catch { }
            try
            {
                Result res = pdfReader.decode(binBmp);
                format = res.BarcodeFormat.ToString();
                return format;
            }
            catch { }

            return format = "No Format"; //If no matching found
        }
コード例 #36
0
		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;
		}