private static string decodeBarcodeText(System.Drawing.Bitmap barcodeBitmap)
        {
            var source = new BitmapLuminanceSource(barcodeBitmap);

            // using http://zxingnet.codeplex.com/
            // PM> Install-Package ZXing.Net
            var reader = new BarcodeReader(null, null, ls => new GlobalHistogramBinarizer(ls))
            {
                AutoRotate = true,
                TryInverted = true,
                Options = new DecodingOptions
                {
                    TryHarder = true,
                    //PureBarcode = true,
                    /*PossibleFormats = new List<BarcodeFormat>
                    {
                        BarcodeFormat.CODE_128
                        //BarcodeFormat.EAN_8,
                        //BarcodeFormat.CODE_39,
                        //BarcodeFormat.UPC_A
                    }*/
                }
            };

            //var newhint = new KeyValuePair<DecodeHintType, object>(DecodeHintType.ALLOWED_EAN_EXTENSIONS, new Object());
            //reader.Options.Hints.Add(newhint);

            var result = reader.Decode(source);
            if (result == null)
            {
                Console.WriteLine("Decode failed.");
                return string.Empty;
            }

            Console.WriteLine("BarcodeFormat: {0}", result.BarcodeFormat);
            Console.WriteLine("Result: {0}", result.Text);

            var writer = new BarcodeWriter
            {
                Format = result.BarcodeFormat,
                Options = { Width = 200, Height = 50, Margin = 4},
                Renderer = new ZXing.Rendering.BitmapRenderer()
            };
            var barcodeImage = writer.Write(result.Text);
            Cv2.ImShow("BarcodeWriter", barcodeImage.ToMat());

            return result.Text;
        }
        /// <summary>
        /// Resturn a <see cref="string"/> which represent the value of the BarCode found in an image
        /// <param name="BarCodeFound">True if the BarCode was find, False if was generate an error code</param>
        /// <returns>The BarCode found or an error string</returns>
        /// </summary>
        public static string BarCode(out bool BarCodeFound, Bitmap Image )
        {
            BarcodeReader wvBarCodeReader;

            List<BarcodeFormat> wvBarCodesList = new List<BarcodeFormat>();
            wvBarCodesList.Add(BarcodeFormat.All_1D);
            /*for (int i = 1; i< 65536; i*=2)
            {
                BarcodeFormat.
            }

            br_list.Add(BarcodeFormat.EAN_13);
            br_list.Add(BarcodeFormat.EAN_8);
            br_list.Add(BarcodeFormat.);

            */
            wvBarCodeReader = new BarcodeReader { AutoRotate = true };
            wvBarCodeReader.Options.PossibleFormats = wvBarCodesList;
            wvBarCodeReader.Options.TryHarder = true;
            wvBarCodeReader.TryInverted = true;

            Result r;
            r = wvBarCodeReader.Decode(Image);

            if (r==null)
            {
                BarCodeFound = false;
                return null;
            }

            BarCodeFound = true;
            return r.Text.ToString();
        }
Exemple #3
1
 ///
 /// 解密二维码
 ///
 /// 图片
 /// 二维码信息
 private string DecodeQrCode(Bitmap barcodeBitmap)
 {
     BarcodeReader reader = new BarcodeReader();
     reader.Options.CharacterSet = "UTF-8";
     var result = reader.Decode(barcodeBitmap);
     return (result == null) ? null : result.Text;
 }
		//called when data for any output pin is requested
		public void Evaluate(int SpreadMax)
		{
			FOutput.SliceCount = 1;
			IStatus.SliceCount = 1;
			if ((FEnabled[0]) && (FStreamIn[0].Length > 16)) {

				var bmp = Bitmap.FromStream(FStreamIn[0]);
				var reader = new ZXing.BarcodeReader { TryHarder = FTryHard[0] };
				var results = reader.DecodeMultiple((Bitmap)bmp);

				if (results != null) {
					for (int i = 0; i < results.Length; i++) {
						var result = results[i];
						FOutput.SliceCount = results.Length;
						FPoints.SliceCount = results.Length;
						IStatus.SliceCount = results.Length;

						FOutput[i] = ((ZXing.Result)(result)).Text;
						FPoints[i].ResizeAndDismiss(0);
						//FLogger.Log(LogType.Debug,results.Length.ToString());

						for (int j = 0; j < result.ResultPoints.Length; j++) {
							var v = new Vector2D((2 * result.ResultPoints[j].X / bmp.Width) - 1, (-2 * result.ResultPoints[j].Y / bmp.Height) + 1);
							FPoints[i].Add(v);
						}
						IStatus[i] = 1;
					}
				} else {
					FOutput[0] = "";
					FPoints[0].SliceCount = 0;
					FPoints[0].ResizeAndDismiss(0);
					IStatus[0] = 0;
				}
			}
		}
        private void button1_Click(object sender, EventArgs e)
        {
            capturedevice = new FilterInfoCollection(FilterCategory.VideoInputDevice);

                if (pictureBox2.Image != null)
                {
                    pictureBox1.Image = (Image)pictureBox2.Image.Clone();
                }
                else
                {
                    MessageBox.Show("check the camera");
                }

                ////////////////////

                IBarcodeReader reader = new BarcodeReader();
                // load a bitmap
                var barcodeBitmap = (Bitmap)pictureBox1.Image;
                // detect and decode the barcode inside the bitmap
                var result = reader.Decode(barcodeBitmap);
                // do something with the result
                if (result != null)
                {
                    txtDecoderType.Text = result.BarcodeFormat.ToString();
                    txtDecoderContent.Text = result.Text;
                Console.Beep();
                }
        }
        private void scanTimer_Tick(object sender, EventArgs e)
        {
            if (CameraScreen.Source != null)
            {
                System.Drawing.Bitmap bitmap;
                using (MemoryStream outStream = new MemoryStream())
                {
                    BitmapEncoder enc = new BmpBitmapEncoder();
                    enc.Frames.Add(BitmapFrame.Create((BitmapImage)CameraScreen.Source));
                    enc.Save(outStream);
                    bitmap = new System.Drawing.Bitmap(outStream);
                }

                ZXing.BarcodeReader Reader = new ZXing.BarcodeReader();
                Result result = Reader.Decode((Bitmap)bitmap);

                try
                {
                    string decoded = result.ToString().Trim();
                    if (decoded != "")
                    {
                        scanTimer.Stop();
                        MessageBox.Show(decoded);
                    }
                }
                catch (Exception ex)
                { }
            }
        }
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            captureManager = new MediaCapture();
            reader = new BarcodeReader();

            PreviewCameraFeed();
        }
        public async Task<ActionResult> Create(FoodItemViewModel model)
        {
            if (ModelState.IsValid)
            {
                var foodItem = _mapper.Map<FoodItem>(model);
                foodItem.Id = Guid.NewGuid().ToString();

                if (model.ImageUpload != null && model.ImageUpload.ContentLength > 0)
                {
                    var uploadDir = "~/uploads";
                    var imagePath = Path.Combine(Server.MapPath(uploadDir), model.ImageUpload.FileName);
                    var imageUrl = Path.Combine(uploadDir, model.ImageUpload.FileName);
                    model.ImageUpload.SaveAs(imagePath);

                    IBarcodeReader reader = new BarcodeReader();
                    var barcodeBitmap = (Bitmap)Bitmap.FromFile(imagePath);
                    var result = reader.Decode(barcodeBitmap);
                    if (result != null)
                    {
                        foodItem.BarCode = new BarCode { Identifier = result.Text, Type = result.BarcodeFormat == BarcodeFormat.QR_CODE ? BarCodeType.QR : BarCodeType.Regular };
                        model.BarCodeId = result.Text;
                    }
                } else if (!string.IsNullOrEmpty(model.BarCodeId))
                {
                    foodItem.BarCode = new BarCode() { Identifier = model.BarCodeId, Type = BarCodeType.Regular };
                }

                var createdFoodItem = await _api.Create(foodItem);
            }
            return View("Detail", model);
        }
        private void Decoding()
        {
            text.TextContent = "This will take a while...";
            var bmp = new Bitmap(Convert.FromBase64String(bitmapString), Bitmap.BitmapImageType.Bmp);

            image.Bitmap = bmp;

            var operation = mainWindow.Dispatcher.BeginInvoke((obj) =>
            {
                var reader = new ZXing.BarcodeReader {
                    TryHarder = false
                };
                return(reader.Decode((Bitmap)obj));
            }, bmp);

            operation.Wait();
            if (operation.Result != null)
            {
                text.TextContent = ((ZXing.Result)(operation.Result)).Text;
            }
            else
            {
                text.TextContent = "No barcode found.";
            }
        }
Exemple #10
0
        private void timer1_Tick(object sender, EventArgs e)
        {
            Bitmap img = (Bitmap)pictureBox1.Image;

            if (img != null)
            {
                ZXing.BarcodeReader Reader = new ZXing.BarcodeReader();
                Result result = Reader.Decode(img);
                try
                {
                    if (result != null)
                    {
                        string decoded = result.ToString().Trim();
                        cbbMaHang.SelectedValue = decoded;
                        button2.Text            = "QR";
                        timer1.Stop();
                        img.Dispose();
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message + "");
                }
            }
        }
Exemple #11
0
        private void timer1_Tick(object sender, EventArgs e)
        {
            Bitmap img = (Bitmap)picCam.Image;

            if (img != null)
            {
                ZXing.BarcodeReader Reader = new ZXing.BarcodeReader();
                Result result = Reader.Decode(img);
                try
                {
                    string decoded = result.ToString().Trim();
                    if (decoded == PrevResult)
                    {
                        return;
                    }
                    if (Checkscan(decoded))
                    {
                        txt_noti.Text = "Scan complete!";
                    }
                    else
                    {
                        //not correct scan
                        txt_noti.Text = "Scan error!";
                    }
                    img.Dispose();
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message + "");
                }
            }
        }
        public FormMain()
        {
            InitializeComponent();

            Renderer = typeof(BitmapRenderer);

            barcodeReader = new BarcodeReader
            {
                AutoRotate = true,
                TryInverted = true,
                Options = new DecodingOptions { TryHarder = true }
            };

            barcodeReader.ResultPointFound += point =>
            {
                if (point == null)
                    resultPoints.Clear();
                else
                    resultPoints.Add(point);
            };
            barcodeReader.ResultFound += result =>
            {
                //txtType.Text = result.BarcodeFormat.ToString();
                txtContent.Text += result.Text + Environment.NewLine;
                var parsedResult = ResultParser.parseResult(result);
                if (parsedResult != null)
                {
                    txtContent.Text += "\r\n\r\nParsed result:\r\n" + parsedResult.DisplayResult + Environment.NewLine + Environment.NewLine;
                }
            };
            resultPoints = new List<ResultPoint>();
        }
Exemple #13
0
        public Main()
        {
            InitializeComponent();

            FormBorderStyle = FormBorderStyle.FixedSingle;

            this.SuspendLayout();

            barcodeReader = new ZXing.BarcodeReader
            {
                AutoRotate  = false,
                TryInverted = false,
                Options     = new ZXing.Common.DecodingOptions {
                    TryHarder = false
                }
            };

            barcodeReader.ResultFound += result =>
            {
                lastResults.Add(result);
            };

            lastResults = new List <Result>();
            fullResults = new List <Result>();

            listView.Columns.Add("code");
            listView.Columns[0].Width = 200;

            statusStrip.Items.Add(" ");
        }
Exemple #14
0
        public void GetDataFromQRCode(Image MyQRCode)
        {
            Bitmap imgQRCode = (Bitmap)MyQRCode;

            if (imgQRCode != null)
            {
                ZXing.BarcodeReader Reader = new ZXing.BarcodeReader();
                Result result = Reader.Decode(imgQRCode);
                if (result != null)
                {
                    string        decoded  = result.ToString().Trim();
                    CustomerModel customer = CustomerDataProvider.GetCustomer(decoded);

                    if (customer != null)
                    {
                        cap.Dispose();
                        myTimer.Stop();
                        label_email.Text             = customer.Email;
                        label_dateCreated.Text       = customer.DateCreated;
                        label_SeatType.Text          = customer.SeatType;
                        label1_name.Text             = customer.Name;
                        ovalPictureBox1_avatar.Image = Image.FromFile(CommonManager.ProjectDirectory() + customer.Avatar);

                        SuccessCheckInForm resultForm = new SuccessCheckInForm(customer);
                        resultForm.FormClosed += ResultForm_FormClosed;

                        resultForm.ShowDialog();
                        //while (resultForm.IsClose == false) { };
                    }
                }
            }
        }
Exemple #15
0
        private void Scan(Mat source)
        {
            Mat crop = source;

            if (isDetectorActive)
            {
                crop = PreProcessImage(source);
            }
            CurrentFrame = BitmapSourceConvert.MatToBitmapSource(source);
            ShowImage("Crop", crop);

            if (LibActive == ZXingLibName)
            {
                IBarcodeReader reader = new ZXing.BarcodeReader();
                var            stream = new MemoryStream();
                crop.Bitmap.Save(stream, ImageFormat.Jpeg);
                Bitmap barcodeBitmap = (Bitmap)Image.FromStream(stream);
                var    result        = reader.Decode(barcodeBitmap);
                BarCodeText = result == null ? NotDetected : result.Text;
                StateColor  = result == null ? System.Windows.Media.Brushes.Red : System.Windows.Media.Brushes.Green;
            }
            else
            {
                //var PhotoResult = IronBarCode.BarcodeReader.ReadASingleBarcode(img.Bitmap, BarcodeEncoding.Code39, IronBarCode.BarcodeReader.BarcodeRotationCorrection.Medium, IronBarCode.BarcodeReader.BarcodeImageCorrection.DeepCleanPixels);
                var PhotoResult = IronBarCode.BarcodeReader.QuicklyReadOneBarcode(crop.Bitmap);
                BarCodeText = PhotoResult == null ? NotDetected : PhotoResult.Value;
                StateColor  = PhotoResult == null ? System.Windows.Media.Brushes.Red : System.Windows.Media.Brushes.Green;
            }
        }
        public async Task<BarCodeResult> PostFormData()
        {
            if (!Request.Content.IsMimeMultipartContent("form-data"))
            {
                throw new HttpResponseException(HttpStatusCode.BadRequest);
            }

            var provider = await Request.Content.ReadAsMultipartAsync(new InMemoryMultipartFormDataStreamProvider());

            var files = provider.Files;
            var file1 = files[0];
            var fileStream = await file1.ReadAsStreamAsync();

            // create a barcode reader instance
            IBarcodeReader reader = new BarcodeReader();
            // load a bitmap
            var barcodeBitmap = new Bitmap(fileStream);
            // detect and decode the barcode inside the bitmap
            var result = reader.Decode(barcodeBitmap);
            // do something with the result

            var barCodeResult = new BarCodeResult();

            if (result != null)
            {
                barCodeResult.DecoderType = result.BarcodeFormat.ToString();
                barCodeResult.DecoderContent = result.Text;
            }

            return barCodeResult;
        }
Exemple #17
0
		/// <summary>
		/// Continuously look for a QR code
		/// NOTE: this method won't work if recording is enabled ('hey Cortana, start recording' thing).
		/// </summary>
		public static async Task<string> ReadAsync(CancellationToken token = default(CancellationToken))
		{
			var mediaCapture = new MediaCapture();
			await mediaCapture.InitializeAsync();
			await mediaCapture.AddVideoEffectAsync(new MrcVideoEffectDefinition(), MediaStreamType.Photo);

			var reader = new BarcodeReader();
			reader.Options.TryHarder = false;

			while (!token.IsCancellationRequested)
			{
				var imgFormat = ImageEncodingProperties.CreateJpeg();
				using (var ras = new InMemoryRandomAccessStream())
				{
					await mediaCapture.CapturePhotoToStreamAsync(imgFormat, ras);
					var decoder = await BitmapDecoder.CreateAsync(ras);
					using (var bmp = await decoder.GetSoftwareBitmapAsync())
					{
						Result result = await Task.Run(() =>
							{
								var source = new SoftwareBitmapLuminanceSource(bmp);
								return reader.Decode(source);
							});
						if (!string.IsNullOrEmpty(result?.Text))
							return result.Text;
					}
				}
				await Task.Delay(DelayBetweenScans);
			}
			return null;
		}
Exemple #18
0
        private async void Page_Loaded(object sender, RoutedEventArgs e)
        {
            await InitializeQrCode();
            var imgProp = new ImageEncodingProperties { Subtype = "BMP", Width = 600, Height = 800 };
            var bcReader = new BarcodeReader();

            while (true)
            {
                var stream = new InMemoryRandomAccessStream();
                await _mediaCapture.CapturePhotoToStreamAsync(imgProp, stream);

                stream.Seek(0);
                var wbm = new WriteableBitmap(600, 800);
                await wbm.SetSourceAsync(stream);

                var result = bcReader.Decode(wbm);

                if (result != null)
                {
                    var msgbox = new MessageDialog(result.Text);
                    await msgbox.ShowAsync();
                }
            }

        }
        private void timer1_Tick(object sender, EventArgs e)
        {
            lblTime.Text = DateTime.Now.ToLongTimeString();


            if (pictureBox1.Image != null)
            {
                ZXing.BarcodeReader Reader = new ZXing.BarcodeReader();
                Result result = null;
                try
                {
                    result = Reader.Decode((Bitmap)pictureBox1.Image);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                    timer1.Enabled = false;
                    timer1.Enabled = true;

                    Console.Write("error:" + ex.Message);
                    return;
                }

                try
                {
                    string qrCode = result.ToString().Trim();
                    if (qrCode != "")
                    {
                        timer1.Enabled = false;


                        Invoke(new Action(() =>
                        {
                            findAccountByRFID(qrCode);


                            SaveDtr();
                            DailyTimeRecordSELECT();
                            if (PhoneNo != null)
                            {
                                new Messaging().sendSms(PhoneNo.Replace("-", ""), lblName.Text + " \n Time: " + DateTime.Now);
                            }


                            lblUseFingerprint.Text = "Confirm..";
                            this.Tag = null;
                        }));

                        Thread.Sleep(5000);
                        timer1.Enabled = true;
                    }
                }
                catch (Exception ex)
                {
                    timer1.Enabled = false;
                    timer1.Enabled = true;
                    //MessageBox.Show(ex.Message);
                }
            }
        }
      public DecodingOptionsForm(BarcodeReader reader, bool multipleBarcodes, bool multipleBarcodesOnlyQR)
      {
         this.reader = reader;
         InitializeComponent();

         chkMultipleDecode.Checked = multipleBarcodes;
         chkMultipleDecodeOnlyQR.Checked = multipleBarcodesOnlyQR;
      }
    protected override void InitTask() {
      reader = new BarcodeReader {
        AutoRotate = true,
        TryHarder = true,
        PossibleFormats = new List<BarcodeFormat> { BarcodeFormat.QR_CODE }
      };

      buffer = new Image<Bgra, Byte>(Color.Width, Color.Height);
    }
Exemple #22
0
        private string GetBarCodes(string filePath)
        {
            BarcodeReaderInZXing reader = new BarcodeReaderInZXing();

            reader.Options.CharacterSet = "UTF-8";
            Bitmap bitmap = new Bitmap(filePath);

            ZXing.Result result = reader.Decode(bitmap);
            return(result == null ? "" : result.Text);
        }
Exemple #23
0
        /// <summary>
        /// Initializes a new instance of the <see cref="Reader" /> class.
        /// </summary>
        /// <param name="capture">MediaCapture instance.</param>
        /// <param name="width">Capture frame width.</param>
        /// <param name="height">Capture frame height.</param>
        public void Init(MediaCapture capture, uint width, uint height)
        {
            this.capture = capture;
            encodingProps = ImageEncodingProperties.CreateJpeg();
            encodingProps.Width = width;
            encodingProps.Height = height;

            barcodeReader = new BarcodeReader {Options = {TryHarder = true}};
            cancelSearch = new CancellationTokenSource();
        }
Exemple #24
0
        protected void Page_Load(object sender, EventArgs e)
        {
            IBarcodeReader reader = new BarcodeReader();
            // load a bitmap
            var barcodeBitmap = (Bitmap)Bitmap.FromFile(Server.MapPath("~/") + "barcodetest1.jpg");
            // detect and decode the barcode inside the bitmap
            var result = reader.Decode(barcodeBitmap);

            Response.Write(result);
        }
        public static string ReadQR(Bitmap qr)
        {
            ImageConverter converter     = new ImageConverter();
            var            bytes         = (byte[])converter.ConvertTo(qr, typeof(byte[]));
            var            barcodeReader = new ZXing.BarcodeReader();
            var            barcodeBitmap = qr;
            var            barcodeResult = barcodeReader.Decode(bytes);

            return(barcodeResult.Text);
        }
        private void btnDecode_Click(object sender, EventArgs e)
        {
            var reader = new ZXing.BarcodeReader();
            var result = reader.Decode((Bitmap)pic.Image);

            if (result != null)
            {
                txtDecode.Text = result.ToString();
            }
        }
Exemple #27
0
        private void AddDetail_Load(object sender, EventArgs e)
        {
            try
            {
                //////////////////////detail
                comboBox1.Items.Clear();
                comboBox3.Items.Clear();
                detail.Clear();
                MySqlCommand cmd1 = new MySqlCommand
                {
                    Connection  = conn,
                    CommandText = string.Format("SELECT Detail_id, Detail_name FROM Detail;")
                };
                MySqlDataReader reader2 = cmd1.ExecuteReader();
                while (reader2.Read())
                {
                    detail.Add(reader2.GetInt32(0));
                    comboBox1.Items.Add(reader2.GetString(1));
                    comboBox3.Items.Add(reader2.GetString(1));
                }
                reader2.Close();
                ///////////////////////model
                comboBox2.Items.Clear();
                model.Clear();
                cmd1 = new MySqlCommand
                {
                    Connection  = conn,
                    CommandText = string.Format("SELECT Model_id, Model_name FROM Model;")
                };
                reader2 = cmd1.ExecuteReader();
                while (reader2.Read())
                {
                    model.Add(reader2.GetInt32(0));
                    comboBox2.Items.Add(reader2.GetString(1));
                }
                reader2.Close();

                videoDevices = new FilterInfoCollection(FilterCategory.VideoInputDevice);

                reader = new ZXing.BarcodeReader();
                comboBox4.Items.Clear();
                if (videoDevices.Count > 0)
                {
                    foreach (FilterInfo device in videoDevices)
                    {
                        comboBox4.Items.Add(device.Name);
                    }
                    comboBox4.SelectedIndex = 0;
                }
            }
            catch (Exception)
            {
            }
        }
Exemple #28
0
        private void ReadBarcode(Bitmap bitmap)
        {
            IBarcodeReader reader        = new ZXing.BarcodeReader();
            var            barcodeBitmap = bitmap;
            var            result        = reader.Decode(barcodeBitmap);

            if (result != null)
            {
                productIdText.Text = result.Text;
            }
        }
        private async void ScanQRCode()
        {
            br = new BarcodeReader {
                PossibleFormats = new BarcodeFormat[] { BarcodeFormat.QR_CODE }
            };
            br.Options.TryHarder = true;
            br.AutoRotate        = true;
            TimerCallback callBack = new TimerCallback(CaptureQRCodeFromCamera);

            timer = new Timer(callBack, null, 500, Timeout.Infinite);
        }
Exemple #30
0
        /// <summary>
        /// Method to handle the Click event of the Capture Code button
        /// </summary>
        /// <param name="sender">Sender of the Event</param>
        /// <param name="e">Arguments of the event</param>
        private async void CaptureQRCodeFromCamera(object data)
        {
            MessageDialog dialog = new MessageDialog(string.Empty);

            try
            {
                await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, async() =>
                {
                    if (!isCameraFound)
                    {
                        return;
                    }

                    ImageEncodingProperties imgFormat = ImageEncodingProperties.CreateJpeg();
                    // create storage file in local app storage
                    StorageFile file = await ApplicationData.Current.LocalFolder.CreateFileAsync(
                        "temp.jpg",
                        CreationCollisionOption.GenerateUniqueName);
                    // take photo
                    await captureMgr.CapturePhotoToStorageFileAsync(imgFormat, file);
                    // Get photo as a BitmapImage
                    BitmapImage bmpImage   = new BitmapImage(new Uri(file.Path));
                    bmpImage.CreateOptions = BitmapCreateOptions.IgnoreImageCache;
                    using (IRandomAccessStream fileStream = await file.OpenAsync(FileAccessMode.Read))
                    {
                        wrb = await Windows.UI.Xaml.Media.Imaging.BitmapFactory.New(1, 1).FromStream(fileStream);
                    }
                    br = new BarcodeReader {
                        PossibleFormats = new BarcodeFormat[] { BarcodeFormat.QR_CODE }
                    };
                    res = br.Decode(wrb);
                    CameraClickedEventArgs cameraArgs = null;
                    if (res != null)
                    {
                        QrCodeContent = res.Text;
                        cameraArgs    = new CameraClickedEventArgs {
                            EncodedData = this.QrCodeContent
                        };
                        if (this.EmailDecoded != null)
                        {
                            EmailDecoded(this, cameraArgs);
                        }
                    }

                    timer.Change(4000, Timeout.Infinite);
                });
            }

            catch (Exception ex)
            {
                dialog = new MessageDialog("Error: " + ex.Message);
                dialog.ShowAsync();
            }
        }
        private void InitializeDecoder(PhotoResult photoResult)
        {
            _image = new BitmapImage();

            _reader = new BarcodeReader();

            _worker = new BackgroundWorker();
            _worker.DoWork += WorkerOnDoWork;
            _worker.RunWorkerCompleted += WorkerOnRunWorkerCompleted;

            TryGetPhoto(photoResult);
        }
Exemple #32
0
        public static string ReadBarCode(string strFilepath)
        {
            ZXing.BarcodeReader barcodeReader = new ZXing.BarcodeReader();

            Image bitmap = Bitmap.FromFile(strFilepath);

            Bitmap bmp = new Bitmap(bitmap);

            Result result = barcodeReader.Decode(bmp);

            return(result.Text);
        }
        public string readQRCode(byte[] src, int width, int height)
        {
            Debug.Write("qr decoding...");
            IBarcodeReader reader = new ZXing.BarcodeReader();
            var            res    = reader.Decode(src, width, height, BitmapFormat.BGRA32);

            if (res == null)
            {
                return(null);
            }
            return(res.Text);
        }
Exemple #34
0
        /// <summary>
        /// Initializes a new instance of the <see cref="BarcodeScannerUI"/> class.
        /// This implementation not use camera autofocus.
        /// </summary>
        public BarcodeScannerUI()
        {
            this.InitializeComponent();

            // Instantiate objects and start camera preview
            this.camera = new PhotoCamera();
            this.reader = new BarcodeReader {Options = {TryHarder = true}};
            this.CameraBrush.SetSource(this.camera);

            // Bind events
            this.camera.Initialized += this.CameraInitialized;
            this.reader.ResultFound += this.ReaderResultFound;
        }
Exemple #35
0
        /// <summary>
        /// Method to handle the unload event of the User Control. Here, all the MediaCapture resources
        /// are cleaned up.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void UserControl_Unloaded(object sender, RoutedEventArgs e)
        {
            captureMgr = null;
            wrb        = null;
            res        = null;
            br         = null;
            if (timer != null)
            {
                timer.Dispose();
            }

            GC.Collect();
        }
Exemple #36
0
    // ==========================================
    //  CONSTRUCTOR
    // ==========================================

    public QRCodeMatcher(int colorW, int colorH) {

      // Build Reader
      reader = new BarcodeReader {
        AutoRotate = true,
        TryHarder = true,
        PossibleFormats = new List<BarcodeFormat> { BarcodeFormat.QR_CODE }
      };

      // Build WriteableBitmap
      this.colorW = colorW;
      this.colorH = colorH;
    }
Exemple #37
0
        private void LoadBarcode()
        {
            Bitmap imgBarCode = (Bitmap)picBarCode.Image;

            if (imgBarCode != null)
            {
                ZXing.BarcodeReader Reader = new ZXing.BarcodeReader();
                Result result  = Reader.Decode(imgBarCode);
                string decoded = result.ToString();//.Trim();
                txtDiscount.Text = decoded;
                imgBarCode.Dispose();
            }
        }
Exemple #38
0
        private void tmpCapture_Tick(object sender, EventArgs e)
        {
            if (vspEntradaSalida.GetCurrentVideoFrame() != null)
            {
                Bitmap image = new Bitmap(vspEntradaSalida.GetCurrentVideoFrame());
                ZXing.BarcodeReader barcodeReader = new ZXing.BarcodeReader()
                {
                    AutoRotate = true
                };

                Result resultado = barcodeReader.Decode(image);
                //barcode.Format = BarcodeFormat.CODE_128;
                if (resultado != null)
                {
                    string texto = resultado.ToString().Trim();
                    vspEntradaSalida.Stop();
                    tmpCapture.Stop();
                    string[] transpaso = texto.Split('-');
                    if (transpaso.Length == 2 && new Regex("[a-zA-Z]*").IsMatch(transpaso[0]) && new Regex("[0-9]*").IsMatch(transpaso[1]))
                    {
                        if (CargarInformacionPlanilla((transpaso[0].Equals("Socio") ? 1 : 0), Int32.Parse(transpaso[1])))
                        {
                            disposeFormTimer  = 5;
                            msgTimer          = new Timer();
                            msgTimer.Interval = 1000;
                            msgTimer.Enabled  = true;
                            msgTimer.Start();
                            msgTimer.Tick += new System.EventHandler(this.timer_tick);
                        }
                        else
                        {
                            if (vspEntradaSalida != null)
                            {
                                vspEntradaSalida.Start();
                                tmpCapture.Start();
                            }
                        }
                    }
                    else
                    {
                        if (vspEntradaSalida != null)
                        {
                            vspEntradaSalida.Start();
                            tmpCapture.Start();
                        }
                    }
                }
            }
        }
Exemple #39
0
    /// <summary>
    /// unityeditorではないときに処理を行う(unityからの実行はできない?)
    /// </summary>
    /// <param name="src"></param>
    /// <param name="width"></param>
    /// <param name="height"></param>
    /// <returns></returns>
    public string Decode(byte[] src, int width, int height)
    {
#if !UNITY_EDITOR
        Debug.Log("qr decoding...");
        ZXing.IBarcodeReader reader = new ZXing.BarcodeReader();
        var res = reader.Decode(src, width, height, ZXing.BitmapFormat.BGRA32);
        if (res == null)
        {
            return(null);
        }
        return(res.Text);
#else
        return("editor debugging...");
#endif
    }
Exemple #40
0
        private void OnPhotoCameraInitialized(object sender, CameraOperationCompletedEventArgs e)
        {
            int width = Convert.ToInt32(_photoCamera.PreviewResolution.Width);
            int height = Convert.ToInt32(_photoCamera.PreviewResolution.Height);

            this._luminance = new PhotoCameraLuminanceSource(width, height);
            this._reader = new BarcodeReader();
            _reader.Options.TryHarder = true;

            Dispatcher.BeginInvoke(() => _previewTransform.Rotation = _photoCamera.Orientation);

            _photoCamera.Resolution = _photoCamera.AvailableResolutions.First();

            _isInitialized = true;
        }
Exemple #41
0
        public void GetDataFromQRCode(Image MyQRCode)
        {
            Bitmap imgQRCode = (Bitmap)MyQRCode;

            if (imgQRCode != null)
            {
                ZXing.BarcodeReader Reader = new ZXing.BarcodeReader();
                Result result = Reader.Decode(imgQRCode);
                if (result != null)
                {
                    string decoded = result.ToString().Trim();
                    textBox1.Text = decoded;
                }
            }
        }
        /// <summary>
        /// Starts the scan : navigates to the scan page and starts reading video stream
        /// Note : Scan will auto-stop if navigation occurs
        /// </summary>
        /// <param name="onBarCodeFound">Delegate Action on a barcode found</param>
        /// <param name="onError">Delegate Action on error</param>
        /// <param name="zxingReader">(optional) A specific reader format, Default will be EAN13Reader </param>
        public static void StartScan(Action<string> onBarCodeFound, Action<Exception> onError, TimeSpan? maxTry = null, BarcodeFormat barcodeFormat = BarcodeFormat.EAN_13)
        {
            if(maxTry.HasValue)
            {
                MaxTry = maxTry.Value;
            }

            OnBarCodeFound = onBarCodeFound;
            OnError = onError;

            _ZXingReader = GetReader(barcodeFormat);

            _rootFrame = Window.Current.Content as Frame;
            _rootFrame.Navigate(typeof(BarcodePage));
        }
Exemple #43
0
        private void btn_Abrir_Click(object sender, EventArgs e)
        {
            OpenFileDialog Abrir = new OpenFileDialog();

            if (Abrir.ShowDialog() == DialogResult.OK)
            {
                Abrir.Filter = "JPEG(*.JPG)|*.JPG|BMP(*.BMP)|*.BMP";
                Image imagen = pbg_Generar.BackgroundImage;

                pbg_codigo.Image = Image.FromFile(Abrir.FileName);
                ZXing.BarcodeReader br = new ZXing.BarcodeReader();
                string texto           = br.Decode((Bitmap)pbg_codigo.Image).ToString();
                txt_Texto.Text = texto;
            }
        }
        public MainView()
        {
            InitializeComponent();

            _eventAggregator = IoC.Get<IEventAggregator>();
            
            _reader = new BarcodeReader()
            {
                AutoRotate = true,
                Options = new DecodingOptions()
                {
                    TryHarder = true
                }
            };
        }
Exemple #45
0
        private void button1_Click(object sender, EventArgs e)
        {

            BarcodeReader qrDecode = new BarcodeReader(); //чтение QR кода         
            try
        { 
            Result text1 = qrDecode.Decode(new Bitmap(pictureBox1.Image as Bitmap)); //декодирование растрового изображения);   
            textBox1.Text = text1.Text;
        }

            catch 
            {              
                MessageBox.Show("Qr-Код отсуствует или не идентифицирован");                
            }
        }
Exemple #46
0
 public BarcodeDecoder(IOptions <BarcodeConfig> optionsAccessor, IBitmapReader bitmapReader)
 {
     _config       = optionsAccessor.Value;
     _bitmapReader = bitmapReader;
     barcodeReader = new ZXing.BarcodeReader
     {
         AutoRotate  = true,
         TryInverted = true,
         Options     = new DecodingOptions
         {
             TryHarder       = true,
             PossibleFormats = _config.PossibleFormats
         }
     };
     results = new List <DecodeResult>();
 }
Exemple #47
0
 private void btnDecode_Click(object sender, EventArgs e)
 {
     IBarcodeReader reader = new BarcodeReader();
     Result result = reader.Decode((Bitmap)pictureBox1.Image);
     if (result != null)
     {
         var txt = result.Text;
         if (ckbEncode.Checked)
         {
             //txt = ED.DecodeBase64(txt);
             txtSourceStr.Text = txt;
             txt = Person.Decrypt(txt);
         }
         txtDecodeInfo.Text = txt;
     }
 }
Exemple #48
0
        private void Form1_Load(object sender, System.EventArgs e)
        {
            videoDevices = new FilterInfoCollection(FilterCategory.VideoInputDevice);

            reader = new ZXing.BarcodeReader();
            // reader.Options.PossibleFormats = new List<BarcodeFormat>();
            // reader.Options.PossibleFormats.Add(BarcodeFormat.QR_CODE);

            if (videoDevices.Count > 0)
            {
                foreach (FilterInfo device in videoDevices)
                {
                    devices.Items.Add(device.Name);
                }
                devices.SelectedIndex = 0;
            }
        }
Exemple #49
0
        /// <summary>
        /// 读取二维码内容
        /// </summary>
        /// <returns></returns>
        public ActionResult DecodeQRCode()
        {
            //获取上传文件
            if (Request.Files.Count > 0)
            {
                HttpPostedFileBase file = Request.Files[0];
                if (file != null)
                {
                    //检查文件扩展名
                    Regex regex = new Regex(".jpg$|.png$", RegexOptions.IgnoreCase);
                    bool isFileOk = regex.IsMatch(file.FileName);
                    if (isFileOk)
                    {
                        try
                        {
                            //获取图片内容
                            Bitmap bmp = new Bitmap(file.InputStream);

                            //新建读取器
                            BarcodeReader reader = new BarcodeReader
                            {
                                //自动旋转图像?
                                AutoRotate = false,
                                Options =
                                {
                                    //更努力尝试去解析?
                                    TryHarder = false
                                }
                            };

                            //解码二维码
                            Result result = reader.Decode(bmp);

                            //返回解析到的文本内容
                            return Content(result.Text);
                        }
                        catch (Exception exception)
                        {
                            Trace.WriteLine(exception);
                        }
                    }
                }
            }
            return Content("上传文件有误。");
        }
 public WindowsFormsDemoForm()
 {
    InitializeComponent();
    barcodeReader = new BarcodeReader {AutoRotate = true, TryHarder = true, TryInverted = true};
    barcodeReader.ResultPointFound += point =>
                                         {
                                            if (point == null)
                                               resultPoints.Clear();
                                            else
                                               resultPoints.Add(point);
                                         };
    barcodeReader.ResultFound += result =>
                                    {
                                       txtType.Text = result.BarcodeFormat.ToString();
                                       txtContent.Text = result.Text;
                                    };
    resultPoints = new List<ResultPoint>();
 }
		void Decode(UIImage img)
		{
			var reader = new BarcodeReader();
			reader.PossibleFormats = new List<BarcodeFormat>() { this.Format };

			this.Root[1].Clear();
			this.Root[1].Add(new ImageDisplayElement(img, 160f));

			try
			{
				var result = reader.Decode(img);

				this.Root[1].Add(new StyledStringElement("Result:", result.Text));
			}
			catch (Exception ex)
			{
				this.Root[1].Add(new StyledMultilineElement(null, ex.ToString()));
			}
		}
Exemple #52
0
 private void CheckBox1_CheckedChanged(object sender, EventArgs e)
 {
     if (checkBox1.Checked)
     {
         reader            = new ZXing.BarcodeReader();
         comboBox5.Enabled = false;
     }
     else
     {
         if (comboBox5.SelectedIndex > 0)
         {
             reader.Options.PossibleFormats = new List <BarcodeFormat>
             {
                 (BarcodeFormat)comboBox1.SelectedValue
             };
         }
         comboBox5.Enabled = true;
     }
 }
Exemple #53
0
        //called when data for any output pin is requested
        public void Evaluate(int SpreadMax)
        {
            FOutput.SliceCount = 1;
            IStatus.SliceCount = 1;
            if ((FEnabled[0]) && (FStreamIn[0].Length > 16))
            {
                var bmp    = Bitmap.FromStream(FStreamIn[0]);
                var reader = new ZXing.BarcodeReader {
                    TryHarder = FTryHard[0]
                };
                var results = reader.DecodeMultiple((Bitmap)bmp);

                if (results != null)
                {
                    for (int i = 0; i < results.Length; i++)
                    {
                        var result = results[i];
                        FOutput.SliceCount = results.Length;
                        FPoints.SliceCount = results.Length;
                        IStatus.SliceCount = results.Length;

                        FOutput[i] = ((ZXing.Result)(result)).Text;
                        FPoints[i].ResizeAndDismiss(0);
                        //FLogger.Log(LogType.Debug,results.Length.ToString());

                        for (int j = 0; j < result.ResultPoints.Length; j++)
                        {
                            var v = new Vector2D((2 * result.ResultPoints[j].X / bmp.Width) - 1, (-2 * result.ResultPoints[j].Y / bmp.Height) + 1);
                            FPoints[i].Add(v);
                        }
                        IStatus[i] = 1;
                    }
                }
                else
                {
                    FOutput[0]            = "";
                    FPoints[0].SliceCount = 0;
                    FPoints[0].ResizeAndDismiss(0);
                    IStatus[0] = 0;
                }
            }
        }
Exemple #54
0
        private void timer1_Tick(object sender, EventArgs e)
        {
            Bitmap img = (Bitmap)picCam.Image;

            if (img != null)
            {
                ZXing.BarcodeReader Reader = new ZXing.BarcodeReader();
                Result result = Reader.Decode(img);
                try {
                    string decoded = result.ToString();

                    SearchMember(decoded);

                    img.Dispose();
                }
                catch (Exception ex) {
                    Console.WriteLine(ex.Message + "");
                }
            }
        }
Exemple #55
0
        public void UT_DecodeTest()
        {
            // create a barcode reader instance
            IBarcodeReader reader = new BarcodeReader();
            // load a bitmap
            Bitmap barcodeBitmap = null;
            barcodeBitmap = (Bitmap)Bitmap.FromFile(@"C:\temp\heart.jpg");

            if (barcodeBitmap != null)
            {
                // detect and decode the barcode inside the bitmap
                var result = reader.Decode(barcodeBitmap);
                // do something with the result
                if (result != null)
                {
                    Console.WriteLine(result.BarcodeFormat.ToString());
                    Console.WriteLine(result.Text);
                }
            }
        }
		public BarcodeReader BuildBarcodeReader ()
		{
			var reader = new BarcodeReader ();
			if (this.TryHarder.HasValue)
				reader.TryHarder = this.TryHarder.Value;
			if (this.PureBarcode.HasValue)
				reader.PureBarcode = this.PureBarcode.Value;
			if (this.AutoRotate.HasValue)
				reader.AutoRotate = this.AutoRotate.Value;
			if (!string.IsNullOrEmpty (this.CharacterSet))
				reader.CharacterSet = this.CharacterSet;

			reader.PossibleFormats = new List<BarcodeFormat> ();

			foreach (var pf in this.PossibleFormats) {
				reader.PossibleFormats.Add(pf);
			}

			return reader;
		}
        /// <summary>
        /// 识别图片
        /// </summary>
        /// <param name="writeableBmp"></param>
        /// <returns></returns>
        private async Task <Result> ScanQRCodeAsync(WriteableBitmap writeableBmp)
        {
            Result res     = null;
            var    options = new ZXing.Common.DecodingOptions()
            {
                TryHarder = true
            };

            this.barcodeReader = new BarcodeReader {
                Options = options, AutoRotate = true
            };

            await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
            {
                //二维码解码
                res = barcodeReader.Decode(writeableBmp);
            });

            return(res);
        }
        public WindowsFormsDemoForm()
        {
            InitializeComponent();
             barcodeReader = new BarcodeReader
            {
               AutoRotate = true,
               TryInverted = true,
               Options = new DecodingOptions {TryHarder = true}
            };
             barcodeReader.ResultPointFound += point =>
                                              {
                                                 if (point == null)
                                                    resultPoints.Clear();
                                                 else
                                                    resultPoints.Add(point);
                                              };

             resultPoints = new List<ResultPoint>();
             lastResults = new List<Result>();
             Renderer = typeof (BitmapRenderer);
        }
Exemple #59
0
        /// <summary>
        /// Spire插件读取PDF中的二维码,Zxing识别二维码
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        public static string QrCodeToPdftwo(string file)
        {
            string str = "";
            //加载PDF文档
            PdfDocument doc = new PdfDocument();

            doc.LoadFromFile(file);

            List <Image> listImages = new List <Image>();

            for (int i = 0; i < doc.Pages.Count; i++)
            {
                // 实例化一个Spire.Pdf.PdfPageBase对象
                PdfPageBase page = doc.Pages[i];

                // 获取所有pages里面的图片
                Image[] images = page.ExtractImages();
                if (images != null && images.Length > 0)
                {
                    listImages.AddRange(images);
                }
            }

            if (listImages.Count > 0)
            {
                //QRCodeDecoder decoder = new QRCodeDecoder();
                //var image = listImages[0];
                //str = decoder.decode(new ThoughtWorks.QRCode.Codec.Data.QRCodeBitmapImage((Bitmap)image));

                var image = listImages[0];
                ZXing.BarcodeReader reader = new ZXing.BarcodeReader();
                reader.Options.CharacterSet = "UTF-8";
                Bitmap map    = new Bitmap(image);
                Result result = reader.Decode(map);
                return(result == null ? "" : result.Text);
            }

            return(str);
        }
Exemple #60
-1
 //public static int GetSize(string barcodeText)
 //{
 //    var encoder = new QrEncoder(ErrorCorrectionLevel.M);
 //    var code = encoder.Encode(barcodeText);
 //    return code.Matrix.Width;
 //}
 public static string Decode(byte[] data)
 {
     // create a barcode reader instance
     IBarcodeReader reader = new BarcodeReader();
     // load a bitmap
     var barcodeBitmap = (Bitmap)Bitmap.FromStream(new MemoryStream(data));
     // detect and decode the barcode inside the bitmap
     var result = reader.Decode(barcodeBitmap);
     // do something with the result
     if (result != null)
     {
         //result.BarcodeFormat.ToString()
         //result.ResultPoints;
         return result.Text;
     }
     return null;
 }