static void Main(string[] args) { string sampleText = "aaa"; QrEncoder qrEncoder = new QrEncoder(ErrorCorrectionLevel.M); QrCode qrCode = qrEncoder.Encode(sampleText); StringBuilder builder = new StringBuilder(); for (int j = 0; j < qrCode.Matrix.Width; j++) { for (int i = 0; i < qrCode.Matrix.Width; i++) { char charToPrint = qrCode.Matrix[i, j] ? '█' : ' '; builder.Append(charToPrint); Console.WriteLine(charToPrint); } } }
private bool GenCode(string content, out MemoryStream ms) { ms = new MemoryStream(); ErrorCorrectionLevel ecl = ErrorCorrectionLevel.M;//误差水平 QuietZoneModules qzm = QuietZoneModules.Two; int moduleSize = 12; QrEncoder encoder = new QrEncoder(ecl); QrCode qr; if (encoder.TryEncode(content, out qr))//对内容进行编码,并保存生成的矩阵 { var render = new GraphicsRenderer(new FixedModuleSize(moduleSize, qzm)); render.WriteToStream(qr.Matrix, ImageFormat.Jpeg, ms); return(true); } return(false); }
/// <summary> /// 生成二维码 /// </summary> /// <param name="content">内容</param> /// <param name="moduleSize">二维码的大小</param> /// <param name="filePath">为存放的图片路径</param> /// <returns>输出流</returns> public static MemoryStream GetQRCode(string content, int moduleSize = 9) { var encoder = new QrEncoder(ErrorCorrectionLevel.M); QrCode qrCode = encoder.Encode(content); GraphicsRenderer render = new GraphicsRenderer(new FixedModuleSize(moduleSize, QuietZoneModules.Two), Brushes.Black, Brushes.White); MemoryStream memoryStream = new MemoryStream(); render.WriteToStream(qrCode.Matrix, ImageFormat.Jpeg, memoryStream); return(memoryStream); //生成图片的代码 //DrawingSize dSize = render.SizeCalculator.GetSize(qrCode.Matrix.Width); //Bitmap map = new Bitmap(dSize.CodeWidth, dSize.CodeWidth); //Graphics g = Graphics.FromImage(map); //render.Draw(g, qrCode.Matrix); //map.Save(fileName, ImageFormat.Jpeg);//fileName为存放的图片路径 }
/// <summary> /// Utilizando la librería Gma.QrCodeNet creamos una nueva imagen en PNG /// que será un código QR con el texto que se le de /// </summary> /// <param name="guid">Texto que tendrá el código QR</param> /// <param name="basePath">Base path</param> /// <returns>Regresa el URL en el que se podrá encontrar la imagen recien /// guardada</returns> public static string CreateQr(string guid, string basePath) { // Se crea un Stream que tendrá la imagen en JPG utilizando QrCodeNet QrEncoder qrEncoder = new QrEncoder(ErrorCorrectionLevel.M); QrCode qrCode = qrEncoder.Encode(guid); GraphicsRenderer renderer = new GraphicsRenderer(new FixedModuleSize(20, QuietZoneModules.Two), Brushes.Black, Brushes.White); MemoryStream stream = new MemoryStream(); renderer.WriteToStream(qrCode.Matrix, ImageFormat.Png, stream, new Point(100, 100)); // Se crea un path donde se guardará el archivo en el disco duro string filePath = Path.Combine(basePath, String.Format("Storage/Qrs/{0}.png", guid)); PhotoData.SaveQrImageFile(filePath, stream.ToArray()); stream.Close(); // Construimos el URL en el que el navegador podrá descargar la imagen return(Path.Combine(ConfigurationManager.AppSettings["PhotoPath"], String.Format("Storage/Qrs/{0}.png", guid))); }
public void GeneraQR(string fecha, string cuit, string ptoVtaNComp, string total, string tipoComp) { string fechaJ = fecha.Substring(6) + "-" + fecha.Substring(3, 2) + "-" + fecha.Substring(0, 2); string cuitJ = cuit.Replace("-", string.Empty); string ptoVta = ptoVtaNComp.Substring(0, 4); string nroComp = ptoVtaNComp.Substring(5); string tipoCompJ = string.Empty; string ver = "1"; total = total.Replace(",", "."); if (tipoComp == "A") { tipoCompJ = "081"; } else { tipoCompJ = "082"; } string moneda = "PES"; string ctz = "1"; string tipoCodAut = "E"; string codAut = "70417054367476"; string jsonS = "ver:" + ver + ",fecha:" + fechaJ + ",cuit:" + cuitJ + ",ptoVta:" + ptoVta + ",tipoCmp:" + tipoCompJ + ",nroCmp:" + nroComp + ",importe:" + total + ",moneda:" + moneda + ",ctz:" + ctz + ",tipoCodAut:" + tipoCodAut + ",codAut:" + codAut; string json64 = Convert.ToBase64String(Encoding.UTF8.GetBytes(jsonS)); string url = "https://www.afip.gob.ar/fe/qr/?p=" + json64; QrEncoder qrEncoder = new QrEncoder(ErrorCorrectionLevel.H); QrCode qrCode = new QrCode(); qrEncoder.TryEncode(url, out qrCode); GraphicsRenderer renderer = new GraphicsRenderer(new FixedCodeSize(400, QuietZoneModules.Zero), Brushes.Black, Brushes.White); MemoryStream ms = new MemoryStream(); renderer.WriteToStream(qrCode.Matrix, ImageFormat.Png, ms); var imageTemporal = new Bitmap(ms); var imagen = new Bitmap(imageTemporal, new Size(new Point(200, 200))); string filePath = Path.Combine(Application.StartupPath + "\\Reportes", "QR.png"); Image ImagenGrb = imagen; ImagenGrb.Save(filePath); }
/// <summary> /// 二维码二进制流 /// </summary> /// <param name="str"></param> /// <returns></returns> public byte[] QrCodeCreate(string str) { QrCode qrcode = new QrEncoder().Encode(str); GraphicsRenderer gRenderer = new GraphicsRenderer(new FixedModuleSize(6, QuietZoneModules.Two), Brushes.Black, Brushes.White); MemoryStream ms = new MemoryStream(); gRenderer.WriteToStream(qrcode.Matrix, ImageFormat.Png, ms); Image image = Image.FromStream(ms); MemoryStream ms1 = new MemoryStream(); image.Save(ms1, ImageFormat.Png); byte[] arr = new byte[ms1.Length]; ms1.Position = 0L; ms1.Read(arr, 0, (int)ms1.Length); ms1.Close(); return(arr); }
public int qr() { QrEncoder qrEncoder = new QrEncoder(ErrorCorrectionLevel.H); QrCode qrCode = new QrCode(); String rambon = (new Random().Next(1, 1000)).ToString(); qrEncoder.TryEncode(rambon, out qrCode); GraphicsRenderer renderer = new GraphicsRenderer(new FixedCodeSize(400, QuietZoneModules.Zero), Brushes.Black, Brushes.White); MemoryStream ms = new MemoryStream(); renderer.WriteToStream(qrCode.Matrix, ImageFormat.Png, ms); var imageTemporal = new Bitmap(ms); return(Convert.ToInt32(qrCode.GetHashCode())); }
private byte[] CreateQRCode(string data) { // generating a barcode here. Code is taken from QrCode.Net library QrEncoder qrEncoder = new QrEncoder(ErrorCorrectionLevel.H); QrCode qrCode = new QrCode(); qrEncoder.TryEncode(data, out qrCode); //GraphicsRenderer renderer = new GraphicsRenderer(new FixedModuleSize(4, QuietZoneModules.Four), Brushes.Black, Brushes.White); var memoryStream = new MemoryStream(); //renderer.WriteToStream(qrCode.Matrix, ImageFormat.Png, memoryStream); // very important to reset memory stream to a starting position, otherwise you would get 0 bytes returned memoryStream.Position = 0; return(memoryStream.ToArray()); }
/// <summary> /// 生成二维码 /// </summary> /// <param name="url"></param> public static void Generate1(string url) { //创建二维码生成类 QrEncoder qrEncoder = new QrEncoder(); QrCode qrCode = qrEncoder.Encode(url); //输出显示在控制台 for (int j = 0; j < qrCode.Matrix.Height; j++) { for (int i = 0; i < qrCode.Matrix.Width; i++) { char charToPoint = qrCode.Matrix[i, j] ? '█' : ' '; Console.Write(charToPoint); } Console.WriteLine(); } }
/// <summary> /// 生成二维码 /// </summary> /// <param name="content">二维码内容,可以是url、文本信息</param> /// <param name="savePath">保存地址</param> public static void Generate(string content, string savePath) { // 二维码容错率 QrEncoder qrEncoder = new QrEncoder(ErrorCorrectionLevel.H); QrCode qrCode = new QrCode(); qrEncoder.TryEncode(content, out qrCode); using (MemoryStream ms = new MemoryStream()) { var renderer = new GraphicsRenderer(new FixedModuleSize(18, QuietZoneModules.Two)); renderer.WriteToStream(qrCode.Matrix, ImageFormat.Png, ms); System.Drawing.Image bitmap = new System.Drawing.Bitmap(ms); bitmap.Save(savePath, System.Drawing.Imaging.ImageFormat.Png); } }
/* * public static void printList(LTL_LotteryList pNumberList) * { * // Configurar impresión para Ticket de Venta * TicketPrinter ticketPrinter = new TicketPrinter(); * SaleTicket saleTicket = new SaleTicket(); * saleTicket.companyName = UtilityService.getCompanyName(); * // Obtener datos del punto de venta * LPS_LotteryPointSale pointSale = UtilityService.getPointSale(); * saleTicket.pointSaleName = pointSale.LPS_DisplayName; * // Obtener datos del sorteo * LotteryDrawRepository drawRepo = new LotteryDrawRepository(); * LTD_LotteryDraw drawObject = drawRepo.getById(pNumberList.LTD_LotteryDraw); * saleTicket.drawDate = drawObject.LTD_CreateDate; * // Obtener datos de tipo de sorteo * LotteryDrawTypeRepository drawTypeRepo = new LotteryDrawTypeRepository(); * LDT_LotteryDrawType drawType = drawTypeRepo.getById(drawObject.LDT_LotteryDrawType); * saleTicket.drawTypeCode = drawType.LDT_Code; * // Llenar datos del número de lista * saleTicket.createDate = DateTime.Now; * saleTicket.ticketId = pNumberList.LTL_Id; * saleTicket.globalId = pointSale.LPS_Id + "" + saleTicket.ticketId; * saleTicket.customerName = pNumberList.LTL_CustomerName; * // Obtener detalle de la lista procesada * LotteryListRepository listRepo = new LotteryListRepository(); * saleTicket.listNumberDetail = listRepo.getTupleListDetail(pNumberList.LTL_Id); * ticketPrinter.saleTicket = saleTicket; * // Obtener nombre de impresora y enviar impresión * string printerName = UtilityService.getTicketPrinterName(); * ticketPrinter.printLotterySaleTicket(printerName); * } */ /* * public static void printPrizeTicket(LTD_LotteryDraw pDraw, string[] pWinningNumberArray) * { * // Configurar impresión para Ticket de Venta * TicketPrinter ticketPrinter = new TicketPrinter(); * PrizeTicket prizeTicket = new PrizeTicket(); * prizeTicket.companyName = UtilityService.getCompanyName(); * prizeTicket.title = "NÚMEROS PREMIADOS"; * // Obtener datos del punto de venta * LPS_LotteryPointSale pointSale = UtilityService.getPointSale(); * prizeTicket.pointSaleName = pointSale.LPS_DisplayName; * prizeTicket.drawDate = pDraw.LTD_CreateDate; * // Obtener datos de tipo de sorteo * LotteryDrawTypeRepository drawTypeRepo = new LotteryDrawTypeRepository(); * LDT_LotteryDrawType drawType = drawTypeRepo.getById(pDraw.LDT_LotteryDrawType); * prizeTicket.drawTypeCode = drawType.LDT_Code; * // Llenar datos del número de lista * prizeTicket.createDate = DateTime.Now; * // Obtener listado de información de ganadores * LotteryListRepository lotteryListRepository = new LotteryListRepository(); * prizeTicket.listWinningInfo = lotteryListRepository.getWinningNumbersList(pDraw, pWinningNumberArray); * prizeTicket.winnerNumbers = pWinningNumberArray; * ticketPrinter.prizeTicket = prizeTicket; * // Obtener nombre de impresora y enviar impresión * string printerName = UtilityService.getTicketPrinterName(); * ticketPrinter.printPrizeTicket(printerName); * } */ public static Bitmap buildQRCode(string pCodeText, int pBitmapWidth, int pBitmapHeight) { QrEncoder qrEncoder = new QrEncoder(ErrorCorrectionLevel.H); QrCode qrCode = new QrCode(); qrEncoder.TryEncode(pCodeText, out qrCode); GraphicsRenderer renderer = new GraphicsRenderer(new FixedCodeSize(400, QuietZoneModules.Zero), Brushes.Black, Brushes.White); MemoryStream ms = new MemoryStream(); renderer.WriteToStream(qrCode.Matrix, ImageFormat.Png, ms); Bitmap imageTemporal = new Bitmap(ms); Bitmap imagen = new Bitmap(imageTemporal, new Size(new Point(pBitmapWidth, pBitmapHeight))); return(imagen); }
/// <summary> /// 生成二维码的方法 /// </summary> /// <param name="str">二维码包含的内容</param> /// <param name="moduleSize">二维码大小</param> /// <param name="no">编号</param> private void createQrCode(string content, int no, int moduleSize = 9) { //QrEncoder qrEncoder = new QrEncoder(ErrorCorrectionLevel.H); //QrCode qrCode = new QrCode(); //qrEncoder.TryEncode(str, out qrCode); string filename = DateTime.Now.ToString("d"); filename = filename.Replace("/", ""); filename = filename.Replace(":", ""); filename = filename.Replace("-", ""); filename = filename.Replace(".", ""); filename = filename.Replace(" ", ""); string filepath = System.AppDomain.CurrentDomain.BaseDirectory + filename; if (!Directory.Exists(filepath)) { Directory.CreateDirectory(filepath); } string fileName = filepath + "\\" + no + ".png"; //Renderer renderer = new Renderer(5, Brushes.Black, Brushes.White); //renderer.CreateImageFile(qrCode.Matrix, @filename, ImageFormat.Png); //ErrorCorrectionLevel 误差校正水平 //QuietZoneModules 空白区域 var encoder = new QrEncoder(ErrorCorrectionLevel.M); QrCode qrCode = encoder.Encode(content); GraphicsRenderer render = new GraphicsRenderer(new FixedModuleSize(moduleSize, QuietZoneModules.Two), Brushes.Black, Brushes.White); //MemoryStream memoryStream = new MemoryStream(); //render.WriteToStream(qrCode.Matrix, ImageFormat.Jpeg, memoryStream); //return memoryStream; //生成图片的代码 DrawingSize dSize = render.SizeCalculator.GetSize(qrCode.Matrix.Width); Bitmap map = new Bitmap(dSize.CodeWidth, dSize.CodeWidth); Graphics g = Graphics.FromImage(map); render.Draw(g, qrCode.Matrix); map.Save(fileName, ImageFormat.Png);//fileName为存放的图片路径 }
public AddressViewModel(HdPubKey model) { Model = model; ClipboardNotificationVisible = false; ClipboardNotificationOpacity = 0; Task.Run(() => { var encoder = new QrEncoder(ErrorCorrectionLevel.M); encoder.TryEncode(Address, out var qrCode); return(qrCode.Matrix.InternalArray); }).ContinueWith(x => { QrCode = x.Result; }); }
public string CreateQrCode(string source, string pathFile) { QrEncoder qrEncoder = new QrEncoder(ErrorCorrectionLevel.H); QrCode qrCode = new QrCode(); qrEncoder.TryEncode(source, out qrCode); GraphicsRenderer renderer = new GraphicsRenderer(new FixedCodeSize(8000, QuietZoneModules.Zero), Brushes.Black, Brushes.White); MemoryStream ms = new MemoryStream(); renderer.WriteToStream(qrCode.Matrix, ImageFormat.Png, ms); Bitmap imagenTemporal = new Bitmap(ms); var imagen = new Bitmap(imagenTemporal, new Size(new Point(200, 200))); imagen.Save(pathFile, ImageFormat.Png); return(pathFile); }
public void Encode_ValidUnicodeContent_ShouldEncodeQrCodeCorrectly() { // Arrange var content = "hello world"; var expectedDataBits = ImageStringToBools(@" +++++++.+.+.+...+.+++++++ +.....+.++...+++..+.....+ +.+++.+.+.+.++.++.+.+++.+ +.+++.+....++.++..+.+++.+ +.+++.+..+...++.+.+.+++.+ +.....+.+..+..+++.+.....+ +++++++.+.+.+.+.+.+++++++ ........++..+..+......... ..+++.+.+++.+.++++++..+++ +++..+..+...++.+...+..+.. +...+.++++....++.+..++.++ ++.+.+.++...+...+.+....++ ..+..+++.+.+++++.++++++++ +.+++...+..++..++..+..+.. +.....+..+.+.....+++++.++ +.+++.....+...+.+.+++...+ +.+..+++...++.+.+++++++.. ........+....++.+...+.+.. +++++++......++++.+.+.+++ +.....+....+...++...++.+. +.+++.+.+.+...+++++++++.. +.+++.+.++...++...+.++..+ +.+++.+.++.+++++..++.+..+ +.....+..+++..++.+.++...+ +++++++....+..+.+..+..+++ "); // Act IBarcode qr = QrEncoder.Encode(content, ErrorCorrectionLevel.H, Encoding.Unicode); // Assert qr.Should().NotBeNull(); expectedDataBits.Length.Should().Be(qr.Bounds.X * qr.Bounds.Y); for (int i = 0; i < expectedDataBits.Length; i++) { int x = i % qr.Bounds.X; int y = i / qr.Bounds.X; qr.At(x, y).Should().Be(expectedDataBits[i], $"of expected bit on index {i}"); } }
//生成带背景图的二维码图片 public static byte[] QRCodeHasBackImg(string text, int size, bool contentImg, string fg = "#000000", string bg = "#FFFFFF") { byte[] result = null; using (MemoryStream ms = new MemoryStream()) { QrEncoder encoder = new QrEncoder(ErrorCorrectionLevel.H); QrCode qr; if (encoder.TryEncode(text, out qr)) { //背景图存在 则生成带背景图的; if (File.Exists(HttpContext.Current.Server.MapPath("~/Images/poster2.jpg")) && contentImg) { Image img = Image.FromFile(HttpContext.Current.Server.MapPath("~/Images/poster2.jpg")); Graphics g = Graphics.FromImage(img); g.DrawImage(img, 0, 0, 400, 600); Bitmap image = null; using (MemoryStream msQR = new MemoryStream()) { GraphicsRenderer renderer = new GraphicsRenderer(new FixedCodeSize(400, QuietZoneModules.Zero), new SolidBrush(ColorTranslator.FromHtml(fg)), new SolidBrush(ColorTranslator.FromHtml(bg))); renderer.WriteToStream(qr.Matrix, ImageFormat.Png, msQR); var imageTemp = new Bitmap(msQR); image = new Bitmap(imageTemp, new Size(new Point(size, size))); } g.DrawImage(image, 245, 74, image.Width, image.Height); GC.Collect(); img.Save(ms, ImageFormat.Jpeg); result = ms.GetBuffer(); } else { //若不存在 则直接生成二维码 GraphicsRenderer renderer = new GraphicsRenderer(new FixedCodeSize(400, QuietZoneModules.Zero), new SolidBrush(ColorTranslator.FromHtml(fg)), new SolidBrush(ColorTranslator.FromHtml(bg))); renderer.WriteToStream(qr.Matrix, ImageFormat.Png, ms); var imageTemp = new Bitmap(ms); var image = new Bitmap(imageTemp, new Size(new Point(size, size))); using (MemoryStream ms2 = new MemoryStream()) { image.Save(ms2, ImageFormat.Jpeg); result = ms2.GetBuffer(); } } } } return(result); }
private void button1_Click(object sender, EventArgs e) { QrEncoder encoder = new QrEncoder(ErrorCorrectionLevel.M); QrCode code = encoder.Encode(txtURL.Text); Gma.QrCodeNet.Encoding.Windows.Render.GraphicsRenderer render = new Gma.QrCodeNet.Encoding.Windows.Render.GraphicsRenderer(new Gma.QrCodeNet.Encoding.Windows.Render.FixedModuleSize(5, Gma.QrCodeNet.Encoding.Windows.Render.QuietZoneModules.Two), Brushes.Black, Brushes.White); using (System.IO.Stream s = new System.IO.MemoryStream()) { render.WriteToStream(code.Matrix, System.Drawing.Imaging.ImageFormat.Png, s); Image img = Image.FromStream(s); pictureBox1.Image = img; } //using (System.IO.FileStream s = new System.IO.FileStream("c:\\1.png", System.IO.FileMode.Create)) //{ // render.WriteToStream(code.Matrix, System.Drawing.Imaging.ImageFormat.Png, s); //} }
private void ShowCode(Graphics g) { QrEncoder qrEncoder = new QrEncoder(ErrorCorrectionLevel.L); QrCode qrCode = qrEncoder.Encode(str); /* * FixedModuleSize---5-----165*165 * FixedModuleSize---4-----132*132 * FixedModuleSize---3-----99*99 * FixedModuleSize---2-----66*66 * FixedModuleSize---1-----33*33 */ FixedModuleSize moduleSize = new FixedModuleSize(4, QuietZoneModules.Two); GraphicsRenderer render = new GraphicsRenderer(moduleSize, Brushes.Black, Brushes.White); Point mP = new Point(627, 595);//设置二维码左上角的位置 render.Draw(g, qrCode.Matrix, mP); }
protected void SaveQrCode(string text, string filename) {//用于保存二维码图像的函数 QrEncoder qrEncoder = new QrEncoder(ErrorCorrectionLevel.M); //设置二维码错误修正率 QrCode qrCode = qrEncoder.Encode(text); //使用text参数进行编码 GraphicsRenderer renderer = new GraphicsRenderer(new FixedModuleSize(5, QuietZoneModules.Two), Brushes.Black, Brushes.White); //实例化Renderer对象, string fileurl = "C://Users//Top//Pictures//Saved Pictures//" + filename + ".png"; using (FileStream stream = new FileStream(fileurl, FileMode.Create)) { renderer.WriteToStream(qrCode.Matrix, ImageFormat.Png, stream); //将二维码矩阵写入文件流,设置图片格式为png } Console.WriteLine("Your QrCode pictures are stored in " + fileurl); }
//生成QRCode的函数 public void DrawQRCode(string qrText) { //pictureBox1重新生成 pictureBox1.Refresh(); //新建QrEncoder类的对象 QrEncoder qrEncoder = new QrEncoder(ErrorCorrectionLevel.M); //新建QrCode类的对象,传入形参 QrCode qrCode = qrEncoder.Encode(qrText); //新建GraphicsRenderer类的对象 GraphicsRenderer render = new GraphicsRenderer(new FixedModuleSize(5, QuietZoneModules.Two), Brushes.Black, Brushes.White); //确定绘图初始点 Point padding = new Point(0, 0); //实例化Graphics类 Graphics graphics = pictureBox1.CreateGraphics(); //将graphics对象导入pictureBox1 render.Draw(graphics, qrCode.Matrix, padding); }
public static MemoryStream generate_QR_Code(string url) { ErrorCorrectionLevel Ecl = ErrorCorrectionLevel.M; //误差校正水平 //string Content = strContent;//待编码内容 QuietZoneModules QuietZones = QuietZoneModules.Two; //空白区域 int ModuleSize = 12; //大小 var encoder = new QrEncoder(Ecl); QrCode qr; MemoryStream ms = new MemoryStream(); if (encoder.TryEncode(url, out qr))//对内容进行编码,并保存生成的矩阵 { var render = new GraphicsRenderer(new FixedModuleSize(ModuleSize, QuietZones)); render.WriteToStream(qr.Matrix, ImageFormat.Png, ms); } ms.Close(); return(ms); }
private void button1_Click(object sender, EventArgs e) { QrEncoder encoder = new QrEncoder(); QrCode qrCode; encoder.TryEncode("http://www.fernandobhz.com.br", out qrCode); GraphicsRenderer gRenderer = new GraphicsRenderer( new FixedModuleSize(10, QuietZoneModules.Four), Brushes.Black, Brushes.White); FileStream fs = new FileStream("C:\\teste.png", FileMode.Create); gRenderer.WriteToStream(qrCode.Matrix, ImageFormat.Png, fs); fs.Close(); }
public static MemoryStream GenQrCode(string content, int size) { QrEncoder qrEncoder = new QrEncoder(ErrorCorrectionLevel.L); QrCode qrCode; qrEncoder.TryEncode(content, out qrCode); GraphicsRenderer render = new GraphicsRenderer(new FixedCodeSize(size, QuietZoneModules.Zero), Brushes.Black, Brushes.Transparent); MemoryStream ms = new MemoryStream(); Bitmap bitmap = new Bitmap(size, size); Graphics graphics = Graphics.FromImage(bitmap); graphics.Clear(System.Drawing.Color.White); render.Draw(graphics, qrCode.Matrix); bitmap.Save(ms, ImageFormat.Jpeg); return(ms); }
public static string GenerateQRCode(string link) { try { QrEncoder qr_encoder = new QrEncoder(); QrCode code = null; qr_encoder.TryEncode(link, out code); GraphicsRenderer renderer = new GraphicsRenderer(new FixedCodeSize(350, QuietZoneModules.Zero), Brushes.Black, Brushes.White); MemoryStream ms = new MemoryStream(); renderer.WriteToStream(code.Matrix, ImageFormat.Png, ms); return(Convert.ToBase64String(ms.GetBuffer())); } catch (Exception ex) { ex.Message.ToString(); return(null); } }
protected override void InitDict() { base.InitDict(); if (cu.type == 1) { Context.Response.Redirect("/wx/user/index.html"); //仅商户有邀请二维码 } var qr = new QrEncoder(); var cd = qr.Encode("http://" + cfg.domain + "/wx/invite-" + cu.id + "-" + cu.no + ".html"); var rd = new GraphicsRenderer(new FixedModuleSize(15, QuietZoneModules.Two)); using (var ms = new MemoryStream()) { rd.WriteToStream(cd.Matrix, ImageFormat.Jpeg, ms); dict.Add("qr", Convert.ToBase64String(ms.ToArray())); } }
/// <summary> /// Generates an img tag with a data uri encoded image of the QR code from the content given. /// </summary> /// <param name="html"> /// </param> /// <param name="content"> /// </param> /// <returns> /// </returns> public static IHtmlString QrCode(this HtmlHelper html, string content) { var enc = new QrEncoder(ErrorCorrectionLevel.H); var code = enc.Encode(content); var r = new Renderer(5, Brushes.Black, Brushes.White); using (var ms = new MemoryStream()) { r.WriteToStream(code.Matrix, ms, ImageFormat.Png); var image = ms.ToArray(); return (html.Raw(String.Format(@"<img src=""data:image/png;base64,{0}"" alt=""{1}"" />", Convert.ToBase64String(image), content))); } }
private void SaveCodeFile(string content, int col_n, string path) { QrEncoder qrEncoder = new QrEncoder(ErrorCorrectionLevel.H); QrCode code = new QrCode(); qrEncoder.TryEncode(content, out code); const int modelSizeInPixels = 4; GraphicsRenderer render = new GraphicsRenderer(new FixedModuleSize(modelSizeInPixels, QuietZoneModules.Two) , Brushes.Black, Brushes.White); //在目标文件夹创建一个空的.bmp文件 string filename = path + "/" + Program.getString(col_n) + Program.GetContSplit(content) + ".bmp"; using (FileStream fs = new FileStream(filename, FileMode.OpenOrCreate, FileAccess.ReadWrite)) { render.WriteToStream(code.Matrix, ImageFormat.Png, fs); } }
Bitmap encodeToBitMap(string data, double dimension_inches, float dpi_x = 600, float dpi_y = 600, ErrorCorrectionLevel correction_level = ErrorCorrectionLevel.L, QuietZoneModules quite_zone = QuietZoneModules.Zero ) { QrEncoder qrEncoder = new QrEncoder(correction_level); QrCode qrCode = qrEncoder.Encode(data); // Calculate number of pixels. Note we use dpi in x direction // but we should probably use whichever is lowest int pixels = (int)(dimension_inches * dpi_x); // Check whether we have enough space //if (pixels < qrCode.Matrix.Width) //throw new Exception("Too small"); ISizeCalculation iSizeCal = new FixedCodeSize(pixels, quite_zone); DrawingBrushRenderer dRenderer = new DrawingBrushRenderer(iSizeCal, System.Windows.Media.Brushes.Black, System.Windows.Media.Brushes.White); //DrawingBrushRenderer dRenderer = new DrawingBrushRenderer(iSizeCal, System.Windows.Media.Brushes.Black, System.Windows.Media.Brushes.LightGray); MemoryStream mem_stream = new MemoryStream(); dRenderer.WriteToStream(qrCode.Matrix, ImageFormatEnum.BMP, mem_stream); Bitmap bitmap = new Bitmap(mem_stream); bitmap.SetResolution(dpi_x, dpi_y); // A different way to do the same. Just incase the bitmap.SetResolution function does not work //System.Windows.Point dpipoint = new System.Windows.Point(dpi, dpi); //BitmapSource bitmapsource = dRenderer.WriteToBitmapSource(qrCode.Matrix, dpipoint); //MemoryStream outStream = new MemoryStream(); //BitmapEncoder bitmapencoder = new BmpBitmapEncoder(); //BitmapFrame bitmapframe = BitmapFrame.Create(bitmapsource); //bitmapencoder.Frames.Add(bitmapframe); //bitmapencoder.Save(outStream); //Bitmap bitmap = new System.Drawing.Bitmap(outStream); return(bitmap); }
public InformacionUsuario(MainWindow mPrincipal) { InitializeComponent(); menuPrincipal = mPrincipal; Thread.CurrentThread.CurrentUICulture = new CultureInfo(Properties.Settings.Default.idioma); AplicarIdioma(); AplicarEstilo(); if (Properties.Settings.Default.tamanoLetra == "P") { AplicarTamanoLetra(-3); } else if (Properties.Settings.Default.tamanoLetra == "G") { AplicarTamanoLetra(3); } else { AplicarTamanoLetra(0); } String textExport = "1111" + "[N]" + Properties.Settings.Default.nombre + "[N]" + "[A]" + Properties.Settings.Default.apellidos + "[A]" + "[AN]" + Properties.Settings.Default.añoNacimiento + "[AN]" + "[P]" + Properties.Settings.Default.peso + "[P]" + "[PRA]" + Properties.Settings.Default.pruebaReflejosAciertos + "[PRA]" + "[PRF]" + Properties.Settings.Default.pruebaReflejosFallos + "[PRF]" + "[D]" + Properties.Settings.Default.Daltonico + "[D]" + "[M]" + Properties.Settings.Default.tipoMovilidad + "[M]"; QrEncoder qrEncoder = new QrEncoder(ErrorCorrectionLevel.H); QrCode qrCode = new QrCode(); qrEncoder.TryEncode(textExport, out qrCode); GraphicsRenderer renderer = new GraphicsRenderer(new FixedCodeSize(400, QuietZoneModules.Zero), System.Drawing.Brushes.Black, System.Drawing.Brushes.White); MemoryStream ms = new MemoryStream(); renderer.WriteToStream(qrCode.Matrix, ImageFormat.Png, ms); var imageTemporal = new Bitmap(ms); var image = new Bitmap(imageTemporal, new System.Drawing.Size(new System.Drawing.Point(200, 200))); System.Windows.Media.Imaging.BitmapSource b = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(image.GetHbitmap(), IntPtr.Zero, System.Windows.Int32Rect.Empty, BitmapSizeOptions.FromWidthAndHeight(image.Width, image.Height)); codigoQR.Source = b; }
/// <summary> /// 写入二维码 /// </summary> /// <param name="entity"></param> private void WriteQRCode(QRCodeEntity entity, Dictionary <string, object> dicSource) { float CurrentTop = entity.Top + this.CurrentHeight; string content = string.Empty; if (entity.ContentType == 2) { content = entity.Content; int beginIndex = content.IndexOf("{{"); int endIndex = content.LastIndexOf("}}"); string key = content.Substring(beginIndex + 2, endIndex - beginIndex - 2); string Value = dicSource.Value <string, object>(key) as string; content = Value; } else if (entity.ContentType == 1) { content = entity.Content; } QrEncoder qrEncoder = new QrEncoder(ErrorCorrectionLevel.H); QrCode qrCode = new QrCode(); qrEncoder.TryEncode(content, out qrCode); using (MemoryStream ms = new MemoryStream()) { if (entity.ModuleSize <= 0 || entity.ModuleSize > 5) { entity.ModuleSize = 3; } GraphicsRenderer renderer = new GraphicsRenderer(new FixedModuleSize(entity.ModuleSize, QuietZoneModules.Two)); renderer.WriteToStream(qrCode.Matrix, ImageFormat.Jpeg, ms); Image image = Image.FromStream(ms); //g.DrawImage(image, new PointF(entity.Left, CurrentTop)); if (entity.Width == 0 || entity.Height == 0) { g.DrawImage(image, entity.Left, CurrentTop); } else { g.DrawImage(image, entity.Left, CurrentTop, entity.Width, entity.Height); } } }
public void QrPerformanceTest() { Stopwatch sw = new Stopwatch(); int timesofTest = 1000; string[] timeElapsed = new string[2]; string testCase = "sdg;alwsetuo1204985lkscvzlkjt;sdfjwltkja;slkdfjoiutLSAFAJ;GLKAJS;LDKJT;LKJ"; QrEncoder encoder = new QrEncoder(ErrorCorrectionLevel.H); sw.Start(); for(int i = 0; i < timesofTest; i++) { encoder.Encode(testCase); } sw.Stop(); timeElapsed[0] = sw.ElapsedMilliseconds.ToString(); sw.Reset(); ErrorCorrectionLevelInternal level = ErrorCorrectionLevelConverter.ToInternal(ErrorCorrectionLevel.H); QRCodeInternal qrCodeInternal = new QRCodeInternal(); sw.Start(); for(int i = 0; i < timesofTest; i++) { EncoderInternal.encode(testCase, level, qrCodeInternal); } sw.Stop(); timeElapsed[1] = sw.ElapsedMilliseconds.ToString(); Assert.Pass("Encode performance {0} Tests~ QrCode.Net: {1} ZXing: {2}", timesofTest, timeElapsed[0], timeElapsed[1]); }
public void Test_against_csv_DataSet(string inputData, ErrorCorrectionLevel errorCorrectionLevel, BitMatrix expectedMatrix) { QrEncoder encoder = new QrEncoder(errorCorrectionLevel); BitMatrix resultMatrix = encoder.Encode(inputData).Matrix; expectedMatrix.AssertEquals(resultMatrix); }