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(); }
/// /// 解密二维码 /// /// 图片 /// 二维码信息 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; }
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) { }; } } } }
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 + ""); } } }
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 + ""); } } }
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."; } }
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; }
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) { } } }
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; } }
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); } } }
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(); } }
/// <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; }
void decodeframe(Bitmap img) { var barcodeResult = barcodeReader.Decode(img); if (barcodeResult != null) { window.Dispatcher.Invoke(new ThreadStart(delegate { tb.Text = barcodeResult.Text.ToString(); })); } }
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); }
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(); } }
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 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); }
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 void video_NewFrame(object sender, NewFrameEventArgs eventArgs) { Bitmap bitmap = (Bitmap)eventArgs.Frame.Clone(); window.Image = bitmap; ZXing.Result result = reader.Decode((Bitmap)eventArgs.Frame.Clone()); if (result != null) { SetResult(result.Text); } }
/// <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(); } }
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); }
public Result Decode(Bitmap image) { try { var result = _reader.Decode(image); return(result); } catch (Exception ex) { return(null); } }
public async Task CS_W_ZX_DetectCode(string filename, BarcodeFormat barcodeFormat, string barcodeValue) { // Load a bitmap in Bgra8 colorspace var file = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///Input/" + filename)); var source = new StorageFileImageSource(file); Bitmap bitmapBgra8 = await source.GetBitmapAsync(null, OutputOption.PreserveAspectRatio); Assert.AreEqual(ColorMode.Bgra8888, bitmapBgra8.ColorMode); // Convert the bitmap to Nv12 colorspace (colorspace used when decoding barcode from cameras) var bitmapYuv = new Bitmap(bitmapBgra8.Dimensions, ColorMode.Yuv420Sp); bitmapYuv.ConvertFrom(bitmapBgra8); // Decode the barcode var reader = new BarcodeReader { Options = new DecodingOptions { PossibleFormats = new BarcodeFormat[] { barcodeFormat }, TryHarder = true } }; Result resultBgra8 = reader.Decode( bitmapBgra8.Buffers[0].Buffer.ToArray(), (int)bitmapBgra8.Dimensions.Width, (int)bitmapBgra8.Dimensions.Height, BitmapFormat.BGRA32 ); Result resultYuv = reader.Decode( bitmapYuv.Buffers[0].Buffer.ToArray(), (int)bitmapYuv.Buffers[0].Pitch, // Should be width here but I haven't found a way to pass both width and stride to ZXing yet (int)bitmapYuv.Dimensions.Height, BitmapFormat.Gray8 ); Assert.IsNotNull(resultBgra8, "Decoding barcode in Bgra8 colorspace failed"); Assert.AreEqual(barcodeValue, resultBgra8.Text); Assert.IsNotNull(resultYuv, "Decoding barcode in Nv12 colorspace failed"); Assert.AreEqual(barcodeValue, resultYuv.Text); }
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(); } }
private void OnStartDecodeQRCode() { if (!requestedWebCam.isPlaying) { requestedWebCam.Play(); previewImg.texture = requestedWebCam; } var res = reader.Decode(requestedWebCam.GetPixels32(), requestedWebCam.width, requestedWebCam.height); if (res != null && !string.IsNullOrEmpty(res.Text)) { ILRuntimeHandler.Instance.EmitMessage($"qrcode:{res.Text}"); } }
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(); } } } } }
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-Код отсуствует или не идентифицирован"); } }
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 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> /// 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 }
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; } }
/// <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("上传文件有误。"); }
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())); } }
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 + ""); } } }
/// <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 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); } } }
private DecodeResult CallDecode(BitmapLuminanceSource imageAsLuminance, long singleStart) { var tempResults = new List <Result>(); if (_config.TryMultipleBarcodeTypes) { tempResults = barcodeReader.DecodeMultiple(imageAsLuminance)?.ToList() ?? new List <Result>(); } else { var result = barcodeReader.Decode(imageAsLuminance); tempResults.Add(result); } var mappedResult = new DecodeResult(); if (tempResults.Count > 0) { mappedResult = new DecodeResult(tempResults[0]); } // search for the correct one (that works) if multiple results foreach (var item in tempResults) { if (item == null) { continue; } var encodedData = StandardOutputTransformer.RetrieveNameAndPages(item.Text); if (!string.IsNullOrWhiteSpace(encodedData.Item1) && encodedData.Item2 != 0 && encodedData.Item3 != 0) { mappedResult = new DecodeResult(item); break; } } return(mappedResult); }
/// <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); }
private void openFileDialog_FileOk(object sender, CancelEventArgs e) { txtPath.Text = openFileDialog.FileName; bool IsValid = ValidateFile(txtPath.Text); if (IsValid) { var codeBitMap = (Bitmap) Bitmap.FromFile(txtPath.Text); pictureBox.Image = codeBitMap; IBarcodeReader reader = new BarcodeReader(); var code = reader.Decode(codeBitMap); if (code != null) { lblcode.Text = code.Text.ToString(); } else { lblcode.Text = "*** FAILED ON DECODING A CODE FROM IMAGE ***"; } } else { lblcode.Text = "*** ERROR LOADING VALID IMAGE ***"; } }
private int Decode(Bitmap inputBitmap, bool tryMultipleBarcodes, IList <BarcodeFormat> possibleFormats, int x, int y, float fXMultiplier, float fYMultiplier, out Rectangle rectFound) { rectFound = new Rectangle(); lastResults.Clear(); IList <Result> results = null; var previousFormats = barcodeReader.Options.PossibleFormats; if (possibleFormats != null) { barcodeReader.Options.PossibleFormats = possibleFormats; } if (tryMultipleBarcodes) { results = barcodeReader.DecodeMultiple(inputBitmap); } else { var result = barcodeReader.Decode(inputBitmap); if (result != null) { if (results == null) { results = new List <Result>(); } results.Add(result); } } barcodeReader.Options.PossibleFormats = previousFormats; if (results == null) { return(0); } return(results.Count); }
private void button2_Click(object sender, EventArgs e) { var reader = new ZXing.BarcodeReader(); Result results = reader.Decode(bf); if (results == null) { MessageBox.Show("aucun qr code"); return; } else { try { string decoded = results.ToString().Trim(); cin = decoded.Substring(0, 8); pass = decoded.Substring(8); bunifuFlatButton1.Enabled = true; } catch (Exception exx) { } } }
private void button2_Click(object sender, EventArgs e) { Bitmap imgBarCode = (Bitmap)pictureBox1.Image; if (pictureBox2 != null) { try { ZXing.BarcodeReader Reader = new ZXing.BarcodeReader(); Result result = Reader.Decode(imgBarCode); string decoded = result.ToString().Trim(); if (!listBox1.Items.Contains(decoded)) { listBox1.Items.Insert(0, decoded); } imgBarCode.Dispose(); } catch (Exception ex) { Console.WriteLine(ex.Message + ""); } } }
private Result ScanBitmap(WriteableBitmap writeableBmp) { var barcodeReader = new BarcodeReader { AutoRotate = true, Options = new DecodingOptions { TryHarder = true, // restrict to one or more supported types, if necessary //PossibleFormats = new [] // { // BarcodeFormat.QR_CODE // } } }; var result = barcodeReader.Decode(writeableBmp); if (result != null) { CaptureImage.Source = writeableBmp; } return result; }
private string ReadBarcode() { StorageFolder cameraRoll = KnownFolders.CameraRoll; //cameraRoll .OpenStreamForReadAsync( //string fileName =cameraRoll.Path + "/MyBarcode.jpg"; string fileName = @"C:\Data\Users\Public\Pictures\Camera Roll\MyBarcode.jpg"; if (!File.Exists(fileName)) return ""; //string fileName = @"D:\MyBarcode.png"; ZXing.IBarcodeReader reader = new BarcodeReader(); // load a bitmap //var barcodeBitmap = (BitmapImage)BitmapImage.LoadFrom("C:\\sample-barcode-image.png"); BitmapImage bi = new BitmapImage(new Uri(fileName, UriKind.RelativeOrAbsolute)); WriteableBitmap wb = new WriteableBitmap(bi.PixelWidth, bi.PixelHeight); // detect and decode the barcode inside the bitmap var result = reader.Decode(wb); // do something with the result if (result != null) { //txtDecoderType.Text = result.BarcodeFormat.ToString(); //txtDecoderContent.Text = result.Text; return result.Text; } else return ""; }
void Decode (Android.Graphics.Bitmap image) { try { var reader = new BarcodeReader (); reader.PossibleFormats = new List<BarcodeFormat> () { CurrentFormat }; reader.TryHarder = true; var result = reader.Decode (image); if (result != null) { this.textViewResults.Text = "Result: " + result.Text; } else { this.textViewResults.Text = "No barcode found"; } } catch (Exception ex) { this.textViewResults.Text = ex.ToString(); } }
private static string InternalDecode(Bitmap bmp) { var reader = new BarcodeReader(); var result = reader.Decode(bmp); bmp.Dispose(); return result == null ? null : result.Text; }
/// <summary> /// Декодирование баркода /// Кодируемые и декодированные данные передаются через аттрибуты класса /// </summary> public string Decode() { using (var image = new Image<Gray, Byte>(_bitmap)) { using (Image<Gray, byte> bw = image.Convert(b => (byte) ((b < 128) ? 0 : 255))) { var reader = new BarcodeReader(); Result result = reader.Decode(bw.Bitmap); if (result == null) throw new Exception("Баркод не распознан"); byte[] bytes = Convert.FromBase64String(result.Text); int count = Marshal.SizeOf(typeof (BinaryData)); GCHandle handle = GCHandle.Alloc(bytes, GCHandleType.Pinned); var binaryData = (BinaryData) Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof (BinaryData)); handle.Free(); ArchiverIndex = binaryData.ArchiverIndex; GammaIndex = binaryData.GammaIndex; MixerIndex = binaryData.MixerIndex; EccIndex = binaryData.EccIndex; ExpandSize = binaryData.ExpandSize; EccCodeSize = binaryData.EccCodeSize; EccDataSize = binaryData.EccDataSize; MaximumGamma = (binaryData.MaximumGamma == 0); Key = Encoding.Default.GetString(bytes.ToList().GetRange(count, bytes.Length - count).ToArray()); return ToString(); } } }
private async Task<string> FindQRCodeAsync() { _isStreaming = true; RaisePropertyChanged(nameof(MediaCapture)); await _mediaCapture.StartPreviewAsync(); IsCameraInitialising = false; ShowCameraPreview = true; Result result = null; while (result == null && _isStreaming) { var photoStorageFile = await ApplicationData.Current.TemporaryFolder.CreateFileAsync(DateTime.UtcNow.ToString("yyyMMddHHmmssff"), CreationCollisionOption.GenerateUniqueName); await _mediaCapture.CapturePhotoToStorageFileAsync(ImageEncodingProperties.CreateJpeg(), photoStorageFile); var stream = await photoStorageFile.OpenReadAsync(); var writableBmp = new WriteableBitmap(1, 1); writableBmp.SetSource(stream); writableBmp = new WriteableBitmap(writableBmp.PixelWidth, writableBmp.PixelHeight); stream.Seek(0); writableBmp.SetSource(stream); var barcodeReader = new BarcodeReader { AutoRotate = true }; barcodeReader.Options.TryHarder = true; try { result = barcodeReader.Decode(writableBmp); } catch (IndexOutOfRangeException) { continue; } catch (UnauthorizedAccessException) { continue; } finally { await photoStorageFile.DeleteAsync(StorageDeleteOption.PermanentDelete); } } if (result != null) { return result.Text; } else { return ""; } }
public static void PostProcessStep2(ScannedImage image, Bitmap bitmap, ScanProfile profile, ScanParams scanParams, int pageNumber) { if (!profile.UseNativeUI && profile.BrightnessContrastAfterScan) { if (profile.Brightness != 0) { AddTransformAndUpdateThumbnail(image, new BrightnessTransform { Brightness = profile.Brightness }); } if (profile.Contrast != 0) { AddTransformAndUpdateThumbnail(image, new TrueContrastTransform { Contrast = profile.Contrast }); } } if (profile.FlipDuplexedPages && pageNumber % 2 == 0) { AddTransformAndUpdateThumbnail(image, new RotationTransform(RotateFlipType.Rotate180FlipNone)); } if (scanParams.DetectPatchCodes && image.PatchCode == PatchCode.None) { IBarcodeReader reader = new BarcodeReader(); var barcodeResult = reader.Decode(bitmap); if (barcodeResult != null) { switch (barcodeResult.Text) { case "PATCH1": image.PatchCode = PatchCode.Patch1; break; case "PATCH2": image.PatchCode = PatchCode.Patch2; break; case "PATCH3": image.PatchCode = PatchCode.Patch3; break; case "PATCH4": image.PatchCode = PatchCode.Patch4; break; case "PATCH6": image.PatchCode = PatchCode.Patch6; break; case "PATCHT": image.PatchCode = PatchCode.PatchT; break; } } } }
private void DecodeBarcode() { var reader = new BarcodeReader(); while (true) { if (currentBitmapForDecoding != null) { var result = reader.Decode(currentBitmapForDecoding); if (result != null) { Invoke(new Action<Result>(ShowResult), result); } else this.Invoke(new Action<Color>(PaintColor), Color.Yellow); if ((_iFrameCount % 2) == 0) { motionLevel = motionDetector.ProcessFrame(currentBitmapForDecoding); // Debug.WriteLine("level=" + motionLevel.ToString()); if (motionLevel > AWAKE_LEVEL) { BeginInvoke(new Action(RefreshLastText)); } BeginInvoke(new Action<float>(DisplayMotionLevel), new object [] {motionLevel}); } _iFrameCount++; currentBitmapForDecoding.Dispose(); currentBitmapForDecoding = null; } int nInterval = 1000; if (motionLevel > AWAKE_LEVEL) nInterval = 200; // 200 #if NO if (motionLevel > 0.5) nInterval = 200; // 200 #endif Thread.Sleep(nInterval); } }
private void RecognizeBarCode(BarCodeRule rule) { Pixbuf WorkImage = Images[0]; RelationalRectangle WorkZone = rule.Box.Clone(); WorkZone.SetTarget(WorkImage.Width, WorkImage.Height); logger.Debug("Зона штрихкода, box: x={0},y={1},w={2},h={3}", WorkZone.PosX, WorkZone.PosY, WorkZone.Width, WorkZone.Heigth); var cutedPixbuf = new Pixbuf(WorkImage, WorkZone.PosX, WorkZone.PosY, WorkZone.Width, WorkZone.Heigth); ShowImage (cutedPixbuf, "Зона штрихкода"); // create a barcode reader instance IBarcodeReader reader = new BarcodeReader(); // load a bitmap var barcodeBitmap = RecognizeHelper.PixbufToBitmap (cutedPixbuf); // detect and decode the barcode inside the bitmap var result = reader.Decode(barcodeBitmap); // do something with the result if (result != null) { logger.Debug ("Формат штрих кода: {0}", result.BarcodeFormat.ToString ()); logger.Debug ("Текст штрих кода разпознан как: {0}", result.Text); rule.ParseCode (Doc, result.BarcodeFormat, result.Text); } else logger.Warn ("Штрих код не распознан."); }
private void button1_Click(object sender, EventArgs e) { Thread.Sleep(3000); while (true) { using (var bmp = CaptureApplication("QRpuzzle")) { var chunks = Split( 18, 77, 160, 167, 6, 13, 3, bmp); var result = Bundle.Reconstruct(chunks, 3); IBarcodeReader reader = new BarcodeReader { PossibleFormats = new[] { BarcodeFormat.QR_CODE }, TryHarder = true }; result.Save("Test2.png"); var code = reader.Decode(result); SendKeys.Send(code.Text); Thread.Sleep(500); } } }
void DecodeQR() { // create a reader with a custom luminance source var barcodeReader = new BarcodeReader {AutoRotate = false, TryHarder = false}; while (true) { if (isQuit) break; try { // decode the current frame var result = barcodeReader.Decode(c, W, H); if (result != null) { LastResult = result.Text; shouldEncodeNow = true; print(result.Text); } // Sleep a little bit and set the signal to get the next frame Thread.Sleep(200); c = null; } catch { } } }
//private Result ScanQRCode(WriteableBitmap writeableBmp) //{ // var barcodeReader = new BarcodeReader // { // TryHarder = true, // AutoRotate = true // }; // var result = barcodeReader.Decode(writeableBmp); // if (result != null) // { // Debug.WriteLine(result.Text); // } // return result; //} private async Task<Result> ScanQRCodeAsync(WriteableBitmap writeableBitmap) { 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(writeableBitmap); }); return res; }
private void ReadMyBarcode(Stream imageStream) { ZXing.IBarcodeReader reader = new BarcodeReader(); BitmapImage bi = new BitmapImage(); bi.SetSource(imageStream ); WriteableBitmap wb = new WriteableBitmap(bi); var result = reader.Decode(wb); if (result != null) { //MessageBox.Show(result.Text); ActionAfterBCScanned(true, result.Text, IsForParked); imageStream.Close(); NavigationService.GoBack(); } else { MessageBox.Show("Unable to Decode the Barcode, Try again."); } }
//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; }