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;
        }
Beispiel #2
3
 /// <summary>
 /// 
 /// </summary>
 /// <param name="code"></param>
 /// <param name="size"></param>
 /// <returns></returns>
 public static Bitmap ToImage(string code, int size = 180)
 {
     BarcodeWriter writer = new BarcodeWriter();
     QrCodeEncodingOptions qr = new QrCodeEncodingOptions()
     {
         CharacterSet = "UTF-8",
         ErrorCorrection = ZXing.QrCode.Internal.ErrorCorrectionLevel.H,
         Height = size,
         Width = size,
     };
     writer.Options = qr;
     writer.Format = BarcodeFormat.QR_CODE;
     Bitmap bitmap = writer.Write(code);
     return bitmap;
 }
Beispiel #3
3
 static void DrawCode(string code, ImageView barcode)
 {
     var writer = new BarcodeWriter
     {
         Format = BarcodeFormat.CODE_39,
         Options = new EncodingOptions
         {
             Height = 200,
             Width = 600
         }
     };
     var bitmap = writer.Write(code);
     Drawable img = new BitmapDrawable(bitmap);
     barcode.SetImageDrawable(img);
 }
        /// <summary>
        /// 生成二维码图片
        /// </summary>
        /// <param name="contents">要生成二维码包含的信息</param>
        /// <param name="width">生成的二维码宽度(默认300像素)</param>
        /// <param name="height">生成的二维码高度(默认300像素)</param>
        /// <returns>二维码图片</returns>
        public static Bitmap GeneratorQrCodeImage(string contents, int width = 300, int height = 300)
        {
            if (string.IsNullOrEmpty(contents))
            {
                return null;
            }

            EncodingOptions options = null;
            BarcodeWriter writer = null;
            options = new QrCodeEncodingOptions
            {
                DisableECI = true,
                CharacterSet = "UTF-8",
                Width = width,
                Height = height,
                ErrorCorrection = ErrorCorrectionLevel.H,
                //控制二维码图片的边框
                Margin = 0
            };
            writer = new BarcodeWriter
            {
                Format = BarcodeFormat.QR_CODE,
                Options = options
            };

            Bitmap bitmap = writer.Write(contents);

            return bitmap;
        }
Beispiel #5
0
        private void button1_Click_1(object sender, EventArgs e)
        {
            if (String.IsNullOrEmpty(id_srch.Text) || String.IsNullOrEmpty(id_srch.Text))
            {
                qr_code.Image = null;
                MessageBox.Show("Text not found", "Oops!", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else
            {
                var qr = new ZXing.BarcodeWriter();
                qr.Options = options;
                qr.Format  = ZXing.BarcodeFormat.QR_CODE;
                var result = new Bitmap(qr.Write(id_srch.Text.Trim()));
                qr_code.Image = result;
            }

            prof_photoMang_cpy.Image    = prof_photoMang.Image;
            prof_photoMang_cpy.SizeMode = PictureBoxSizeMode.StretchImage;
            qr_code_cpy.Image           = qr_code.Image;
            id_srch_cpy.Text            = id_srch.Text;
            name2_cpy.Text           = name2.Text;
            dateTimePicker2_cpy.Text = dateTimePicker2.Text;
            occupS_cpy.Text          = occupS.Text;
            MaritS_cpy.Text          = MaritS.Text;
        }
		public virtual Stream Create(BarCodeCreateConfiguration cfg) {
#if __ANDROID__
            var writer = new ZXing.BarcodeWriter {
				Format = (BarcodeFormat)Enum.Parse(typeof(BarcodeFormat), cfg.Format.ToString()),
                Encoder = new MultiFormatWriter(),
                Options = new EncodingOptions {
					Height = cfg.Height,
					Margin = cfg.Margin,
					Width = cfg.Height,
					PureBarcode = cfg.PureBarcode
                }
            };
#endif
#if __IOS__
            var writer = new ZXing.Mobile.BarcodeWriter
            {
                Format = (BarcodeFormat)Enum.Parse(typeof(BarcodeFormat), cfg.Format.ToString()),
                Encoder = new MultiFormatWriter(),
                Options = new EncodingOptions
                {
                    Height = cfg.Height,
                    Margin = cfg.Margin,
                    Width = cfg.Height,
                    PureBarcode = cfg.PureBarcode
                }
            };
#endif
            return this.ToImageStream(writer, cfg);
        }
Beispiel #7
0
        private async void Update()
        {
            var writer1 = new BarcodeWriter
            {
                Format = BarcodeFormat.QR_CODE,
                Options = new ZXing.Common.EncodingOptions
                {
                    Height = 200,
                    Width = 200
                },

            };

            var image = writer1.Write(Text);//Write(text);


            using (InMemoryRandomAccessStream ms = new InMemoryRandomAccessStream())
            {
                using (DataWriter writer = new DataWriter(ms.GetOutputStreamAt(0)))
                {
                    writer.WriteBytes(image);
                    await writer.StoreAsync();
                }

                var output = new BitmapImage();
                await output.SetSourceAsync(ms);
                ImageSource = output;
            }


        }
Beispiel #8
0
		public override UITableViewCell GetCell (UITableView tv)
		{
			var cell = tv.DequeueReusableCell(this.CellKey);
			UIImageView iv = null;

			if (cell == null)
			{
				cell = new UITableViewCell(UITableViewCellStyle.Default, this.CellKey);

				iv = new UIImageView(new RectangleF(10f, 5f, tv.Bounds.Width - 20f, this.MaxHeight - 10f));
				iv.Tag = 101;
				iv.ContentMode = UIViewContentMode.ScaleAspectFit;

				cell.AddSubview(iv);

			}
			else
			{
				iv = cell.ViewWithTag(101) as UIImageView;

			}

			if (this.barcodeImg == null)
			{
				var writer = new BarcodeWriter() { Format = this.format };
				this.barcodeImg = writer.Write(this.value);
			}

			iv.Image = this.barcodeImg;

			return cell;
		}
Beispiel #9
0
        public static BitmapSource GetQrCodeImage(string qrValue)
        {
            var barcodeWriter = new BarcodeWriter
            {
                Format = BarcodeFormat.QR_CODE,
                Options = new EncodingOptions
                {
                    Height = 300,
                    Width = 300,
                    Margin = 1
                }
            };

            using (var bMap = barcodeWriter.Write(qrValue))
            {
                var hbmp = bMap.GetHbitmap();
                try
                {
                    var source = Imaging.CreateBitmapSourceFromHBitmap(hbmp, IntPtr.Zero, Int32Rect.Empty,
                        BitmapSizeOptions.FromEmptyOptions());
                    // QRCode.Source = source;
                    // QrCodeImage = source;
                    return source;
                }
                finally
                {
                    // DeleteObject(hbmp); // TODO huh? what or where is DeleteObject ???

                }
            }
        }
Beispiel #10
0
        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                var qr = new ZXing.BarcodeWriter();//new instance of a barcodewriter class
                qr.Options = options;
                qr.Format  = ZXing.BarcodeFormat.QR_CODE;
                var result = new Bitmap(qr.Write(textBox1.Text.Trim()));
                Img.Image = result;
                Bitmap bmp1 = new Bitmap(Img.Image);
                //Bitmap bmp2 = new Bitmap(ImgThumb.Image);
                System.Drawing.ImageConverter ic = new System.Drawing.ImageConverter();
                byte[] btImage1 = new byte[1];
                btImage1 = (byte[])ic.ConvertTo(bmp1, btImage1.GetType());
                // byte[] img = ReadImageFile(label6.Text);

                SaveFileDialog save = new SaveFileDialog();
                save.CreatePrompt    = true;
                save.OverwritePrompt = true;
                save.FileName        = textBox1.Text;
                save.Filter          = "PNG|*.png|JPEG|*.jpg|BMP|*.bmp|GIF|*.gif";
                if (save.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    Img.Image.Save(save.FileName);
                    save.InitialDirectory = Environment.GetFolderPath
                                                (Environment.SpecialFolder.Desktop);
                }
                MessageBox.Show("Register Successfully");
            }
            catch (Exception ex)
            {
                MessageBox.Show("Enter Correct Value");
            }
        }
        public Bitmap GenerateQR(int width, int height, string text)
        {
            var bw = new ZXing.BarcodeWriter();

            var encOptions = new ZXing.Common.EncodingOptions
            {
                Width       = width,
                Height      = height,
                Margin      = 0,
                PureBarcode = false
            };

            encOptions.Hints.Add(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);

            bw.Renderer = new BitmapRenderer();
            bw.Options  = encOptions;
            bw.Format   = ZXing.BarcodeFormat.QR_CODE;
            Bitmap bm          = bw.Write(text);
            Bitmap overlay     = new Bitmap(imagePath);
            int    deltaHeigth = bm.Height - overlay.Height;
            int    deltaWidth  = bm.Width - overlay.Width;

            Graphics g = Graphics.FromImage(bm);

            g.DrawImage(overlay, new Point(deltaWidth / 2, deltaHeigth / 2));

            return(bm);
        }
Beispiel #12
0
        private void btn_Registration_Click_1(object sender, EventArgs e)
        {
            //QR코드 생성
            ZXing.BarcodeWriter barcodeWriter = new ZXing.BarcodeWriter();
            barcodeWriter.Format = ZXing.BarcodeFormat.QR_CODE;

            barcodeWriter.Options.Width  = this.pictureBox_QR.Width;
            barcodeWriter.Options.Height = this.pictureBox_QR.Height;

            string strQRCode = tb_ENT_NO.Text.ToString();

            //strQRCode += tb_Pname.Text.ToString();

            this.pictureBox_QR.Image = barcodeWriter.Write(strQRCode);
            string deskPath = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);

            barcodeWriter.Write(strQRCode).Save(deskPath + @"\" + strQRCode + ".jpg");

            //생성된 QR코드 DB에 저장
            MemoryStream ms = new MemoryStream();

            pictureBox_QR.Image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
            byte[] img = ms.ToArray();
            cmd.CommandText = " UPDATE ENTERING SET ENT_BARCODE = @img WHERE ENT_NO = '" + tb_ENT_NO.Text + "'";
            cmd.Parameters.Add("@img", MySqlDbType.LongBlob);
            cmd.Parameters["@img"].Value = img;
            cmd.ExecuteNonQuery();
            //System.IO.File.Delete(deskPath + @"\test.jpg");
        }
Beispiel #13
0
        public ImageSource createQR(string tekst, int wymiar)
        {
            if (tekst == "")
            {
                //pictureBox1.Image = null;
                System.Windows.Forms.MessageBox.Show("Text not found", "Oops!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return(null);
            }
            else
            {
                options.Width  = wymiar;
                options.Height = wymiar;
                var qr = new ZXing.BarcodeWriter();
                qr.Options = options;
                qr.Format  = ZXing.BarcodeFormat.QR_CODE;
                var         result = new Bitmap(qr.Write(tekst.Trim()));
                ImageSource tmp    = ImageSourceForBitmap(result);
                try
                {
                    ((EditItems)System.Windows.Application.Current.MainWindow).Qrimage.Source = tmp;
                }
                catch (Exception)
                {
                }

                return(tmp);
            }
        }
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            int a = tbctrl.SelectedIndex;

            if (a == 0)
            {
                if (txt != null & txt != "")
                {
                    try
                    {
                        var bw         = new ZXing.BarcodeWriter();
                        var encOptions = new ZXing.Common.EncodingOptions()
                        {
                            Width = Convert.ToInt32(hw), Height = Convert.ToInt32(hw), Margin = 0
                        };
                        bw.Options = encOptions;
                        bw.Format  = ZXing.BarcodeFormat.QR_CODE;
                        //string text = "BEGIN:VCARD VERSION:3.0 N:Derlysh;Ilya;V TITLE:Chief of information security TEL;TYPE=work:+4956835753 TEL;TYPE=cell:+79039705658 EMAIL;TYPE=INTERNET:[email protected] END:VCARD";
                        var result = new Bitmap(bw.Write(txt));
                        System.Windows.Controls.Image i = new System.Windows.Controls.Image();
                        result.SetResolution(Convert.ToInt32(dpi), Convert.ToInt32(dpi));
                        result.Save(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\" + nm + ".jpg");
                        MessageBox.Show("Выполнено!");
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.ToString());
                    }
                }
                else
                {
                    MessageBox.Show("Нет данных!");
                }
            }
            else
            {
                try
                {
                    var bw         = new ZXing.BarcodeWriter();
                    var encOptions = new ZXing.Common.EncodingOptions()
                    {
                        Width = Convert.ToInt32(hw), Height = Convert.ToInt32(hw), Margin = 0
                    };
                    bw.Options = encOptions;
                    bw.Format  = ZXing.BarcodeFormat.QR_CODE;
                    //string text = "BEGIN:VCARD VERSION:3.0 N:Derlysh;Ilya;V TITLE:Chief of information security TEL;TYPE=work:+4956835753 TEL;TYPE=cell:+79039705658 EMAIL;TYPE=INTERNET:[email protected] END:VCARD";
                    bw.Options.Hints.Add(EncodeHintType.CHARACTER_SET, "UTF-8");
                    bw.Options.Hints.Add(EncodeHintType.DISABLE_ECI, true);
                    var result = new Bitmap(bw.Write(card.generate()));
                    System.Windows.Controls.Image i = new System.Windows.Controls.Image();
                    result.SetResolution(Convert.ToInt32(dpi), Convert.ToInt32(dpi));
                    result.Save(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\" + nm + ".jpg");
                    MessageBox.Show("Выполнено!");
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.ToString());
                }
            }
        }
Beispiel #15
0
        private async void Update()
        {
            var writer1 = new BarcodeWriter
            {
                Format  = BarcodeFormat.QR_CODE,
                Options = new ZXing.Common.EncodingOptions
                {
                    Height = 200,
                    Width  = 200
                },
            };

            var image = writer1.Write(Text);//Write(text);


            using (InMemoryRandomAccessStream ms = new InMemoryRandomAccessStream())
            {
                using (DataWriter writer = new DataWriter(ms.GetOutputStreamAt(0)))
                {
                    writer.WriteBytes(image);
                    await writer.StoreAsync();
                }

                var output = new BitmapImage();
                await output.SetSourceAsync(ms);

                ImageSource = output;
            }
        }
        private void Button1_Click(object sender, EventArgs e)
        {
            QrCodeEncodingOptions options = new QrCodeEncodingOptions
            {
                DisableECI   = true,
                CharacterSet = "UTF-8",
                Width        = 250,
                Height       = 250,
            };
            var writer = new BarcodeWriter();

            writer.Format  = BarcodeFormat.QR_CODE;
            writer.Options = options;

            if (String.IsNullOrWhiteSpace(textBox1.Text) || String.IsNullOrEmpty(textBox1.Text))
            {
                pictureBox1.Image = null;
                MessageBox.Show("Text not found", "Oops!", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else
            {
                var qr = new ZXing.BarcodeWriter();
                qr.Options = options;
                qr.Format  = ZXing.BarcodeFormat.QR_CODE;
                var result = new Bitmap(qr.Write(textBox1.Text.Trim()));
                pictureBox1.Image = result;
            }
        }
Beispiel #17
0
        private void loadData()
        {
            IDPhong = Common.getIDPhong().ToString();
            ///lấy ID phòng null
            if (String.IsNullOrEmpty(IDPhong))
            {
                return;
            }
            Token = RandomString(8);
            InsertToken(IDPhong, Token);

            QrCodeEncodingOptions options = new QrCodeEncodingOptions();

            options = new QrCodeEncodingOptions
            {
                DisableECI   = true,
                CharacterSet = "UTF-8",
                Width        = 800,
                Height       = 800,
            };
            IDPhong = HeThong.Common.getIDPhong().ToString();
            var qr = new ZXing.BarcodeWriter();

            qr.Options = options;
            qr.Format  = ZXing.BarcodeFormat.QR_CODE;
            Token      = getToken(IDPhong);
            String tmp = IDPhong + "," + Token;

            btnChangeToken.Text = Token;
            var result = new Bitmap(qr.Write(tmp));

            imgBarcode.Image = result;
            txtPhong.Text    = (from a in db.DiaDiemHocs where a.ID == int.Parse(IDPhong) select a.TenDiaDiem).Single().ToString();
            lueLopMonHoc.Properties.DataSource = db.getDSLopHocTheoNgay(int.Parse(IDPhong));
        }
Beispiel #18
0
        public static HtmlString GenerateQrCode(this HtmlHelper html, string groupName, int height = 250, int width = 250, int margin = 0)
        {
            var qrValue = groupName;
            var barcodeWriter = new ZXing.BarcodeWriter
            {
                Format = BarcodeFormat.QR_CODE,
                Options = new EncodingOptions
                {
                    Height = height,
                    Width = width,
                    Margin = margin
                }
            };

            using (var bitmap = barcodeWriter.Write(qrValue))
            using (var stream = new MemoryStream())
            {
                bitmap.Save(stream, ImageFormat.Png);

                var img = new TagBuilder("img");
                img.MergeAttribute("alt", "QR Code를 스캔하면 관련 정보를 확인 할 수 있습니다");
                img.MergeAttribute("title", "QR Code를 스캔하면 관련 정보를 확인 할 수 있습니다");
                img.Attributes.Add("src", String.Format("data:image/gif;base64,{0}",
                    Convert.ToBase64String(stream.ToArray())));

                return MvcHtmlString.Create(img.ToString(TagRenderMode.SelfClosing));
            }
        }
Beispiel #19
0
        private void ViewBarCode()
        {
            PrintTemplateModel model = new PrintTemplateHelper().GetConfig();

            if (model == null)
            {
                MessageBox.Show("打印模板参数获取失败!");
                return;
            }

            var      paperWidth  = model.PageWidth * printMultiple;
            var      paperHeight = model.PageHeight * printMultiple;
            Bitmap   image       = new Bitmap(paperWidth, paperHeight);
            Graphics g           = Graphics.FromImage(image);

            System.Drawing.Brush bush = new SolidBrush(System.Drawing.Color.Black);//填充的颜色

            try
            {
                //消除锯齿
                g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
                g.PageUnit      = GraphicsUnit.Pixel;
                //清空图片背景颜色
                g.Clear(System.Drawing.Color.White);

                var code = "1231125-102-23";

                #region PDF417
                PDF417EncodingOptions pdf_options = new PDF417EncodingOptions
                {
                    Margin       = 0,
                    DisableECI   = true,
                    CharacterSet = "UTF-8",
                    Width        = ConvertInt(model.BarCodeWidth),
                    Height       = ConvertInt(model.BarCodeHeight),
                    PureBarcode  = false
                };
                var pdf417Writer = new ZXing.BarcodeWriter();
                pdf417Writer.Format  = BarcodeFormat.PDF_417;
                pdf417Writer.Options = pdf_options;
                #endregion

                Bitmap bmp = pdf417Writer.Write(code);

                // Bitmap bmp = CreateImg.GenerateBitmap(code, 5, 5);
                g.DrawImage(bmp, ConvertInt(model.BarCodeX), ConvertInt(model.BarCodeY), ConvertInt(model.BarCodeWidth), ConvertInt(model.BarCodeHeight));

                IntPtr       myImagePtr = image.GetHbitmap();                                                                                                                           //创建GDI对象,返回指针
                BitmapSource imgsource  = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(myImagePtr, IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions()); //创建imgSource

                DeleteObject(myImagePtr);

                imgTest.Source = imgsource;
            }
            finally
            {
                g.Dispose();
                image.Dispose();
            }
        }
        private void GenerateBarcode(string barcode)
        {
            try
            {
                //


                var writer = new ZXing.BarcodeWriter
                {
                    Format = BarcodeFormat.CODE_128
                };
                Bitmap bitmap = writer.Write(barcode);

                usp_tblStatusMasterGetByType_Result result = InventoryEntities.usp_tblStatusMasterGetByType(8).FirstOrDefault();
                string sPath = result.statusDesc;


                using (MemoryStream Mmst = new MemoryStream())
                {
                    //bitm.Save("ms", ImageFormat.Jpeg);
                    bitmap.Save(sPath + barcode + ".png");
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        public static IHtmlString GenerateMatrixCodeLabelSm(this HtmlHelper html, string inputentry, int height = 144, int width = 144, int margin = 0)
        {
            var qrValue = inputentry + "          "; // 10 trailing spaces added to guard against unpredictabilty.
            var barcodeWriter = new BarcodeWriter
            {
                Format = BarcodeFormat.DATA_MATRIX,
                Options = new EncodingOptions
                {
                    Height = height,
                    Width = width,
                    Margin = margin
                }
            };

            using (var bitmap = barcodeWriter.Write(qrValue))
            using (var stream = new MemoryStream())
            {
                bitmap.Save(stream, ImageFormat.Gif);

                var img = new TagBuilder("img");
                img.MergeAttribute("alt", "matrix barcode");
                img.Attributes.Add("src", String.Format("data:image/gif;base64,{0}",
                    Convert.ToBase64String(stream.ToArray())));

                return MvcHtmlString.Create(img.ToString(TagRenderMode.SelfClosing));
            }
        }
        public override void ViewDidLoad()
        {
            base.ViewDidLoad ();
            lblResult.Text = "";

            txInput.Text = "http://thinkpower.info/xamarin/cn/";

            //扫描条码
            btnScan.TouchUpInside += async (sender, e) => {
                var scanner = new ZXing.Mobile.MobileBarcodeScanner();
                var result = await scanner.Scan();

                if (result != null)
                    this.lblResult.Text = result.Text;
            };

            //产生条码
            btnGenerateBarCode.TouchUpInside += (sender, e) => {
                txInput.ResignFirstResponder();
                var writer = new BarcodeWriter
                {
                    Format = BarcodeFormat.QR_CODE

                };
                var bitmap = writer.Write(txInput.Text);
                this.img_code.Image = bitmap;
            };
        }
        public HttpResponseMessage GetCode128(string value, int? height = null)
        {
            if (value == null || value.Length == 1 || value.Length > 80) {
                var errorResponse = new HttpResponseMessage(HttpStatusCode.BadRequest) {
                    Content = new StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(new { Error = "Value must be between 1 and 80 characters." })),
                };
                return errorResponse;
            }

            var response = new HttpResponseMessage();
            var writer = new BarcodeWriter() {
                Format = BarcodeFormat.CODE_128,
            };
            if (height.HasValue) {
                writer.Options.Hints[ZXing.EncodeHintType.HEIGHT] = height.Value;
            }

            Bitmap barcodeBitmap = writer.Write(value);
            using (var pngStream = new MemoryStream()) {
                barcodeBitmap.Save(pngStream, ImageFormat.Png);
                response.Content = new ByteArrayContent(pngStream.ToArray());
                response.Content.Headers.ContentType = new MediaTypeHeaderValue("image/png");
                return response;
            }
        }
Beispiel #24
0
        private void button12_Click(object sender, EventArgs e)
        {
            double pht      = 0;
            double totalPHT = 0;

            for (int count = 0; count < dataGridView1.Rows.Count; count++)
            {
                pht       = Convert.ToDouble(dataGridView1.Rows[count].Cells["Column4"].Value) * Convert.ToDouble(dataGridView1.Rows[count].Cells["Column3"].Value);
                totalPHT += pht;
            }

            double mntTVA = totalPHT * 0.2;
            double TTC    = mntTVA + totalPHT;

            ado.cmd.CommandText = "insert into facture_frs(idf_frs,                      date_fac_frs, total_pht_fac_frs, taux_tva_fac_frs, montant_tva_fac_frs, total_ttc_fac_frs) values (" +
                                  int.Parse(textBox2.Text) + "," + dateTimePicker1.Text + " ," + totalPHT + ",      " + 20 + ",                " + mntTVA + ", " + TTC + ")";

            ado.cmd.Connection = ado.cn;
            ado.cmd.ExecuteNonQuery();

            ado.cmd.CommandText = "select max(idf_fac_frs) as last from facture_frs";
            ado.cmd.Connection  = ado.cn;
            ado.dr = ado.cmd.ExecuteReader();
            while (ado.dr.Read())
            {
                lastFact = int.Parse(ado.dr["last"].ToString());
            }
            ado.dr.Close();
            int rayon    = int.Parse(comboBox1.Text);
            int rowCount = dataGridView1.Rows.Count;

            for (int i = 0; i < rowCount; i++)
            {
                var qr = new ZXing.BarcodeWriter();
                qr.Options = options;
                qr.Format  = ZXing.BarcodeFormat.QR_CODE;
                var    result  = new Bitmap(qr.Write(dataGridView1.Rows[i].Cells[0].Value.ToString().Trim()));
                var    res2    = imageToByteArray(result);
                var    img2str = Convert.ToBase64String(res2);
                string design  = dataGridView1.Rows[i].Cells[0].Value.ToString();

                qtt = Retrieve(design);
                int qttnv = qtt + int.Parse(dataGridView1.Rows[i].Cells[1].Value.ToString());
                ado.cmd.CommandText = "update article set idf_rayon = " + rayon + " ,qte_stock = " + qttnv + " ,prix_ht_stock = " + float.Parse(dataGridView1.Rows[i].Cells[3].Value.ToString()) + ",taux_TVA = " + int.Parse(dataGridView1.Rows[i].Cells[4].Value.ToString()) + " ,qr ='" + img2str + "' where design_art = '" + dataGridView1.Rows[i].Cells[0].Value.ToString() + "'";


                ado.cmd.Connection = ado.cn;
                ado.cmd.ExecuteNonQuery();

                int lastIdArt = RetrieveId();

                ado.cmd.CommandText = "insert into ligne_fac_frs(ref_art,idf_fac_frs,qte_achete,prix_achat) values (" +
                                      lastIdArt + "," +
                                      lastFact + "," + int.Parse(dataGridView1.Rows[i].Cells[2].Value.ToString()) + "," +
                                      int.Parse(dataGridView1.Rows[i].Cells[3].Value.ToString()) + ")";
            }
            MessageBox.Show("ajout terminer");
            vider();
            dataGridView1.Rows.Clear();
        }
        public static IHtmlString GenerateRelayQrCode(this HtmlHelper html, string alt, string value, int height = 250, int width = 250, int margin = 0)
        {
            var barcodeWriter = new BarcodeWriter
            {
                Format = BarcodeFormat.QR_CODE,
                Options = new EncodingOptions
                {
                    Height = height,
                    Width = width,
                    Margin = margin
                }
            };

            using (var bitmap = barcodeWriter.Write(value))
            using (var stream = new MemoryStream())
            {
                bitmap.Save(stream, ImageFormat.Gif);

                var img = new TagBuilder("img");
                img.MergeAttribute("alt", alt);
                img.Attributes.Add("src", String.Format("data:image/gif;base64,{0}",
                    Convert.ToBase64String(stream.ToArray())));

                return MvcHtmlString.Create(img.ToString(TagRenderMode.SelfClosing));
            }
        }
Beispiel #26
0
        public static System.Drawing.Bitmap CreateImage(string content, string format, int width, int height, bool pureBarcode, string fontName, float fontSize)
        {
            var writer = new ZXing.BarcodeWriter
            {
                Format  = (BarcodeFormat)(Enum.Parse(typeof(BarcodeFormat), format)),
                Options = new ZXing.Common.EncodingOptions
                {
                    Height      = height,
                    Width       = width,
                    Margin      = 0,
                    PureBarcode = pureBarcode,
                }
            };

            if (writer.Renderer is ZXing.Rendering.BitmapRenderer)
            {
                ((ZXing.Rendering.BitmapRenderer)writer.Renderer).TextFont = new System.Drawing.Font(fontName, fontSize <= 0 ? 12 : fontSize);
            }
            else if (writer.Renderer is ZXing.Rendering.WriteableBitmapRenderer)
            {
                ((ZXing.Rendering.WriteableBitmapRenderer)writer.Renderer).FontFamily = new System.Windows.Media.FontFamily(fontName); ((ZXing.Rendering.WriteableBitmapRenderer)writer.Renderer).FontSize = fontSize <= 0 ? 12 : fontSize;
            }
            var data = writer.Encode(content);

            System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(data.Width, data.Height);

            for (int x = 0; x < data.Width; x++)
            {
                for (int y = 0; y < data.Height; y++)
                {
                    bitmap.SetPixel(x, y, data[x, y] ? System.Drawing.Color.Black : System.Drawing.Color.White);
                }
            }
            return(bitmap);
        }
Beispiel #27
0
        /// <summary>
        ///         Trả về file name (path) của ảnh tạo ra bởi ZXing library (temp file)
        /// </summary>
        /// <param name="Text">Văn bản cần sinh mã QR</param>
        /// <param name="ImageSize">Kích thước của ảnh QR. Tối đa là 500 px</param>
        /// <param name="Correction">Mức độ chịu lỗi</param>
        /// <param name="Margin">Số điểm ảnh trắng để làm biên </param>
        /// <returns></returns>
        static string GetQRCodeLocalFileNameByZXing(string Text, int ImageSize = 500, CorrectionLevel Correction = CorrectionLevel.High, int Margin = 0)
        {
            QRCodeWriter qr = new ZXing.QrCode.QRCodeWriter(); //QRCode as a BitMatrix 2D array

            Dictionary <EncodeHintType, object> hint = new Dictionary <EncodeHintType, object>();

            hint.Add(EncodeHintType.MARGIN, Margin); // margin of the QRCode image
            hint.Add(EncodeHintType.ERROR_CORRECTION, Correction);

            var matrix = qr.encode(Text, BarcodeFormat.QR_CODE, ImageSize, ImageSize, hint); // encode QRCode matrix from source text

            ZXing.BarcodeWriter w = new ZXing.BarcodeWriter();
            Bitmap img            = w.Write(matrix);                    // QRCode Bitmap image
            string tempFile       = Path.GetTempFileName();             //create a temp file to save QRCode image

            img.Save(tempFile, System.Drawing.Imaging.ImageFormat.Png); //save QRCode image to temp file


            //old one - use clipboard
            //MemoryStream ms = new MemoryStream();
            //img.Save(ms, System.Drawing.Imaging.ImageFormat.Png); //save QRCode image to memory stream
            //System.Drawing.Image i = System.Drawing.Image.FromStream(ms); // create image in Image form
            //Clipboard.SetDataObject(i);// set image to clipboard



            return(tempFile);
        }
Beispiel #28
0
        private static void ProcessLabelItem(LabelItem labelItem, Graphics g, PrintLabelSettings settings)
        {
            switch (labelItem.LabelType)
            {
                case LabelTypesEnum.Label:
                    g.DrawString(labelItem.LabelText,
                        new Font(labelItem.FontName ?? "Arial", labelItem.FontSize, (labelItem.IsBold ? FontStyle.Bold : FontStyle.Regular) | (labelItem.IsItalic ? FontStyle.Italic : FontStyle.Regular)),
                        Brushes.Black, labelItem.StartX, labelItem.StartY);
                    break;
                case LabelTypesEnum.BarCode:
                    var content = labelItem.LabelText;

                    var writer = new BarcodeWriter
                    {
                        Format = BarcodeFormat.CODE_128,
                        Options = new ZXing.QrCode.QrCodeEncodingOptions
                        {
                            ErrorCorrection = ZXing.QrCode.Internal.ErrorCorrectionLevel.H,
                            Width = settings.BarCodeMaxWidth,
                            Height = settings.BarCodeHeight,
                            PureBarcode = true,
                        }
                    };
                    var barCodeBmp = writer.Write(content);
                    g.DrawImageUnscaled(barCodeBmp, labelItem.StartX, labelItem.StartY);
                    break;
                case LabelTypesEnum.Stamp:
                    var pen = new Pen(Color.Black, 2);
                    g.DrawEllipse(pen, labelItem.StartX, labelItem.StartY, settings.StampDiameter, settings.StampDiameter);
                    g.DrawString(labelItem.LabelText,
                        new Font(labelItem.FontName ?? "Arial", labelItem.FontSize, (labelItem.IsBold ? FontStyle.Bold : FontStyle.Regular) | (labelItem.IsItalic ? FontStyle.Italic : FontStyle.Regular)),
                        Brushes.Black, labelItem.StartX + 2, labelItem.StartY + 11);
                    break;
            }
        }
Beispiel #29
0
        //https://www.codeproject.com/Articles/1005081/Basic-with-QR-Code-using-Zxing-Library
        public byte[] GenerateQRCode(string text = "")
        {
            QrCodeEncodingOptions options;

            options = new QrCodeEncodingOptions
            {
                DisableECI   = true,
                CharacterSet = "UTF-8",
                Width        = 250,
                Height       = 250,
            };

            var writer = new BarcodeWriter();

            writer.Format  = BarcodeFormat.QR_CODE;
            writer.Options = options;

            if (String.IsNullOrWhiteSpace(text) || String.IsNullOrEmpty(text))
            {
                return(null);
            }
            else
            {
                var qr = new ZXing.BarcodeWriter();
                qr.Options = options;
                qr.Format  = ZXing.BarcodeFormat.QR_CODE;
                var result    = new Bitmap(qr.Write(text.Trim()));
                var resultBit = ImageToByte2(result);
                return(resultBit);
            }
        }
Beispiel #30
0
        public static Image Encode(string content, int width, int height)
        {
            if (string.IsNullOrEmpty(content))
            {
                return(null);
            }
            ZXing.BarcodeWriter barcodeWriter = new ZXing.BarcodeWriter
            {
                Format  = BarcodeFormat.QR_CODE,
                Options = new ZXing.QrCode.QrCodeEncodingOptions
                {
                    Height       = width,
                    Width        = height,
                    Margin       = 0,
                    CharacterSet = "UTF-8"
                }
            };

            using (var bitmap = barcodeWriter.Write(content))
            {
                using (var stream = new MemoryStream())
                {
                    bitmap.MakeTransparent();
                    bitmap.Save(stream, ImageFormat.Png);
                    bitmap.MakeTransparent();
                    var image = Image.FromStream(stream);

                    // return stream.ToArray();
                    // pictureBox.Image = image;

                    return(image);
                }
            }
        }
Beispiel #31
0
        public void DrawImage(ref Bitmap bm, string code)
        {
#if NETSTANDARD2_0
            var writer = new ZXing.BarcodeWriter <Bitmap>();
#else
            var writer = new ZXing.BarcodeWriter();
#endif

            if (code.Length == 13)
            {
                writer.Format = ZXing.BarcodeFormat.EAN_13;
            }
            else if (code.Length == 8)
            {
                writer.Format = ZXing.BarcodeFormat.EAN_8;
            }
            else
            {
                writer.Format = ZXing.BarcodeFormat.CODE_128;
            }

            Graphics g = null;
            g = Graphics.FromImage(bm);
            float mag = PixelConversions.GetMagnification(g, bm.Width, bm.Height,
                                                          OptimalHeight, OptimalWidth);

            int barHeight = PixelConversions.PixelXFromMm(g, OptimalHeight * mag);
            int barWidth  = PixelConversions.PixelYFromMm(g, OptimalWidth * mag);

            writer.Options.Height      = barHeight;
            writer.Options.Width       = barWidth;
            writer.Options.PureBarcode = true;
            bm = writer.Write(code);
        }
        public static IHtmlString GenerateLinearCode(this HtmlHelper html, string inputentry, int height = 210, int width = 900, int margin = 0)
        {
            var qrValue = inputentry;
            var barcodeWriter = new BarcodeWriter
            {
                Format = BarcodeFormat.CODE_39,
                Options = new EncodingOptions
                {
                    Height = height,
                    Width = width,
                    Margin = margin,
                    PureBarcode = true
                }
            };

            using (var bitmap = barcodeWriter.Write(qrValue))
            using (var stream = new MemoryStream())
            {
                bitmap.Save(stream, ImageFormat.Gif);

                var img = new TagBuilder("img");
                img.MergeAttribute("alt", "code39 barcode");
                img.Attributes.Add("src", String.Format("data:image/gif;base64,{0}",
                    Convert.ToBase64String(stream.ToArray())));

                return MvcHtmlString.Create(img.ToString(TagRenderMode.SelfClosing));
            }
        }
Beispiel #33
0
        private void GenerateBarCodeFromaGivenString(string barcode)
        {
            Image img = null;

            using (var ms = new MemoryStream())
            {
                var writer = new ZXing.BarcodeWriter
                {
                    Format  = BarcodeFormat.CODE_128,
                    Options =
                    {
                        Height      =    80,
                        Width       =   280,
                        PureBarcode = false,
                        Margin      = 1
                    }
                };

                img = writer.Write(barcode);
                img.Save(ms, ImageFormat.Jpeg);
                ViewBag.BarcodeImage = "data:image/png;base64," + Convert.ToBase64String(ms.ToArray());
                var filePath = Server.MapPath("~/Areas/Production/Images/BarCodes/" + barcode + ".jpg");
                img.Save(filePath, ImageFormat.Jpeg);
                //return View();
            }
        }
Beispiel #34
0
        static void Main(string[] args)
        {
            var parsedArgs = new Arguments();

            if (args.Length == 0)
            {
                Console.WriteLine(Parser.ArgumentsUsage(typeof(Arguments)));
                return;
            }

            if (!Parser.ParseArgumentsWithUsage(args, parsedArgs))
            {
                Console.WriteLine("Can't parse arguments");
                return;
            }

            var writer = new BarcodeWriter
                {
                    Format = BarcodeFormat.QR_CODE,
                    Options = new EncodingOptions
                        {
                            Height = parsedArgs.Size,
                            Width = parsedArgs.Size,
                            PureBarcode = true,
                            Margin = 0
                        },
                    Renderer = (IBarcodeRenderer<Bitmap>) Activator.CreateInstance(typeof (BitmapRenderer))
                };

            var bitmap = writer.Write(parsedArgs.Content);
            bitmap.SetResolution(parsedArgs.DPI, parsedArgs.DPI);
            bitmap.Save(parsedArgs.Output);
        }
        private BarcodeGroup Generate(BarcodeWriter bw, BarcodeOptions options)//string ap, string dayFrom, string dayTo)
        {
            Random rndNumber = new Random();
            //	load flight details
            var flightResult = AccessGateFlightInfo.ToList().Where(x => x.FlightNo == options.FlightNo).ToList();
            //	If no result, return
            if (flightResult.Count == 0)
            {
                return new BarcodeGroup();
            }
            //	Make flight easier to access
            var flight = flightResult[0];
            var carrier = flight.CarrierDesignator;
            if (carrier.Length < 3)
                carrier = carrier.PadRight(3, ' ');
            var pnr = "";
            string name = options.Name.Length > 20 ? options.Name.Substring(0, 20) : options.Name.PadRight(20, ' ');

            var jDate = (flight.DepartDateTime.DayOfYear + 14).ToString().PadLeft(3, '0');
            var securityValue = name.ToArray().Sum(c => (int)c) + flight.FromAirport.ToArray().Sum(c => (int)c) + options.CISN.ToArray().Sum(c => (int)c);
            var r = (rndNumber).Next(100, 700).ToString();
            var securityFactor = Convert.ToInt32(r, 16);
            securityValue += securityFactor;
            pnr = string.Format("{0}{1}", securityFactor.ToString("X3"), securityValue.ToString("X4"));
            var d = ConfigurationManager.GetSAVConfigSetting("SmartAccessValidation", "CovertSerialNumber");
            var barcode = string.Format("M1{0}E{1}{10}{2}{3}{4}{5}Y{6}{7}01E0293[{8}To{9}]{11}", name, pnr, flight.ToAirport, carrier, flight.FlightNo, jDate, options.Seat, options.CISN, options.StartDate, options.EndDate, options.AP, (Convert.ToInt32(d.KeyValue) + 1).ToString().PadLeft(6, '0'));

            var bg = new BarcodeGroup
            {
                barcode = barcode,
                image = bw.Write(barcode)
            };

            return bg;
        }
Beispiel #36
0
        protected override Stream ToImageStream(BarcodeWriter writer, BarCodeCreateConfiguration cfg) {
            var ms = new MemoryStream();
            Deployment.Current.Dispatcher.BeginInvoke(() => {
                var bitmap = writer.Write(cfg.BarCode);
                bitmap.SaveJpeg(ms, cfg.Width, cfg.Height, 0, 100);
                ms.Seek(0, SeekOrigin.Begin);
            });

            return ms;
        }
Beispiel #37
0
      protected override void OnCreate(Bundle bundle)
      {
         base.OnCreate(bundle);

         this.SetContentView(Resource.Layout.EncoderActivityLayout);


         buttonGenerate = this.FindViewById<Button>(Resource.Id.buttonEncoderGenerate);
         buttonSaveToGallery = this.FindViewById<Button>(Resource.Id.buttonEncoderSaveBarcode);
         textValue = this.FindViewById<EditText>(Resource.Id.textEncoderValue);
         imageBarcode = this.FindViewById<ImageView>(Resource.Id.imageViewEncoderBarcode);
         textViewEncoderMsg = this.FindViewById<TextView>(Resource.Id.textViewEncoderMsg);

         this.buttonSaveToGallery.Enabled = false;
         this.Title = "Write: " + CurrentFormat.ToString();

         buttonGenerate.Click += (sender, e) =>
         {

            var value = string.Empty;

            this.RunOnUiThread(() => { value = this.textValue.Text; });

            try
            {
               var writer = new BarcodeWriter
                               {
                                  Format = CurrentFormat,
                                  Options = new EncodingOptions
                                               {
                                                  Height = 200,
                                                  Width = 600
                                               }
                               };
               bitmap = writer.Write(value);

               this.RunOnUiThread(() =>
               {
                  this.imageBarcode.SetImageDrawable(new Android.Graphics.Drawables.BitmapDrawable(bitmap));
                  this.buttonSaveToGallery.Enabled = true;
               });
            }
            catch (Exception ex)
            {
               bitmap = null;
               this.buttonSaveToGallery.Enabled = false;
               this.RunOnUiThread(() => this.textViewEncoderMsg.Text = ex.ToString());
            }
         };

         buttonSaveToGallery.Click += (sender, e) =>
         {
            Android.Provider.MediaStore.Images.Media.InsertImage(this.ContentResolver, bitmap, "Zxing.Net: " + CurrentFormat.ToString(), "");
         };
      }
        private void txtStudentNumber_Leave(object sender, EventArgs e)
        {
            dbConnect.isOpen();
            if (txtStudentNumber.Text != "")
            {
                using (MySqlConnection con = new MySqlConnection("datasource=127.0.0.1; port = 3306;username = root; password=; database=dbLibrary; convert zero datetime=True;"))
                {
                    using (MySqlCommand com = new MySqlCommand())
                    {
                        com.Connection  = con;
                        com.CommandType = CommandType.Text;
                        com.CommandText = "SELECT * FROM `tblstudents` WHERE studentNo = @sn";
                        com.Parameters.AddWithValue("@sn", txtStudentNumber.Text);

                        try
                        {
                            con.Open();
                            MySqlDataReader sdr = com.ExecuteReader();
                            if (sdr.Read() == true)
                            {
                                if (sdr.GetInt32(13) == 0)
                                {
                                    MessageBox.Show("Student already exists.");
                                    txtStudentNumber.Focus();
                                }
                            }
                            else
                            {
                                QrCodeEncodingOptions options = new QrCodeEncodingOptions
                                {
                                    DisableECI   = true,
                                    CharacterSet = "UTF-8",
                                    Width        = 500,
                                    Height       = 500,
                                    Margin       = 0
                                };
                                var qr = new ZXing.BarcodeWriter();
                                qr.Options = options;
                                qr.Format  = ZXing.BarcodeFormat.QR_CODE;
                                var result = new Bitmap(qr.Write(txtStudentNumber.Text));
                                pbQR.Image = result;
                                //CodeQrBarcodeDraw qrcode = BarcodeDrawFactory.CodeQr;
                                //pbQR.Image = qrcode.Draw(txtStudentNumber.Text, 500);
                            }
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(ex.Message);
                        }

                        con.Close();
                    }
                }
            }
        }
 public BarcodeGroup GenerateFastTrackBarcode(FastTrackOptions options)
 {
     Random rndNumber = new Random();
     //	Generate random name
     //var png = new PersonNameGenerator();
     string name;
     if (rndNumber.Next(0, 2) == 0)
     {
         name = "Mrs Test Name";// + png.GenerateRandomFemaleFirstName() + " " + png.GenerateRandomLastName();
     }
     else
     {
         name = "Mr Test Name";// + png.GenerateRandomMaleFirstName() + " " + png.GenerateRandomLastName();
     }
     //	random flight number
     var ag = AccessGateFlightInfo.ToList(DateTime.Today.AddDays(-7), DateTime.Today);
     Console.WriteLine(ag.Count);
     if (ag.Count == 0)
     {
         Console.WriteLine("No Flights");
         return new BarcodeGroup();
     }
     var randomFlight = ag[rndNumber.Next(0, ag.Count - 1)];
     var flightNo = randomFlight.FlightNo;
     if (flightNo.Length < 5)
     {
         flightNo = flightNo.PadRight(5, ' ');
     }
     //	random seat
     var seat = "";
     var rndSeatLetter = rndNumber.Next(65, 73);
     var seatLetter = (char)rndSeatLetter;
     var rndSeatNumber = rndNumber.Next(1, 11);
     seat = string.Format("{0}{1}", rndSeatNumber, seatLetter).PadLeft(4, '0');
     //	random cisn
     var rndCisn = rndNumber.Next(0, 150);
     var cisn = rndCisn.ToString().PadLeft(5, '0');
     //	return barcode
     BarcodeOptions testParams = new BarcodeOptions()
     {
         Name = name,
         FlightNo = flightNo,
         Seat = seat,
         CISN = cisn,
         StartDate = DateTime.Today.AddDays(-7).ToString("yyyyMMdd"),
         EndDate = DateTime.Today.ToString("yyyyMMdd"),
         AP = "test"
     };
     var bw = new BarcodeWriter
     {
         Format = BarcodeFormat.PDF_417,
         Options = { Margin = 2 }
     };
     return Generate(bw, testParams);
 }
 private static Color32[] Encode(string textForEncoding, int width, int height)
 {
     var writer = new BarcodeWriter {
         Format = BarcodeFormat.QR_CODE,
         Options = new QrCodeEncodingOptions {
             Height = height,
             Width = width
         }
     };
     return writer.Write(textForEncoding);
 }
Beispiel #41
0
        protected void btnHoroscopeSet_Click(object sender, EventArgs e)
        {
            // Database management
            QRCodeContext db = new QRCodeContext();
            // Save a new set
            HoroscopeSet newSet = new HoroscopeSet();
            newSet.Id = Guid.NewGuid();
            newSet.GeneratedOn = DateTime.Now;
            HoroscopeSet lastSet = db.HoroscopeSets.OrderByDescending(s => s.SetNumber).FirstOrDefault();
            newSet.SetNumber = lastSet == null ? 1 : lastSet.SetNumber + 1;
            db.HoroscopeSets.Add(newSet);

            // Generate QR code imges
            string folderBatch = Path.Combine(System.IO.Path.GetTempPath(), Guid.NewGuid().ToString());
            System.IO.Directory.CreateDirectory(folderBatch);
            foreach(HoroscopeSign sign in db.HoroscopeSigns)
            {
                Guid qrId = Guid.NewGuid();
                string url = string.Format(Properties.Settings.Default.ViewPath, Properties.Settings.Default.DomainName, qrId.ToString());
                string shortUrl = GetShortUrl(url).Replace("http://", "");

                // Initialize the QR witer
                BarcodeWriter writer = new BarcodeWriter
                {
                    Format = BarcodeFormat.QR_CODE
                };
                Bitmap qrCode = writer.Write(shortUrl);
                qrCode.SetResolution(1200, 1200);
                qrCode.Save(Path.Combine(folderBatch, qrId.ToString()) + ".jpg");

                // Save the item to the database
                db.HoroscopeQrCodes.Add(new HoroscopeQrCode
                {
                    Id = qrId,
                    HoroscopeSignId = sign.Id,
                    HoroscopeSetId = newSet.Id,
                    LongURL = url,
                    ShortURL = shortUrl
                });
            }

            // Save the database changes
            db.SaveChanges();

            // Zip the package
            string zipFileName = folderBatch + ".zip";
            ZipFile.CreateFromDirectory(folderBatch, zipFileName);

            //Download file
            Response.ContentType = "application/x-zip-compressed";
            Response.AppendHeader("Content-Disposition", "attachment; filename=QRCodes.zip");
            Response.TransmitFile(zipFileName);
            Response.End();
        }
        public override async Task GenerateQRCode(MediaQRContent content)
        {
            if (!AppverseBridge.Instance.RuntimeHandler.RuntimeDispatcher.HasThreadAccess)
            {
                await AppverseBridge.Instance.RuntimeHandler.RuntimeDispatcher.RunAsync(CoreDispatcherPriority.High, () => GenerateQRCode(content));
            }
            else
            {
                if (content == null) return;
                try
                {
                    var size = (content.Size == 0) ? 256 : content.Size;
                    var writer = new BarcodeWriter
                    {
                        Format = BarcodeFormat.QR_CODE,
                        Options = new EncodingOptions { Height = size, Width = size }
                    };

                    //content = encodeQRCodeContents(content);
                    var resultWriteableBitmap = writer.Write(content.Text);

                    var QRFile = await WindowsPhoneUtils.DocumentsFolder.CreateFileAsync(String.Concat("QR_", Guid.NewGuid().ToString().Replace("-", String.Empty), ".png"));
                    //Open File Stream to write content
                    using (var writeStream = await QRFile.OpenAsync(FileAccessMode.ReadWrite))
                    {
                        byte[] pixels;
                        //Read pixels from generated image
                        using (var readStream = resultWriteableBitmap.PixelBuffer.AsStream())
                        {
                            pixels = new byte[readStream.Length];
                            await readStream.ReadAsync(pixels, 0, pixels.Length);
                        }
                        //Encode pixels in the stream
                        var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, writeStream);
                        encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Premultiplied,
                            (uint)resultWriteableBitmap.PixelWidth, (uint)resultWriteableBitmap.PixelHeight, 96, 96,
                            pixels);
                        await encoder.FlushAsync();
                    }
                    var mediaData = new MediaMetadata
                    {
                        ReferenceUrl = QRFile.Path.Replace(WindowsPhoneUtils.DocumentsFolder.Path, String.Empty),
                        Title = QRFile.DisplayName
                    };
                    WindowsPhoneUtils.InvokeCallback("Appverse.Scanner.onGeneratedQR", WindowsPhoneUtils.CALLBACKID, JsonConvert.SerializeObject(mediaData));
                }
                catch (Exception ex)
                {
                    WindowsPhoneUtils.Log(String.Concat("Error while generating QR: ", ex.Message));
                }
            }

        }
Beispiel #43
0
        private void button4_Click(object sender, EventArgs e)
        {
            OpenFileDialog openQR = new OpenFileDialog();

            if (openQR.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                var QRCODE = new ZXing.BarcodeWriter();
                QRCODE.Options            = options4QR;
                QRCODE.Format             = ZXing.BarcodeFormat.QR_CODE;
                pictureBox1.ImageLocation = openQR.FileName;
            }
        }
        public static void GenerateQRCode(string Text)
        {
            Bitmap wvImage;
            BarcodeWriter wvQRCodeWriter = new BarcodeWriter();
            wvQRCodeWriter.Format = BarcodeFormat.QR_CODE;
            ZXing.Common.EncodingOptions encOptions = new ZXing.Common.EncodingOptions() { Width = 500, Height = 500, Margin = 1 };
            wvQRCodeWriter.Options = encOptions;

            wvImage = wvQRCodeWriter.Write(Text);

            ///implementare per il salvataggio/stampa del QRCode
        }
Beispiel #45
0
        private void txt_Nombre_TextChanged(object sender, EventArgs e)
        {
            if (txt_Nombre.Text != "")
            {
                ZXing.BarcodeWriter br = new ZXing.BarcodeWriter();

                br.Format = ZXing.BarcodeFormat.QR_CODE;

                Bitmap bm = new Bitmap(br.Write(txt_Nombre.Text), 300, 300);
                pbg_Generar.Image = bm;
            }
        }
Beispiel #46
0
        protected override Stream ToImageStream(BarcodeWriter writer, BarCodeCreateConfiguration cfg) {
			var stream = new MemoryStream();

			var cf = cfg.ImageType == ImageType.Png
				? Bitmap.CompressFormat.Png
				: Bitmap.CompressFormat.Jpeg;

			using (var bitmap = writer.Write(cfg.BarCode))
				bitmap.Compress(cf, 0, stream);

			stream.Position = 0;
			return stream;
        }
        private void button3_Click(object sender, EventArgs e)
        {
            // Step 5: Create Browse a Local Image Button
            OpenFileDialog open = new OpenFileDialog();

            if (open.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                var qr = new ZXing.BarcodeWriter();
                qr.Options = options;
                qr.Format  = ZXing.BarcodeFormat.QR_CODE;
                pictureBox1.ImageLocation = open.FileName;
            }
        }
        private void button1_Click(object sender, EventArgs e)
        {
            BarcodeWriter writer = new BarcodeWriter();
            writer.Format = BarcodeFormat.QR_CODE;
            writer.Options = new EncodingOptions()
            {
                Width = imgQrCode.Width,
                Height = imgQrCode.Height,
                Margin = 2
            };

            imgQrCode.Image = new Bitmap(writer.Write(txtMensagem.Text));
        }
Beispiel #49
0
        private void generateqrlabel()
        {
            QrCodeEncodingOptions options = new QrCodeEncodingOptions
            {
                DisableECI   = true,
                CharacterSet = "UTF-8",
                Width        = 100,
                Height       = 100,
            };
            BarcodeWriter writer = new BarcodeWriter();

            writer.Format  = BarcodeFormat.QR_CODE;
            writer.Options = options;

            var qr = new ZXing.BarcodeWriter();

            qr.Options = options;
            qr.Format  = ZXing.BarcodeFormat.QR_CODE;

            string intlotcode = get_intlotcode();

            String asfis        = "";
            String suppliercode = txtsuppcode.Text.Trim();

            List <object[]> data = new List <object[]>();
            MainMenu        frm  = new MainMenu();

            data = frm.get_data_table_string("tbspecies", "", "");

            if (data.Count > 0)
            {
                asfis = data[0][1].ToString();
            }

            String origin         = "INDONESIA";
            String fishing_ground = get_fishing_ground();
            String certcode       = cbcertificate.Text.Trim();

            String loincode = loin_code_global;
            String grade    = cbgrade.Text.Trim();
            double rweight  = Double.Parse(txtweight.Text);
            String remark   = txtremark.Text.Trim();

            String qrtext = loincode + "\r\nAsfis: " + asfis + "\r\ngrade: " + grade + "\r\nweight: " + rweight.ToString() + "Kg\r\n" + origin + "\r\nfishing_ground: " + fishing_ground + "\r\n" + intlotcode + "\r\n" + remark + "\r\n";

            var result = new Bitmap(qr.Write(qrtext));

            pbLabel.Image = result;

            printlabel();
        }
Beispiel #50
0
        private void generateQrImage(string qrText)
        {
            var qrCodeWriter = new ZXing.BarcodeWriter {
                Format  = BarcodeFormat.QR_CODE,
                Options = new ZXing.QrCode.QrCodeEncodingOptions
                {
                    CharacterSet = "UTF-8",
                    Height       = 200,
                    Width        = 200,
                }
            };

            IMG_QrCode.Source = qrCodeWriter.Write(qrText);
        }
Beispiel #51
0
 public WriteableBitmap QRCode(string key, string label, int width = 150, int height = 150)
 {
     IBarcodeWriter writer = new BarcodeWriter
     {
         Format = BarcodeFormat.QR_CODE,
         Options = new ZXing.Common.EncodingOptions
         {
             Height = height,
             Width = width
         }
     };
     PixelData result = writer.Write("otpauth://totp/" + label + "?secret=" + key);
     return (WriteableBitmap)result.ToBitmap();
 }
        private static WriteableBitmap GenerateQRCode(string text)
        {
            BarcodeWriter _writer = new BarcodeWriter();

            _writer.Format = BarcodeFormat.QR_CODE;

            _writer.Options.Height = 400;
            _writer.Options.Width = 400;
            _writer.Options.Margin = 10;

            var barcodeImage = _writer.Write(text);

            return barcodeImage;
        }
		public override void GenerateQRCode(MediaQRContent content)
		{
			SystemLogger.Log (SystemLogger.Module.PLATFORM, "1");
			try{
				MediaMetadata mediaData = new MediaMetadata();
				SystemLogger.Log (SystemLogger.Module.PLATFORM, "2");

				int size = content.Size;
				if (size == 0) {
					size = 256;
				}
				var writer = new ZXing.BarcodeWriter
				{ 
					Format = BarcodeFormat.QR_CODE, 
					Options = new EncodingOptions { Height = size, Width = size } 
				};
				//var img = writer.Write(content.Text);
				SystemLogger.Log (SystemLogger.Module.PLATFORM, "3");

				var uuid = Guid.NewGuid ();
				string s = uuid.ToString ();
				String filename = "QR_" + s;
				NSError err;
				DirectoryData dest = new DirectoryData(DEFAULT_ROOT_PATH);
				string path = Path.Combine(dest.FullName, filename+".png");
				SystemLogger.Log (SystemLogger.Module.PLATFORM, "4");
				content = encodeQRCodeContents(content);
				using(UIImage img = writer.Write(content.Text)) {
					
					using (var data = img.AsPNG ()) {
						data.Save (path, true, out err);
					}
				}
				SystemLogger.Log (SystemLogger.Module.PLATFORM, "5");

				mediaData.ReferenceUrl = filename+".png";
				mediaData.Title = filename;

				SystemLogger.Log (SystemLogger.Module.PLATFORM, "6");

				UIApplication.SharedApplication.InvokeOnMainThread (delegate {
					UIViewController viewController = UIApplication.SharedApplication.KeyWindow.RootViewController;
					FireUnityJavascriptEvent(viewController, "Appverse.Scanner.onGeneratedQR", mediaData);

				});
			}catch(Exception ex)
			{
				SystemLogger.Log (SystemLogger.Module.PLATFORM, "GenerateQRCode - exception: " + ex.Message);
			}
		}
Beispiel #54
0
        private Bitmap CreatetBarcode(string code, int?width = null, int?height = null, bool?pureBarcode = null)
        {
            //var code = BarCode.ConvertCustomerBarCode("0140113", "秋田県大仙市堀見内 南田茂木 添60-1");
            var writer = new ZXing.BarcodeWriter
            {
                //Format = ZXing.BarcodeFormat.CODE_128,
                Encoder = new JapanesePostalWriter()
            };

            writer.Options.PureBarcode = pureBarcode ?? false;
            writer.Options.Width       = width ?? 0;    // code.Length*2*100;
            writer.Options.Height      = height ?? 300; // 3*100;
            return(writer.Write(code));
        }
Beispiel #55
0
        private void Form1_Load(object sender, EventArgs e)
        {
            //---
            //單純QR
            Bitmap bitmap           = null;
            string strQrCodeContent = "http://jashliao.eu/wordpress/";

            ZXing.BarcodeWriter writer = new ZXing.BarcodeWriter
            {
                Format  = ZXing.BarcodeFormat.QR_CODE,
                Options = new ZXing.QrCode.QrCodeEncodingOptions
                {
                    //Create Photo
                    Height       = 200,
                    Width        = 200,
                    CharacterSet = "UTF-8",
                    //錯誤修正容量
                    //L水平    7%的字碼可被修正
                    //M水平    15%的字碼可被修正
                    //Q水平    25%的字碼可被修正
                    //H水平    30%的字碼可被修正
                    ErrorCorrection = ZXing.QrCode.Internal.ErrorCorrectionLevel.H
                }
            };

            bitmap = writer.Write(strQrCodeContent);    //Create Qr-code , use input string

            //---
            //Storage bitmpa
            string strDir;

            strDir  = System.Windows.Forms.Application.StartupPath;
            strDir += "\\temp.png";
            bitmap.Save(strDir, System.Drawing.Imaging.ImageFormat.Png);
            //---Storage bitmpa
            //---單純QR

            //---
            //插入LOGO QrCode
            strDir  = System.Windows.Forms.Application.StartupPath;
            strDir += "\\temp01.png";
            Bitmap bitmap01 = null;

            bitmap01 = GetQRCodeByZXingNet("http://jashliao.eu/wordpress/", 200, 200);
            bitmap01.Save(strDir, System.Drawing.Imaging.ImageFormat.Png);

            pictureBox1.Image = bitmap01;
            //---插入LOGO QrCode
        }
Beispiel #56
0
        private void button1_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(txtLastName.Text))
            {
                MessageBox.Show(Properties.Resources.NameIsNullOrEmptyMessage);
                return;
            }

            StringBuilder sb = new StringBuilder();
            sb.Append("BEGIN:VCARD\r\n");
            sb.Append("VERSION:2.1\r\n");
            sb.AppendFormat("N;LANGUAGE=zh-tw;CHARSET=utf-8:{0};{1}\r\n", txtLastName.Text.Trim(), txtFirstName.Text.Trim());

            if (string.IsNullOrEmpty(txtFN.Text))
                txtFN.Text = string.Format("{0}{1}", txtLastName.Text, txtFirstName.Text);
            sb.AppendFormat("FN;CHARSET=utf-8:{0}\r\n", txtFN.Text.Trim());

            if (!string.IsNullOrEmpty(txtORG.Text))
                sb.AppendFormat("ORG;CHARSET=utf-8:{0};{1}\r\n", txtORG.Text.Trim(), txtDepart.Text.Trim());

            if (!string.IsNullOrEmpty(txtMobile.Text))
                sb.AppendFormat("TEL;CELL;VOICE:{0}\r\n", txtMobile.Text.Trim());

            if (!string.IsNullOrEmpty(txtWork.Text))
                sb.AppendFormat("TEL;WORK;VOICE:{0}\r\n", txtWork.Text.Trim());

            if (!string.IsNullOrEmpty(txtHome.Text))
                sb.AppendFormat("TEL;HOME;VOICE:{0}\r\n", txtHome.Text.Trim());

            if (!string.IsNullOrEmpty(txtEmail.Text))
                sb.AppendFormat("EMAIL;PREF;INTERNET:{0}\r\n", txtEmail.Text.Trim());

            sb.AppendFormat("REV:{0}\r\n", DateTime.Now.ToString("yyyyMMddThhmmssZ"));
            sb.Append("END:VCARD");

            txtVCardResult.Text = sb.ToString();

            string sEncode = "utf-8";
            string EncoderContent = GetEncodingString(txtVCardResult.Text, sEncode);

            BarcodeWriter bw = new BarcodeWriter();
            bw.Format = BarcodeFormat.QR_CODE;
            bw.Options.Width = 260;
            bw.Options.Height = 237;
            bw.Options.PureBarcode = true;

            Bitmap bitmap = bw.Write(EncoderContent);
            pictureBox1.Image = (Image)bitmap;
        }
Beispiel #57
0
        private static void InitWriter()
        {
            WT        = new ZXing.BarcodeWriter();
            WT.Format = ZXing.BarcodeFormat.QR_CODE;
            var options = new QrCodeEncodingOptions
            {
                DisableECI      = true,
                CharacterSet    = "UTF-8",
                ErrorCorrection = ZXing.QrCode.Internal.ErrorCorrectionLevel.H,
            };

            WT.Options = options;

            initedWriter = true;
        }
        public void QrCreate(string qr, string saveTitle)
        {
            var writer = new ZXing.BarcodeWriter
            {
                Format  = BarcodeFormat.QR_CODE,
                Options = new ZXing.Common.EncodingOptions
                {
                    Height = 400,
                    Width  = 400
                }
            };

            writer.Write(qr)
            .Save(@"C:\Users\Kevin\Desktop\" + saveTitle + ".bmp");
        }
Beispiel #59
0
        private void BtnGenerateID_Click(object sender, EventArgs e)
        {
            //frmGenerateQR frm = new frmGenerateQR();
            if (lblStudNo.Text == "Student Number")
            {
                MyMessageBox.ShowMessage("No student selected!", "", MessageBoxButtons.RetryCancel, MessageBoxIcon.Error);
            }
            else
            {
                frmLibraryCard frm = new frmLibraryCard();
                frm.lblLibrarian.Text = admin;
                cn.Open();
                cm = new SqlCommand("SELECT (firstName + ' ' + LastName) AS Name, studentNum, contact, course, image FROM tblStudent WHERE studentNum = @studentNum", cn);
                //cm = new SqlCommand("SELECT (firstName + ' ' + LastName) AS Name, studentNum FROM tblStudent WHERE studentNum = @studentNum", cn);
                cm.Parameters.AddWithValue("@studentNum", lblStudNo.Text);
                dr = cm.ExecuteReader();
                while (dr.Read())
                {
                    frm.lblStudentName.Text = dr["Name"].ToString();
                    frm.lblCourse.Text      = dr["course"].ToString();
                    frm.lblStudentNum.Text  = dr["studentNum"].ToString();
                    frm.lblContactNo.Text   = dr["contact"].ToString();
                    //Load Image
                    byte[]       imgbytes = (byte[])dr["image"];
                    MemoryStream mstream  = new MemoryStream(imgbytes);
                    frm.studentImage.Image = Image.FromStream(mstream);

                    //
                    if (String.IsNullOrWhiteSpace(lblStudNo.Text) || String.IsNullOrEmpty(lblStudNo.Text))
                    {
                        frm.QR.Image = null;
                        MessageBox.Show("Text not found", "Oops!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    else
                    {
                        var qr = new ZXing.BarcodeWriter();
                        qr.Options = options;
                        qr.Format  = ZXing.BarcodeFormat.QR_CODE;
                        var result = new Bitmap(qr.Write(lblStudNo.Text.Trim()));
                        frm.QR.Image = result;
                        //lblStudNo.Text = "";
                    }
                }
                dr.Close();
                cn.Close();
                frm.Show();
            }
        }
Beispiel #60
-1
        private Bitmap GenerateBarCodeZXing(string data)
        {
            //IBarcodeReader reader = new ZXing.BarcodeReader();
            var writer = new ZXing.BarcodeWriter
            {
                //ErrorCorrection = ZXing.QrCode.Internal.ErrorCorrectionLevel.H,
                Format  = BarcodeFormat.PDF_417,
                Options = new EncodingOptions {
                    Height = 90, Width = 90, Margin = 10
                },                                                                       //optional,
            };

            // writer.Options.dim

            writer.Renderer = new ZXing.Rendering.BitmapRenderer();
            var imgBitmap = writer.Write(data);
            var size      = new Size(450, 109);

            Bitmap original = new Bitmap(imgBitmap, size);

            using (var stream = new MemoryStream())
            {
                imgBitmap.Save(stream, ImageFormat.Jpeg);
                return(original);
            }
        }