コード例 #1
1
        private void ReadBitmap(Bitmap bitmap)
        {
            var reader = new ZXing.BarcodeReader();
            reader.Options.TryHarder = true;
            reader.AutoRotate = true;

            var decoded = reader.Decode(bitmap);

            if (decoded != null)
            {
                var text = decoded.Text;

                var uri = new Uri(text);

                if (uri.Scheme == "otpauth")
                {
                    var queryString = HttpUtility.ParseQueryString(uri.Query);
                    var secret = queryString["secret"];
                    var account = uri.LocalPath.StartsWith("/") ? uri.LocalPath.Substring(1) : uri.LocalPath;
                    txtAccountName.Text = HttpUtility.UrlDecode(account);
                    Key = secret;
                }
                else
                {
                    MessageBox.Show("The QR Code does not contain valid OAuth data", "Authentiqr.NET", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            else
            {
                MessageBox.Show("The QR Code could not be read", "Authentiqr.NET", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
コード例 #2
1
ファイル: MainForm.cs プロジェクト: epulosis/animalcrossingqr
        private void LoadFromQR(Bitmap bitmap)
        {
            ZXing.BarcodeReader reader = new ZXing.BarcodeReader();
            reader.PossibleFormats = new[] { ZXing.BarcodeFormat.QR_CODE };
            ZXing.Result result = reader.Decode(bitmap);

            if (result != null)
            {
                try
                {
                    AC.Pattern pattern = AC.Pattern.CreateFromRawData(result.RawBytes);
                    LoadPattern(pattern);
                }
                catch (NotImplementedException)
                {
                    MessageBox.Show("This type of pattern is currently not supported.", Text);
                }
            }
            else
            {
                MessageBox.Show("A valid QR code was not found in the selected image.", Text);
            }
        }
コード例 #3
0
        public async Task ScanBarcodeAsync(Windows.Storage.StorageFile file)
        {
            WriteableBitmap bitmap;
            BitmapDecoder decoder;
            using (IRandomAccessStream str = await file.OpenReadAsync())
            {
                decoder = await BitmapDecoder.CreateAsync(str);
                bitmap = new WriteableBitmap(Convert.ToInt32(decoder.PixelWidth), Convert.ToInt32(decoder.PixelHeight));
                await bitmap.SetSourceAsync(str);
            }

            lock (locker)
            {                
                ZXing.BarcodeReader reader = new ZXing.BarcodeReader();
                reader.Options.PossibleFormats = new ZXing.BarcodeFormat[] { ZXing.BarcodeFormat.CODE_128, ZXing.BarcodeFormat.QR_CODE, ZXing.BarcodeFormat.CODE_39 };
                reader.Options.TryHarder = true;
                reader.AutoRotate = true;
                var results = reader.Decode(bitmap);
                if (results == null)
                {
                    this.OnBarcodeScannCompleted(new BarcodeScanCompletedEventArgs(false, string.Empty));
                }
                else
                {
                    this.OnBarcodeScannCompleted(new BarcodeScanCompletedEventArgs(true, results.Text));
                }
            }
        }
コード例 #4
0
 private ProtectedString ParseFromImage(System.Drawing.Bitmap bitmap)
 {
     if (bitmap == null)
     {
         return(ProtectedString.EmptyEx);
     }
     ZXing.BarcodeReader r      = new ZXing.BarcodeReader();
     ZXing.Result        result = r.Decode(bitmap);
     if (result != null)
     {
         return(new ProtectedString(true, result.Text));
     }
     return(ProtectedString.EmptyEx);
 }
コード例 #5
0
 private void BtnUpload_Click(object sender, EventArgs e)
 {
     if (FileUpload1.HasFile)
     {
         DivInfo.Visible    = false;
         DivWarning.Visible = false;
         var ext      = Path.GetExtension(FileUpload1.FileName).ToLower();
         var tempPath = Path.GetTempFileName() + ext;
         FileUpload1.SaveAs(tempPath);
         HashSet <String> exts = new HashSet <string> {
             ".bmp", ".png", ".jpg", ".gif", ".png"
         };
         if (exts.Contains(ext))
         {
             ImageQR.ImageUrl = "/handlers/imageloader.ashx?ImgPath=" + tempPath;
             var qr      = new ZXing.BarcodeReader();
             var options = new DecodingOptions
             {
                 CharacterSet = "UTF-8",
             };
             qr.Options = options;
             Bitmap bmp = (Bitmap)Bitmap.FromFile(tempPath);
             var    res = qr.Decode(bmp);
             if (res != null && !string.IsNullOrEmpty(res.Text))
             {
                 try
                 {
                     var decrypt = Crypto.Decrypt(res.Text);
                     LoadHeaderInfo(decrypt.Trim());
                 }
                 catch
                 {
                     CommonWeb.Alert(this, "Qr dapat dibaca tapi tidak valid.");
                 }
             }
             else
             {
                 CommonWeb.Alert(this, "Qr tidak dapat dibaca, atau gambar tidak valid.");
             }
         }
         else
         {
             CommonWeb.Alert(this, "Silakan upload file dengan tipe gambar");
         }
     }
     else
     {
         CommonWeb.Alert(this, "Silakan pilih foto QR LHP terlebih dahulu.");
     }
 }
コード例 #6
0
        private void video_NewFrame(object sender, NewFrameEventArgs eventArgs)
        {
            Thread threadShowPicture = new Thread(ShowPicture);
            Bitmap bitmap            = (Bitmap)eventArgs.Frame.Clone(); //Загрузка картинки с камеры в picturebox

            pbCamImage.Image = bitmap;

            ZXing.Result result = reader.Decode((Bitmap)eventArgs.Frame.Clone()); //Выгрузка результата сканирования
            if (result != null)
            {
                SetResult(result.Text);
                threadShowPicture.Abort();
            }
        }
コード例 #7
0
        public Form1()
        {
            InitializeComponent();

            Bitmap img = new Bitmap("qrcode.gif");

            ZXing.BarcodeReader reader = new ZXing.BarcodeReader();
            ZXing.Result        result = reader.Decode(img);

            if (result != null)
            {
                textBox1.Text = result.BarcodeFormat.ToString();
                textBox2.Text = result.Text;
            }
        }
コード例 #8
0
        public async Task <DecodeResult> DecodeAsync(Frame frame)
        {
            var result = await Task.Run <ZXing.Result>(() =>
            {
                var width = 0;

                if (frame.Format == FrameFormat.Bgra32)
                {
                    width = (int)frame.Dimensions.Width;
                }
                else if (frame.Format == FrameFormat.Gray8)
                {
                    width = (int)frame.Pitch;
                }
                else
                {
                    throw new ArgumentException(String.Format("Incompatible frame format: {0}", frame.Format.ToString()));
                }

                return(_reader.Decode(frame.Buffer, width, (int)frame.Dimensions.Height, FrameFormatToBitmapFormat(frame.Format)));
            });

            if (result != null)
            {
                var decodeResult = new DecodeResult()
                {
                    Text   = result.Text,
                    Data   = result.RawBytes,
                    Format = result.BarcodeFormat.ToString()
                };

                if (result.ResultPoints != null && result.ResultPoints.Length > 0)
                {
                    decodeResult.InterestPoints = new List <Windows.Foundation.Point>();

                    foreach (ZXing.ResultPoint point in result.ResultPoints)
                    {
                        decodeResult.InterestPoints.Add(new Windows.Foundation.Point(point.X, point.Y));
                    }
                }

                return(decodeResult);
            }
            else
            {
                return(null);
            }
        }
コード例 #9
0
ファイル: Form1.cs プロジェクト: xiefengan/receipt
        private void timer3_Tick(object sender, EventArgs e)
        {
            System.Drawing.Bitmap bitmap = null;
            //宣告 QRCode Reader 物件

            ZXing.IBarcodeReader reader = new ZXing.BarcodeReader();

            bitmap = (Bitmap)pictureBox2.Image;
            //進行解碼的動作
            ZXing.Result result = reader.Decode(bitmap);

            if (result != null)
            {   //如果有成功解讀,則顯示文字
                label10.Text = result.Text;
            }
        }
コード例 #10
0
        /// <summary>
        /// Decodes a barcode from the given image.
        /// </summary>
        /// <param name="image">The image of the barcode.</param>
        /// <returns>The data encoded in the barcode.</returns>
        ///
        /// <remarks>Uses the ZXing.NET library to parse the image.</remarks>
        public string DecodeBarcode(Image image)
        {
            var reader = new ZXing.BarcodeReader();

            var bmp  = new Bitmap(image);
            var data = reader.Decode(bmp);

            if (data != null)
            {
                return(data.Text);
            }
            else
            {
                return("");
            }
        }
コード例 #11
0
        private void button2_Click(object sender, EventArgs e)
        {
            ZXing.BarcodeReader barcodeReader = new ZXing.BarcodeReader();
            string deskPath = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);

            System.IO.FileInfo fi = new System.IO.FileInfo(deskPath + @"\test.jpg");

            if (fi.Exists)
            {
                var barcodeBitmap = (Bitmap)Image.FromFile(deskPath + @"\test.jpg");
                var result        = barcodeReader.Decode(barcodeBitmap);

                this.textBox1.Text = result.Text;
            }
            else
            {
                MessageBox.Show("Please generate QRcode first.\n Press barcode maker button.", "Nofile", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
コード例 #12
0
        private void ReadBitmap(Bitmap bitmap)
        {
            var reader  = new ZXing.BarcodeReader();
            var decoded = reader.Decode(bitmap);

            RenderQRCode(decoded.Text);

            Regex otpInfo = new Regex(@"otpauth://totp/(.*)\?secret=([^&]+)(&.*)?");

            if (otpInfo.IsMatch(decoded.Text))
            {
                var match = otpInfo.Match(decoded.Text);
                txtAccountName.Text = HttpUtility.UrlDecode(match.Groups[1].Value);
                SetKey(match.Groups[2].Value);
            }
            else
            {
                MessageBox.Show("The QR Code does not contain valid OAuth data", "LCGoogleApps", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
コード例 #13
0
ファイル: Form1.cs プロジェクト: ricochoi712/QRCodeScanner
        private void TimerEventProcessor(object sender, EventArgs e)
        {
            Image <Bgr, Byte> frame = new Image <Bgr, Byte>(360, 280);

            frame             = cap.QueryFrame();
            _pictureBox.Image = frame.ToBitmap();

            ZXing.IBarcodeReader reader = new ZXing.BarcodeReader();

            ZXing.Result result = reader.Decode(frame.ToBitmap());

            qrRealTime._timer.Tick += new EventHandler(qrRealTime._timer_Tick);

            if (result != null)
            {
                _timer.Stop();
                _pictureBox.Image = null;
                MessageBox.Show(result.Text);
                qrRealTime._timer.Stop();
            }
        }
コード例 #14
0
        private void ReadBitmap(Bitmap bitmap)
        {
            var reader = new ZXing.BarcodeReader();

            reader.Options.TryHarder = true;
            reader.AutoRotate        = true;

            var decoded = reader.Decode(bitmap);

            if (decoded != null)
            {
                if (!ParseOtpAuth(decoded.Text))
                {
                    MessageBox.Show("The QR Code does not contain valid OAuth data", "Authentiqr.NET", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            else
            {
                MessageBox.Show("The QR Code could not be read", "Authentiqr.NET", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
コード例 #15
0
        public Barcode Read(Bitmap barcodeImage)
        {
            if (barcodeImage is null)
            {
                return(null);
            }
            barcodeImage = AddWhiteBorder(barcodeImage);

            ZXing.BarcodeReader reader = new ZXing.BarcodeReader();
            reader.Options.AssumeGS1 = true;
            reader.Options.TryHarder = true;
            reader.TryInverted       = true;
            reader.AutoRotate        = true;

            ZXing.Result result = reader.Decode(barcodeImage);
            if (result is null)
            {
                return(null);
            }

            return(new Barcode(result.Text, FormatMap.Resolve(result.BarcodeFormat)));
        }
コード例 #16
0
        private void InitializeDecoder(PhotoConfirmationCapturedEventArgs photoResult)
        {
            _image  = new BitmapImage();
            _reader = new ZXing.BarcodeReader();


            Task.Run(delegate()
            {
                _reader.Options.TryHarder = false;
                _reader.TryInverted       = false;
                _reader.AutoRotate        = false;
                _image.SetSource(photoResult.Frame);
                ZXing.Result result = _reader.Decode(new WriteableBitmap(_image.PixelWidth, _image.PixelHeight));
                if (result != null)
                {
                    AddBarcodeToResults(result);
                }
                else
                {
                    SetActivityMessage("No barcode detected", false);
                }
            }).ConfigureAwait(false).GetAwaiter().GetResult();
        }
コード例 #17
0
        private async void Button_Click(object sender, RoutedEventArgs e)
        {
            var picker = new Windows.Storage.Pickers.FileOpenPicker();

            picker.ViewMode = Windows.Storage.Pickers.PickerViewMode.Thumbnail;
            picker.FileTypeFilter.Add(".jpg");
            picker.FileTypeFilter.Add(".jpeg");
            picker.FileTypeFilter.Add(".png");
            picker.FileTypeFilter.Add(".gif");
            picker.FileTypeFilter.Add(".bmp");

            Windows.Storage.StorageFile file = await picker.PickSingleFileAsync();

            if (file == null)
            {
                return;
            }

            ClearResult();

            // 選択された画像ファイルからSoftwareBitmapを作る
            // https://docs.microsoft.com/ja-jp/windows/uwp/audio-video-camera/imaging
            SoftwareBitmap softwareBitmap;

            using (IRandomAccessStream stream = await file.OpenReadAsync())
            {
                BitmapDecoder decoder = await BitmapDecoder.CreateAsync(stream);

                softwareBitmap = await decoder.GetSoftwareBitmapAsync();
            }
            // Image コントロールは、BGRA8 エンコードを使用し、プリマルチプライ処理済みまたはアルファ チャネルなしの画像しか受け取れない
            // 異なるフォーマットの場合は変換する☟
            if (softwareBitmap.BitmapPixelFormat != BitmapPixelFormat.Bgra8 ||
                softwareBitmap.BitmapAlphaMode == BitmapAlphaMode.Straight)
            {
                softwareBitmap = SoftwareBitmap.Convert(softwareBitmap, BitmapPixelFormat.Bgra8, BitmapAlphaMode.Premultiplied);
            }
            // ImageコントロールにはSoftwareBitmapSourceを渡す
            var source = new SoftwareBitmapSource();
            await source.SetBitmapAsync(softwareBitmap);

            this.Image1.Source = source;

            // バーコード読み取り
            ZXing.BarcodeReader _reader
                = new ZXing.BarcodeReader
                {
                AutoRotate = true,
                Options    = { TryHarder = true }
                };
            // UWPではSoftwareBitmapかWriteableBitmapを渡す
            //ZXing.Result result = _reader.Decode(softwareBitmap);
            // ☟別スレッドでやるときも、作成済みのSoftwareBitmapインスタンスを渡してよい
            ZXing.Result result
                = await Task.Run(() => _reader.Decode(softwareBitmap));

            if (result != null)
            {
                ShowResult(result);
            }
        }
コード例 #18
0
 /// <summary>
 /// バーコードリーダー
 /// </summary>
 /// <param name="_bitmap">ビットマップ</param>
 /// <returns>バーコードリーダーの結果</returns>
 public async Task <ZXing.Result> BarcodeReader(Bitmap _bitmap)
 {
     ZXing.BarcodeReader reader = new ZXing.BarcodeReader();
     reader.AutoRotate = true;
     return(await Task.Run(() => reader.Decode(_bitmap)));
 }
コード例 #19
0
        private string ToImage(HttpPostedFile file)
        {
            var reader = new ZXing.BarcodeReader();

            return(reader.Decode(new Bitmap(System.Drawing.Image.FromStream(file.InputStream))).Text);
        }
コード例 #20
0
        public void OnPreviewFrame(byte[] bytes, Android.Hardware.Camera camera)
        {
            //Check and see if we're still processing a previous frame
            if (processingTask != null && !processingTask.IsCompleted)
            {
                return;
            }

            if ((DateTime.UtcNow - lastPreviewAnalysis).TotalMilliseconds < options.DelayBetweenAnalyzingFrames)
            {
                return;
            }

            var cameraParameters = camera.GetParameters();
            var width            = cameraParameters.PreviewSize.Width;
            var height           = cameraParameters.PreviewSize.Height;

            //var img = new YuvImage(bytes, ImageFormatType.Nv21, cameraParameters.PreviewSize.Width, cameraParameters.PreviewSize.Height, null);
            lastPreviewAnalysis = DateTime.UtcNow;

            processingTask = Task.Factory.StartNew(() =>
            {
                try
                {
                    if (barcodeReader == null)
                    {
                        barcodeReader = new ZXing.BarcodeReader(null, null, null, (p, w, h, f) =>
                                                                new ZXing.PlanarYUVLuminanceSource(p, w, h, 0, 0, w, h, false));
                        //new PlanarYUVLuminanceSource(p, w, h, dataRect.Left, dataRect.Top, dataRect.Width(), dataRect.Height(), false))

                        if (this.options.TryHarder.HasValue)
                        {
                            barcodeReader.Options.TryHarder = this.options.TryHarder.Value;
                        }
                        if (this.options.PureBarcode.HasValue)
                        {
                            barcodeReader.Options.PureBarcode = this.options.PureBarcode.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 <ZXing.BarcodeFormat>();

                            foreach (var pf in this.options.PossibleFormats)
                            {
                                barcodeReader.Options.PossibleFormats.Add(pf);
                            }
                        }
                    }

                    bool rotate   = false;
                    int newWidth  = width;
                    int newHeight = height;

                    var cDegrees = getCameraDisplayOrientation(this.activity);

                    if (cDegrees == 90 || cDegrees == 270)
                    {
                        rotate    = true;
                        newWidth  = height;
                        newHeight = width;
                    }

                    var start = PerformanceCounter.Start();

                    if (rotate)
                    {
                        bytes = rotateCounterClockwise(bytes, width, height);
                    }

                    var result = barcodeReader.Decode(bytes, newWidth, newHeight, ZXing.RGBLuminanceSource.BitmapFormat.Unknown);

                    PerformanceCounter.Stop(start, "Decode Time: {0} ms (width: " + width + ", height: " + height + ", degrees: " + cDegrees + ", rotate: " + rotate + ")");

                    if (result == null || string.IsNullOrEmpty(result.Text))
                    {
                        return;
                    }

                    Android.Util.Log.Debug("ZXing.Mobile", "Barcode Found: " + result.Text);

                    ShutdownCamera();

                    callback(result);
                }
                catch (ZXing.ReaderException)
                {
                    Android.Util.Log.Debug("ZXing.Mobile", "No barcode Found");
                    // ignore this exception; it happens every time there is a failed scan
                }
                catch (Exception)
                {
                    // TODO: this one is unexpected.. log or otherwise handle it
                    throw;
                }
            });
        }
コード例 #21
-1
        private void InitializeDecoder(PhotoConfirmationCapturedEventArgs photoResult)
        {
            _image = new BitmapImage();
            _reader = new ZXing.BarcodeReader();

            Task.Run(delegate()
            {
            _reader.Options.TryHarder = false;
            _reader.TryInverted = false;
            _reader.AutoRotate = false;
            _image.SetSource(photoResult.Frame);
            ZXing.Result result = _reader.Decode(new WriteableBitmap(_image.PixelWidth, _image.PixelHeight));
            if (result != null)
            {
                AddBarcodeToResults(result);
            }
            else
            {
                SetActivityMessage("No barcode detected", false);
            }
            }).ConfigureAwait(false).GetAwaiter().GetResult();
        }