/// <summary> /// 获取二维码 /// </summary> /// <param name="strContent">待编码的字符</param> /// <param name="ms">输出流</param> ///<returns>True if the encoding succeeded, false if the content is empty or too large to fit in a QR code</returns> public static bool GetQRCode(string strContent, string savePath) { var ms = new MemoryStream(); ErrorCorrectionLevel Ecl = ErrorCorrectionLevel.M; //误差校正水平 string Content = strContent; //待编码内容 QuietZoneModules QuietZones = QuietZoneModules.Two; //空白区域 int ModuleSize = 12; //大小 var encoder = new QrEncoder(Ecl); QrCode qr; if (encoder.TryEncode(Content, out qr))//对内容进行编码,并保存生成的矩阵 { try { using (var stream = new FileStream(savePath, FileMode.Create)) { var render = new GraphicsRenderer(new FixedModuleSize(ModuleSize, QuietZones)); render.WriteToStream(qr.Matrix, System.Drawing.Imaging.ImageFormat.Png, stream); } } catch (Exception ex) { return(false); } } else { return(false); } return(true); }
/// <summary> /// 显示二维码 /// </summary> /// <returns></returns> public void ShowQrCode() { try { string code = Request["code"]; QrEncoder qrEncoder = new QrEncoder(ErrorCorrectionLevel.H); QrCode qrCode = new QrCode(); qrEncoder.TryEncode(code, out qrCode); GraphicsRenderer renderer = new GraphicsRenderer(new FixedModuleSize(5, QuietZoneModules.Two), Brushes.Black, Brushes.White); using (MemoryStream ms = new MemoryStream()) { renderer.WriteToStream(qrCode.Matrix, ImageFormat.Png, ms); Image img = Image.FromStream(ms); img.Save(Response.OutputStream, ImageFormat.Jpeg); } } catch (Exception ex) { throw; } }
private void GenerarCodigoQR() { string texto = this.tb_texto.Text.Trim(); //si el text box no tiene valores nulos ni esta limpio if (!string.IsNullOrEmpty(texto)) { QrEncoder qrEncoder = new QrEncoder(ErrorCorrectionLevel.H); QrCode qrCode = new QrCode(); try { //tratamos de convertir el texto en codigo qr qrEncoder.TryEncode(texto, out qrCode); GraphicsRenderer renderer = new GraphicsRenderer(new FixedCodeSize(400, QuietZoneModules.Zero), Brushes.Black, Brushes.FloralWhite); MemoryStream ms = new MemoryStream(); renderer.WriteToStream(qrCode.Matrix, ImageFormat.Png, ms); var imagen_temporal = new Bitmap(ms); var imagen = new Bitmap(imagen_temporal, new Size(new Point(200, 200))); pn_generador.BackgroundImage = imagen_temporal; } catch (Exception ex) { MessageBox.Show(ex.Message, "Información", MessageBoxButtons.OK, MessageBoxIcon.Asterisk); } GC.Collect(); } else { MessageBox.Show("Escribe algo flojo :v", "Información", MessageBoxButtons.OK, MessageBoxIcon.Information); tb_texto.Focus(); } }
/// <summary> /// Méthode retournant un objet d'image Bitmap d'un code QR /// </summary> /// <param name="text">Le texte à encoder</param> /// <param name="errorCorrection">Le niveau de correction d'erreur choisi. Détermine le pourcentage de la structure du codeQR est utilisé pour corriger les erreurs.</param> /// <returns>Objet BitmapImage du codeQR</returns> public static BitmapImage getQrBitmap(string text, ErrorCorrectionLevel errorCorrection = ErrorCorrectionLevel.M) { QrCode qrCode; QrEncoder qrEncoder = new QrEncoder(errorCorrection); //Peut techniquement échouer et le cas n'est pas géré. qrEncoder.TryEncode(text, out qrCode); //Détermine l'épaisseur des traits, la couleur de fond et la couleur du code QR. GraphicsRenderer gRenderer = new GraphicsRenderer( new FixedModuleSize(2, QuietZoneModules.Two), Brushes.Black, Brushes.White); BitmapImage bi = new BitmapImage(); using (MemoryStream memoryStream = new MemoryStream()) { //Utilise les bytes du codeQR encodé qui se trouve dans l'objet qrCode dans un MemoryStream pour faire une BitmapImage. gRenderer.WriteToStream(qrCode.Matrix, ImageFormat.Png, memoryStream); bi.BeginInit(); bi.CacheOption = BitmapCacheOption.OnLoad; bi.StreamSource = memoryStream; bi.EndInit(); } return(bi); }
private void CreateFile(QrCodePart part) { var item = _contentManager.Get(part.ContentItem.Id); if (item != null && item.Has <QrCodePart>()) { var qrEncoder = new QrEncoder(ErrorCorrectionLevel.M); var qrCode = new QrCode(); var thevalue = string.IsNullOrWhiteSpace(part.Record.Value) ? part.Settings.GetModel <QrCodeTypePartSettings>().Value : part.Record.Value; var tokens = new Dictionary <string, object> { { "Content", part.ContentItem } }; thevalue = _tokenizer.Replace(thevalue, tokens); if (qrEncoder.TryEncode(thevalue, out qrCode)) { var renderer = new GraphicsRenderer(new FixedCodeSize(item.As <QrCodePart>().Size, QuietZoneModules.Zero), Brushes.Black, Brushes.White); var stream = new MemoryStream(); renderer.WriteToStream(qrCode.Matrix, ImageFormat.Png, stream); stream.Position = 0; var outputPath = _orchardServices.WorkContext.HttpContext.Server.MapPath(string.Format("~/Media/{0}/qrcode", _shellSettings.Name)); if (!Directory.Exists(outputPath)) { Directory.CreateDirectory(outputPath); } var filename = outputPath + @"\qrcode_" + part.ContentItem.Id.ToString() + ".png"; using (FileStream file = new FileStream(filename, FileMode.Create, System.IO.FileAccess.Write)) { var bytes = new byte[stream.Length]; stream.Read(bytes, 0, (int)stream.Length); file.Write(bytes, 0, bytes.Length); stream.Close(); } } } }
static void Main(string[] args) { String Folio_val = args[0]; string path = Directory.GetCurrentDirectory(); // String Folio_val = "https://www.google.com"; // String Direccion = "http://rppccolimaevidencias.col.gob.mx:8182/evidencia/Certi2?Secuence=" + Folio_val; String Direccion = Folio_val; QrEncoder qrEncoder = new QrEncoder(ErrorCorrectionLevel.H); QrCode qrCode = new QrCode(); qrEncoder.TryEncode(Direccion, out qrCode); GraphicsRenderer render = new GraphicsRenderer(new FixedModuleSize(400, QuietZoneModules.Zero), Brushes.Black, Brushes.White); MemoryStream ms = new MemoryStream(); render.WriteToStream(qrCode.Matrix, ImageFormat.Jpeg, ms); var imagenTemporal = new Bitmap(ms); var imagen = new Bitmap(imagenTemporal, new Size(new Point(200, 200))); imagen.Save(@path + "\\codigo.jpeg", ImageFormat.Jpeg); using (Document doc = new Document(PageSize.LETTER, 30f, 20f, 50f, 40f)) { PdfWriter writer = PdfWriter.GetInstance(doc, new FileStream(@path + "\\prueba.pdf", FileMode.Create)); writer.PageEvent = new HeaderFooter(); doc.Open(); iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(@path + "\\codigo.jpeg"); iTextSharp.text.Font _standardFont = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 8, iTextSharp.text.Font.NORMAL, BaseColor.BLACK); img.SetAbsolutePosition(500, 700); img.ScaleToFit(50f, 50F); doc.Add(img); doc.Close(); writer.Close(); } Console.WriteLine(Folio_val); }
public static MemoryStream GenQrCode(string content, int size, Image logo) { QrEncoder qrEncoder = new QrEncoder(ErrorCorrectionLevel.L); QrCode qrCode; qrEncoder.TryEncode(content, out qrCode); GraphicsRenderer render = new GraphicsRenderer(new FixedCodeSize(size, QuietZoneModules.Two), 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); //计算画框的宽度高度以及位置 float rectWidth = logo.Width; float rectHeight = logo.Height; float rectX = (size - logo.Width) / 2; float rectY = (size - logo.Height) / 2; //加上水印 graphics.DrawImage(logo, rectX, rectY, rectWidth, rectHeight); bitmap.Save(ms, ImageFormat.Jpeg); return(ms); }
private static WriteableBitmap RenderQrcodeImage(string data) { try { QrEncoder encoder = new QrEncoder(ErrorCorrectionLevel.M); QrCode qrCode; encoder.TryEncode(data, out qrCode); WriteableBitmapRenderer wRenderer = new WriteableBitmapRenderer(new FixedModuleSize(2, QuietZoneModules.Two), Colors.Black, Colors.White); WriteableBitmap wBitmap = new WriteableBitmap(70, 70, 96, 96, PixelFormats.Gray8, null); wRenderer.Draw(wBitmap, qrCode.Matrix); return(wBitmap); } catch (Exception) { QrEncoder encoder = new QrEncoder(ErrorCorrectionLevel.M); QrCode qrCode; encoder.TryEncode("test", out qrCode); WriteableBitmapRenderer wRenderer = new WriteableBitmapRenderer(new FixedModuleSize(2, QuietZoneModules.Two), Colors.Black, Colors.White); WriteableBitmap wBitmap = new WriteableBitmap(70, 70, 96, 96, PixelFormats.Gray8, null); wRenderer.Draw(wBitmap, qrCode.Matrix); return(wBitmap); } }
/// <summary> /// 生成二维码图片 /// </summary> /// <param name="codeContent"></param> /// <param name="fileName"></param> /// <returns></returns> public static bool CreateImgCode(string codeContent, string fileName) { bool flag = false; try { string path = Path.GetDirectoryName(fileName); if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } //创建二维码生成类 QrEncoder qrEncoder = new QrEncoder(ErrorCorrectionLevel.M); QrCode qrCode = new QrCode(); qrEncoder.TryEncode(codeContent, out qrCode); GraphicsRenderer gRender = new GraphicsRenderer(new FixedModuleSize(30, QuietZoneModules.Four)); BitMatrix matrix = qrCode.Matrix; //qrCodeGraphicControl1.GetQrMatrix(); using (FileStream stream = new FileStream(fileName, FileMode.Create)) { gRender.WriteToStream(matrix, System.Drawing.Imaging.ImageFormat.Png, stream, new Point(600, 600)); } flag = true; } catch (Exception ex) { ClassLoger.Error("QrCodeHelper.Create_ImgCode"); } return(flag); }
/// <summary> /// 生成二维码 /// </summary> /// <param name="content">内容</param> /// <param name="filePath">保存文件路径</param> /// <param name="errorMessage">错误异常消息</param> /// <returns></returns> public static bool Generate(string content, string filePath, out string errorMessage) { errorMessage = string.Empty; var qrEncoder = new QrEncoder(ErrorCorrectionLevel.H); try { QrCode qrCode; qrEncoder.TryEncode(content, out qrCode); var renderer = new Renderer(5, Brushes.Black, Brushes.White); if (!Directory.Exists(Path.GetDirectoryName(filePath))) { Directory.CreateDirectory(Path.GetDirectoryName(filePath)); } else { FileInfo fileInfo = new FileInfo(filePath); if (fileInfo.Exists) { fileInfo.Delete(); } } renderer.CreateImageFile(qrCode.Matrix, filePath, ImageFormat.Png); return(true); } catch (Exception ex) { errorMessage = ex.Message; return(false); } }
/// 获取二维码 /// </summary> /// <param name="content">内容</param> /// <param name="ModuleSize">大小(数值*25px)</param> /// <returns>二维码图片</returns> public Bitmap GetQRCode(string content, int ModuleSize) { Bitmap bitmap = null; try { //生成二维码 using (MemoryStream ms = new MemoryStream()) { ErrorCorrectionLevel Ecl = ErrorCorrectionLevel.M; //误差校正水平 string Content = content; //待编码内容 QuietZoneModules QuietZones = QuietZoneModules.Two; //空白区域 var encoder = new QrEncoder(Ecl); QrCode qr; if (encoder.TryEncode(Content, out qr))//对内容进行编码,并保存生成的矩阵 { var render = new GraphicsRenderer(new FixedModuleSize(ModuleSize, QuietZones)); render.WriteToStream(qr.Matrix, ImageFormat.Png, ms); } bitmap = new Bitmap(ms); } } catch (Exception e) { throw e; } return(bitmap); }
private void button1_Click(object sender, EventArgs e) { /// generar un codigo QR para los elementos de la caja // crear un encoder, codificador QrEncoder Codificador = new QrEncoder(ErrorCorrectionLevel.H); // crear un codigo QR QrCode Codigo = new QrCode(); // generar generar un codigo apartir de datos, y pasar el codigo por referencia Codificador.TryEncode(textBox1.Text, out Codigo); // generar un graficador GraphicsRenderer Renderisado = new GraphicsRenderer(new FixedCodeSize(200, QuietZoneModules.Zero), Brushes.Black, Brushes.White); // generar un flujo de datos MemoryStream ms = new MemoryStream(); // escribir datos en el renderizado Renderisado.WriteToStream(Codigo.Matrix, ImageFormat.Png, ms); // generar controles para ponerlos en el form var ImagenQR = new Bitmap(ms); var ImgenSalida = new Bitmap(ImagenQR, new Size(panel1.Width, panel1.Height)); // asignar la imagen al panel panel1.BackgroundImage = ImgenSalida; }
public bool GetQRCode(string strContent, string path, string backgroundPath, int width, int height, int x, int y, MemoryStream ms) { ErrorCorrectionLevel Ecl = ErrorCorrectionLevel.M; //误差校正水平 string Content = strContent; //待编码内容 QuietZoneModules QuietZones = QuietZoneModules.Two; //空白区域 int ModuleSize = 12; //大小 var encoder = new QrEncoder(Ecl); QrCode qr; if (encoder.TryEncode(Content, out qr))//对内容进行编码,并保存生成的矩阵 { var render = new GraphicsRenderer(new FixedModuleSize(ModuleSize, QuietZones)); render.WriteToStream(qr.Matrix, ImageFormat.Png, ms); Bitmap b = new Bitmap(width, height); Graphics g = Graphics.FromImage(b); using (FileStream fs = new FileStream(backgroundPath, FileMode.Open)) { Bitmap bmp = new Bitmap(fs); Bitmap bmp2 = new Bitmap(ms); // Graphics g2 = Graphics.FromImage(bmp); g.DrawImage(bmp2, new Rectangle(x, y, width, height)); bmp.Save(path); } } else { return(false); } return(true); }
/// <summary> /// 获取二维码 /// </summary> /// <param name="strContent">待编码的字符</param> /// <param name="ms">输出流</param> ///<returns>True if the encoding succeeded, false if the content is empty or too large to fit in a QR code</returns> public static bool GetQRCode(string strContent, MemoryStream ms) { try { //误差校正水平 ErrorCorrectionLevel Ecl = ErrorCorrectionLevel.M; //待编码内容 string Content = strContent; //空白区域 QuietZoneModules QuietZones = QuietZoneModules.Two; //大小 int ModuleSize = 7; var encoder = new QrEncoder(Ecl); QrCode qr; //对内容进行编码,并保存生成的矩阵 if (encoder.TryEncode(Content, out qr)) { var render = new GraphicsRenderer(new FixedModuleSize(ModuleSize, QuietZones)); render.WriteToStream(qr.Matrix, ImageFormat.Png, ms); } else { return(false); } } catch (Exception ex) { LogHelper.Error(ex); } finally { } return(true); }
/// <summary> /// 获取二维码 /// </summary> /// <param name="strContent">待编码的字符</param> /// <param name="ms">输出流</param> ///<returns>True if the encoding succeeded, false if the content is empty or too large to fit in a QR code</returns> public static bool GetQRCode(string strContent, MemoryStream ms) { try { ErrorCorrectionLevel Ecl = ErrorCorrectionLevel.M; //误差校正水平 string Content = strContent; //待编码内容 QuietZoneModules QuietZones = QuietZoneModules.Two; //空白区域 int ModuleSize = 12; //大小 var encoder = new QrEncoder(Ecl); QrCode qr; if (encoder.TryEncode(Content, out qr))//对内容进行编码,并保存生成的矩阵 { var render = new GraphicsRenderer(new FixedModuleSize(ModuleSize, QuietZones)); render.WriteToStream(qr.Matrix, ImageFormat.Png, ms); } else { return(false); } return(true); } catch { return(false); } }
protected void Page_Load(object sender, EventArgs e) { var api = Request["Api"]; if (String.IsNullOrEmpty(api)) { return; } var manager = new OAuthHelper(ConfigurationManager.AppSettings["wxappid"]); var url = manager.BuildOAuthUrl("http://wx.taogame.com/OAuthUserInfoDemo.aspx", api == "snsapi_base" ? OAuthScope.Base : OAuthScope.UserInfo, api); QrEncoder encoder = new QrEncoder(ErrorCorrectionLevel.M); QrCode qrCode; encoder.TryEncode(url, out qrCode); GraphicsRenderer gRenderer = new GraphicsRenderer( new FixedModuleSize(2, QuietZoneModules.Two), Brushes.Black, Brushes.White); MemoryStream ms = new MemoryStream(); gRenderer.WriteToStream(qrCode.Matrix, ImageFormat.Jpeg, ms); Response.BinaryWrite(ms.ToArray()); }
StreamGeometry CreateQrCode(string qrContent) { try { QrEncoder qrEncoder = new QrEncoder(ErrorCorrectionLevel.H); QrCode qrCode = new QrCode(); qrEncoder.TryEncode(qrContent, out qrCode); //StreamGeometry geometry = PathRender.DrawEllipseGeometry(qrCode.Matrix, 1, 1, false); //drawing1.Geometry = geometry; //double w = geometry.Bounds.Width / 4; //double h = geometry.Bounds.Height / 4; //double x = geometry.Bounds.Width / 2 - w / 2; //double y = geometry.Bounds.Height / 2 - h / 2; //drawIcon1.Rect = new Rect(x, y, w, h); var geometry = PathRender.DrawRectGeometry(qrCode.Matrix, 1, 1, false); //qrDrawing.Geometry = geometry; return(geometry); } catch (Exception ex) { MessageBox.Show(ex.Message); } return(null); }
/// <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)); } }
static void Main(string[] args) { QrEncoder qr = new QrEncoder(ErrorCorrectionLevel.M); QrCode myQrCode = new QrCode(); bool isSuccess = qr.TryEncode("This is a test", out myQrCode); if (isSuccess == true) { Console.WriteLine($"QrCode Matrix Height:{myQrCode.Matrix.Height}, Wide={myQrCode.Matrix.Width}"); int qrsize = myQrCode.Matrix.Width; if (qrsize < 600) { qrsize = 600; } else { qrsize += 600; } ImageFormat imageFormat = ImageFormat.Png; GraphicsRenderer qrRender = new GraphicsRenderer( new FixedCodeSize(qrsize, QuietZoneModules.Two)); FileStream imgFile = new FileStream($".\\abc3.{imageFormat}", FileMode.Create); qrRender.WriteToStream(myQrCode.Matrix, imageFormat, imgFile); imgFile.Close(); } }
public byte[] Generator(string codeString, int size) { this.qrCodeSize = size; this.qrCodeString = codeString; QrEncoder qrEncoder = new QrEncoder(ErrorCorrectionLevel.H); Gma.QrCodeNet.Encoding.QrCode qrCode = new Gma.QrCodeNet.Encoding.QrCode(); qrEncoder.TryEncode(QrCodeString, out qrCode); var renderer = new GraphicsRenderer(new FixedCodeSize(QrCodeSize, QuietZoneModules.Zero), Brushes.Black, Brushes.White); MemoryStream stream = new MemoryStream(); renderer.WriteToStream(qrCode.Matrix, ImageFormat.Png, stream); byte[] qrCodeBuffer = null; try { qrCodeBuffer = stream.ToBuffer(); } catch (Exception exception) { SimpleConsole.WriteLine("Generator qr code fail. exception message:" + exception.Message); } return(qrCodeBuffer); }
private void codigoqr(string folio) { try { string valor = folio; QrEncoder qrEncoder = new QrEncoder(ErrorCorrectionLevel.H); QrCode qrCode = new QrCode(); qrEncoder.TryEncode(valor, 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); imagen = new Bitmap(imageTemporal, new Size(new Point(100, 100))); //imagen.Save("imagen.png", ImageFormat.Png); // Guardar en el disco duro la imagen (Carpeta del proyecto) } catch (Exception err) { string error = err.Message; MessageBox.Show("Ocurrio un Error con qr, intente de nuevo."); string funcion = "codigoqr"; Utilerias.LOG.write(_clase, funcion, error); } }
/// <summary> /// 生成二维码图片 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void button2_Click(object sender, EventArgs e) { List <string> list = new List <string>() { "TK101", "TK102", "TK103", "TK104", "TK201", "TK202", "TK203", "TK204", "TK205", "TK206", "TK207", "TK208", "TK209", "TK210", "TK211", "TK212", "TK213", "TK214", "TK301", "TK302", "TK303", "TK304", "TK401", "TK402", "TK403", "TK404", "TK405", "TK406", "TK407", "TK408", "TK409", "TK410", "TK411", "TK412", "TK413", "TK414", }; foreach (string str in list) { string Content = str; QrEncoder qrEncoder = new QrEncoder(ErrorCorrectionLevel.H); QrCode qrCode = new QrCode(); qrEncoder.TryEncode(Content, out qrCode); using (MemoryStream ms = new MemoryStream()) { GraphicsRenderer renderer = new GraphicsRenderer(new FixedModuleSize(18, QuietZoneModules.Two), Brushes.White, Brushes.MidnightBlue); renderer.WriteToStream(qrCode.Matrix, ImageFormat.Jpeg, ms); Image image = Image.FromStream(ms); image.Save(str + ".jpg"); } } }
private void btnConsultarLibro_Click(object sender, EventArgs e) { clsInventario objConsultaLibro = new clsInventario(); objConsultaLibro.CodigoLibro = txtCodLibro.Text; QrEncoder qrEncoder = new QrEncoder(ErrorCorrectionLevel.H); QrCode qrCode = new QrCode(); qrEncoder.TryEncode(txtCodLibro.Text, out qrCode); GraphicsRenderer renderer = new GraphicsRenderer(new FixedCodeSize(150, QuietZoneModules.Zero), Brushes.Black, Brushes.White); MemoryStream ms = new MemoryStream();//Crear memoria de conjunto de datos, para almacenar el cod qr renderer.WriteToStream(qrCode.Matrix, ImageFormat.Png, ms); var imageTemporal = new Bitmap(ms); var imagen = new Bitmap(imageTemporal, new Size(new Point(150, 150)));// panelResultado.BackgroundImage = imagen; imagen.Save("QR.png", ImageFormat.Png); btnImprimir.Enabled = true; objConsultaLibro.consultarLibro(GridViewLibros); if (txtCodLibro.Text == "") { objConsultaLibro.cargarInventario(GridViewLibros); } txtCodLibro.Clear(); }
Bitmap ComputeQRCode(int slice) { var qrEncoder = new QrEncoder(FErrorCorrectionLevel[slice]); var qrCode = new QrCode(); if (qrEncoder.TryEncode(FText[slice], out qrCode)) { using (var fore = new SolidBrush(FForeColor[slice].Color)) using (var back = new SolidBrush(FBackColor[slice].Color)) { var renderer = new GraphicsRenderer(new FixedModuleSize(FPixelSize[slice], FQuietZoneModules[slice]), fore, back); DrawingSize dSize = renderer.SizeCalculator.GetSize(qrCode.Matrix.Width); var bmp = new Bitmap(dSize.CodeWidth, dSize.CodeWidth); using (var g = Graphics.FromImage(bmp)) renderer.Draw(g, qrCode.Matrix); return(bmp); } } else { return(null); } }
/// <summary> /// Prints a QR Code on the console output. /// </summary> /// <param name="URI">URI to encode.</param> public static void PrintQRCode(string URI) { QrEncoder encoder = new QrEncoder(ErrorCorrectionLevel.M); if (encoder.TryEncode(URI, out QrCode qrCode)) { ConsoleColor Bak = Console.BackgroundColor; BitMatrix Matrix = qrCode.Matrix; int w = Matrix.Width; int h = Matrix.Height; int x, y; for (y = -3; y < h + 3; y++) { for (x = -3; x < w + 3; x++) { if (x >= 0 && x < w && y >= 0 && y < h && Matrix[x, y]) { Console.BackgroundColor = ConsoleColor.Black; Console.Out.Write(" "); } else { Console.BackgroundColor = ConsoleColor.White; Console.Out.Write(" "); } } Console.Out.WriteLine(); } Console.BackgroundColor = Bak; } }
public SaveIamge CreateQR(string helpId) { QrEncoder qrEncoder = new QrEncoder(ErrorCorrectionLevel.H); QrCode qrCode = new QrCode(); string url = ConfigurationManager.AppSettings["imgMapPath"] + "WxOrder/HelpClass?helpId=" + helpId; //string url = CommonHelper.GetRedirect("WxOrder%2fHelpClass?helpId=" + helpId); qrEncoder.TryEncode(url, out qrCode); GraphicsRenderer renderer = new GraphicsRenderer(new FixedModuleSize(3, QuietZoneModules.Two), Brushes.Black, Brushes.White); string filename = string.Format("{0}.png", helpId); string saveUrl = "/Images/QR/"; string filePath = Path.Combine(HttpContext.Server.MapPath(saveUrl), filename); using (MemoryStream ms = new MemoryStream()) { renderer.WriteToStream(qrCode.Matrix, ImageFormat.Png, ms); Image img = Image.FromStream(ms); img.Save(filePath); } string showImg = CommonHelper.LinkImageUrl(saveUrl); SaveIamge model = new SaveIamge() { filename = filename, showImg = HttpContext.Server.MapPath(saveUrl) }; return(model); }
public ActionResult GenerateQrCode() { var userName = User.Identity.Name; var user = _userService.GetUserById(User.Identity.GetUserId()); string barcodeText = userName + "_" + user.PasswordHash; var qrEncoder = new QrEncoder(ErrorCorrectionLevel.H); var qrCode = new QrCode(); qrEncoder.TryEncode(barcodeText, out qrCode); var renderer = new GraphicsRenderer(new FixedModuleSize(4, QuietZoneModules.Four), Brushes.Black, Brushes.White); Stream memoryStream = new MemoryStream(); renderer.WriteToStream(qrCode.Matrix, ImageFormat.Png, memoryStream); memoryStream.Position = 0; var resultStream = new FileStreamResult(memoryStream, "image/png") { FileDownloadName = $"uStora_qr_{userName}_{DateTime.Now:yyyyMMddhhmmsss}.png" }; user.QrCode = barcodeText; _userService.SaveChanges(); return(resultStream); }
private void exportarDatos_Click(object sender, RoutedEventArgs e) { 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(600, 600))); SaveFileDialog sv = new SaveFileDialog(); sv.Filter = "Image PNG (*.png)|*.png"; sv.ShowDialog(); if (!string.IsNullOrEmpty(sv.FileName)) { image.Save(sv.FileName, ImageFormat.Png); } image.Dispose(); }
private void frmRepLibros_QR_Load(object sender, EventArgs e) { List <Libros> Lista_L = new List <Libros>(); foreach (Libros item in Lista) { QrEncoder qrEncoder = new QrEncoder(ErrorCorrectionLevel.H); QrCode qrCode = new QrCode(); qrEncoder.TryEncode(item.Id.ToString(), 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(145, 125))); ImageConverter converter = new ImageConverter(); item.Codigo = (byte[])converter.ConvertTo(imagen, typeof(byte[])); Lista_L.Add(item); } reportViewer1.LocalReport.DataSources.Clear(); reportViewer1.LocalReport.DataSources.Add(new Microsoft.Reporting.WinForms.ReportDataSource("dsLibros_QR", Lista_L)); this.reportViewer1.RefreshReport(); }
protected void GenerateQRCode() { if (_borderQRCode == null || _qrCodeRect == null) { return; } if (string.IsNullOrWhiteSpace(ItemURL)) { _borderQRCode.Visibility = Visibility.Collapsed; return; } try { QrEncoder encoder = new QrEncoder(ErrorCorrectionLevel.M); QrCode qrCode; if (encoder.TryEncode(ItemURL, out qrCode)) { DrawingBrushRenderer dRenderer = new DrawingBrushRenderer(new FixedModuleSize(2, QuietZoneModules.Two), System.Windows.Media.Brushes.Black, System.Windows.Media.Brushes.White); System.Windows.Media.DrawingBrush dBrush = dRenderer.DrawBrush(qrCode.Matrix); _qrCodeRect.Fill = dBrush; _borderQRCode.Visibility = System.Windows.Visibility.Visible; } else { _borderQRCode.Visibility = System.Windows.Visibility.Collapsed; } } catch { _borderQRCode.Visibility = System.Windows.Visibility.Collapsed; } }