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; }
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="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; }
/// <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; }
protected override void OnNavigatedTo(NavigationEventArgs e) { IBarcodeWriter writer = new BarcodeWriter { Format = BarcodeFormat.QR_CODE, Options = new ZXing.Common.EncodingOptions { Height = 300, Width = 300, }, Renderer = new ZXing.Rendering.PixelDataRenderer() { Foreground = Colors.Black } }; var result = writer.Write("www.microsoft.com"); var wb = result.ToBitmap() as WriteableBitmap; QrcodeImg.Source = wb; }
public MainWindowPresenter() { // init server connection InitializePresItServiceClient(); // create random session ID to be authenticated by user var sessionId = Guid.NewGuid().ToString(); // create and show QR code of session ID var writer = new BarcodeWriter { Format = BarcodeFormat.QR_CODE, Options = new QrCodeEncodingOptions {Margin = 1} }; var result = writer.Write(sessionId); var img = new BitmapImage(); using (var memory = new MemoryStream()) { result.Save(memory, ImageFormat.Png); memory.Position = 0; img.BeginInit(); img.StreamSource = memory; img.CacheOption = BitmapCacheOption.OnLoad; img.EndInit(); } barcodeImage = img; // Connect to server and wait until we get authenticated new Thread(() => { while (true) { try { clientId = service.IsAuthenticated(sessionId); if (clientId == null) continue; if (IsAuthenticated != null) IsAuthenticated(this, EventArgs.Empty); break; } catch (TimeoutException) { } } }).Start(); // create slide importers importers = new List<ISlidesImporter> { new ImageImporter(), new PowerPointImporter() }; }
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"); }
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(); } }
public static IHtmlString GenerateMatrixCode(this HtmlHelper html, string inputentry, int height = 250, int width = 250, 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 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)); } }
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; }
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; } }
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; }
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)); }
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 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); }
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; } }
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); } } }
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; } }
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 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 ??? } } }
/// <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); }
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); } }
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)); } }
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 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()); } } }
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)); } }
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; } }
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; } }
//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); } }
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(); } }
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(); }
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"); } }
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; }
public virtual Stream Create(BarCodeCreateConfiguration cfg) { var writer = new 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 } }; #if __IOS__ return (cfg.ImageType == ImageType.Png) ? writer.Write(cfg.BarCode).AsPNG().AsStream() : writer.Write(cfg.BarCode).AsJPEG().AsStream(); #elif __ANDROID__ MemoryStream stream = null; var cf = cfg.ImageType == ImageType.Png ? Bitmap.CompressFormat.Png : Bitmap.CompressFormat.Jpeg; using (var bitmap = writer.Write(cfg.BarCode)) { // bitmap.Compress(cf, 0, ms); doesn't work var buffer = ByteBuffer.Allocate(bitmap.RowBytes * bitmap.Height); bitmap.CopyPixelsToBuffer(buffer); buffer.Rewind(); // var bytes = buffer.ToArray<byte>(); doesn't work var classHandle = JNIEnv.FindClass("java/nio/ByteBuffer"); var methodId = JNIEnv.GetMethodID(classHandle, "array", "()[B"); var resultHandle = JNIEnv.CallObjectMethod(buffer.Handle, methodId); var bytes = JNIEnv.GetArray<byte>(resultHandle); JNIEnv.DeleteLocalRef(resultHandle); stream = new MemoryStream(bytes); } stream.Position = 0; return stream; #elif WINDOWS_PHONE return new MemoryStream(writer.Write(cfg.BarCode).ToByteArray()); #endif }
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(); } } } }
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); }
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 static Bitmap GenerateSimple(string strCode, int width = 512, int height = 512) { if (initedWriter == false) { InitWriter(); } WT.Options.Width = width; WT.Options.Height = height; return(WT.Write(strCode)); }
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 }
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; } }
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 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)); }
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(); }
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); }
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); } }
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 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)); }
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; }
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; }
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 }
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"); }
/*/****************************************************************/ public ActionResult VerOC(int id) { OrdenDeCompraVM OrdComVm = new OrdenDeCompraVM(); using (vialcatEntities dc = new vialcatEntities()) { //parte nueva ****************************************** #region ObjetoOrdenDeCompra var OOrd_Com = dc.vial_ordendecompra .Include(c => c.vial_afiliados) .FirstOrDefault(c => c.idOrdenDeCompra == id); OrdComVm.Comercio = OOrd_Com.comercio; OrdComVm.IdOrdenDeCompra = OOrd_Com.idOrdenDeCompra; OrdComVm.Afiliado = OOrd_Com.Afiliado; OrdComVm.Importe = OOrd_Com.importe; OrdComVm.FechaEmision = OOrd_Com.fecha_emision.Value; OrdComVm.DatosAfiliado = OOrd_Com.vial_afiliados.apellido.ToUpper() + ", " + OOrd_Com.vial_afiliados.nombre.ToUpper(); OrdComVm.FechaVencimiento = OOrd_Com.fecha_vencimiento.Value; #endregion ObjetoOrdenDeCompra } using (var ms = new MemoryStream()) { string userid = id.ToString(); Image img = null; var writer = new ZXing.BarcodeWriter() { Format = BarcodeFormat.CODE_128 }; writer.Options.Height = 80; writer.Options.Width = 280; writer.Options.PureBarcode = true; img = writer.Write(userid); img.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg); //return File(ms.ToArray(), "image/jpeg"); ViewBag.Codigo = "data:image/jpeg;base64," + Convert.ToBase64String(ms.ToArray(), 0, ms.ToArray().Length); } return(View(OrdComVm)); }
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(); } }
public static Bitmap GenerateBarCode(string strValue) { ZXing.BarcodeWriter barcodeWriter = new ZXing.BarcodeWriter(); barcodeWriter.Format = ZXing.BarcodeFormat.CODE_128; EncodingOptions encodingOptions = new EncodingOptions(); // dont put the data on barcode. encodingOptions.PureBarcode = false; encodingOptions.Height = 6; barcodeWriter.Options = encodingOptions; Bitmap bitmap = barcodeWriter.Write(strValue); return(bitmap); }
//creating and saving QrCode public Bitmap QrCreate(string qr) { Bitmap storedQr; var writer = new ZXing.BarcodeWriter { Format = BarcodeFormat.QR_CODE, Options = new ZXing.Common.EncodingOptions { Height = 400, Width = 400 } }; storedQr = writer.Write(qr); return(storedQr); }
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); } }
private static WriteableBitmap GenerateQrCode(string content) { var writer = new BarcodeWriter { Renderer = new ZXing.Rendering.WriteableBitmapRenderer { Foreground = System.Windows.Media.Color.FromArgb(255, 0, 0, 0), }, Format = BarcodeFormat.QR_CODE, Options = { Height = 400, Width = 400 } }; var barcodeImage = writer.Write(content); return barcodeImage; }