Ejemplo n.º 1
0
        /// <summary>
        /// 生成带Logo二维码
        /// </summary>
        /// <param name="content">内容</param>
        /// <param name="iconPath">logo路径</param>
        /// <param name="moduleSize">二维码的大小</param>
        /// <returns>输出流</returns>
        public static MemoryStream GetQRCode(string content, string iconPath, int moduleSize = 9)
        {
            QrEncoder qrEncoder = new QrEncoder(ErrorCorrectionLevel.M);
            QrCode    qrCode    = qrEncoder.Encode(content);

            GraphicsRenderer render = new GraphicsRenderer(new FixedModuleSize(moduleSize, QuietZoneModules.Two), Brushes.Black, Brushes.White);

            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);

            //追加Logo图片 ,注意控制Logo图片大小和二维码大小的比例
            //PS:追加的图片过大超过二维码的容错率会导致信息丢失,无法被识别
            System.Drawing.Image img = System.Drawing.Image.FromFile(iconPath);

            Point imgPoint = new Point((map.Width - img.Width) / 2, (map.Height - img.Height) / 2);

            g.DrawImage(img, imgPoint.X, imgPoint.Y, img.Width, img.Height);

            MemoryStream memoryStream = new MemoryStream();

            map.Save(memoryStream, ImageFormat.Jpeg);

            return(memoryStream);

            //生成图片的代码: map.Save(fileName, ImageFormat.Jpeg);//fileName为存放的图片路径
        }
Ejemplo n.º 2
0
        static void Main(string[] args)
        {
            Console.Write("请输入文本(小于100个字符):");
            string    sampleText = Console.ReadLine();
            QrEncoder qrEncoder  = new QrEncoder(ErrorCorrectionLevel.M);
            QrCode    qrCode     = qrEncoder.Encode(sampleText);

            if (sampleText.Length > 100)
            {
                Console.WriteLine("提示:文本信息过长!");
            }
            else
            {
                for (int j = 0; j < qrCode.Matrix.Width; j++)
                {
                    for (int i = 0; i < qrCode.Matrix.Width; i++)
                    {
                        char charToPrint = qrCode.Matrix[i, j] ? ' ' : '■';
                        Console.Write(charToPrint);
                    }
                    Console.WriteLine();
                }
                Console.WriteLine("按任意键退出:");
                Console.ReadKey();
            }
        }
Ejemplo n.º 3
0
        //生成二维码
        private void button2_Click(object sender, EventArgs e)
        {
            if (url == "")
            {
                label1.Text = "您未选中任何数据!";
            }
            else
            {
                string file1 = "./url1.png";

                QrEncoder qrEncoder = new QrEncoder(ErrorCorrectionLevel.M);
                QrCode    qrCode    = qrEncoder.Encode(url);
                //保存成png文件

                GraphicsRenderer render = new GraphicsRenderer(new FixedModuleSize(5, QuietZoneModules.Two), Brushes.Black, Brushes.White);

                FileStream stream = new FileStream(file1, FileMode.Create);

                using (stream)
                {
                    render.WriteToStream(qrCode.Matrix, ImageFormat.Png, stream);
                }
                stream.Close();

                FileStream pFileStream = new FileStream(file1, FileMode.Open, FileAccess.Read);
                pictureBox1.Image = Image.FromStream(pFileStream);
                pFileStream.Close();
                pFileStream.Dispose();
            }
        }
Ejemplo n.º 4
0
        public void Pulsera(string loteCanal, int numeroCanal)
        {
            string lString = loteCanal + ":::" + numeroCanal.ToString();
            string lRuta   = Path.GetTempPath().ToString() + numeroCanal + "qrCode.bmp";

            QrEncoder encoder = new QrEncoder(ErrorCorrectionLevel.H);
            QrCode    lQrCode = encoder.Encode(lString);

            GraphicsRenderer renderer = new GraphicsRenderer(new FixedModuleSize(5, QuietZoneModules.Two), Brushes.Black, Brushes.White);

            FileStream fileStream = new FileStream(lRuta, FileMode.Create);

            renderer.WriteToStream(lQrCode.Matrix, ImageFormat.Bmp, fileStream);
            fileStream.Close();

            Image imageQRCode = Image.FromFile(lRuta);

            //FIN

            this.rvVisorReportes.LocalReport.DataSources.Clear();
            this.dataSet.Clear();
            this.dataTable.Clear();

            this.dataTable = new DataTable("Pulsera");

            DataColumn colLote = new DataColumn();

            colLote.DataType   = System.Type.GetType("System.String");
            colLote.ColumnName = "lote";

            DataColumn colNumeroCanal = new DataColumn();

            colNumeroCanal.DataType   = System.Type.GetType("System.Int32");
            colNumeroCanal.ColumnName = "numeroCanal";

            DataColumn colQRCode = new DataColumn();

            colQRCode.DataType   = System.Type.GetType("System.Byte[]");
            colQRCode.ColumnName = "qrCode";

            this.dataTable.Columns.Add(colLote);
            this.dataTable.Columns.Add(colNumeroCanal);
            this.dataTable.Columns.Add(colQRCode);

            this.dataRow = this.dataTable.NewRow();

            this.dataRow["lote"]        = loteCanal;
            this.dataRow["numeroCanal"] = numeroCanal;
            this.dataRow["qrCode"]      = GetBytes(imageQRCode);
            this.dataTable.Rows.Add(this.dataRow);
            this.dataSet.Tables.Add(this.dataTable);

            this.reportDataSource = new ReportDataSource("Pulsera", this.dataTable);
            this.rvVisorReportes.LocalReport.DataSources.Add(this.reportDataSource);

            this.rvVisorReportes.LocalReport.ReportEmbeddedResource = "FYRASA.Informes.Pulsera.rdlc";

            this.rvVisorReportes.RefreshReport();
            this.ShowDialog();
        }
Ejemplo n.º 5
0
        public void ShouldFailInParallelRunning()
        {
            // Arrange
            var qrEncoder = new QrEncoder(ErrorCorrectionLevel.M);
            var qrCode    = qrEncoder.Encode("Hello World");
            var list      = new List <Task>();

            // Act
            for (var i = 0; i < 1000; i++)
            {
                list.Add(Task.Factory.StartNew(() =>
                {
                    using (var ms = new MemoryStream())
                    {
                        var renderer = new GraphicsRenderer(new FixedModuleSize(5, QuietZoneModules.Two), Brushes.Black, Brushes.White);
                        renderer.WriteToStream(qrCode.Matrix, ImageFormat.Png, ms);
                    }
                }));
            }

            // Assert
            Assert.ThrowsException <AggregateException>(() =>
            {
                Task.WaitAll(list.ToArray());
            });
        }
Ejemplo n.º 6
0
        public void Test_against_reference_implementation(string inputData, ErrorCorrectionLevel errorCorrectionLevel, BitMatrix expectedMatrix)
        {
            QrEncoder encoder      = new QrEncoder(errorCorrectionLevel);
            BitMatrix resultMatrix = encoder.Encode(inputData).Matrix;

            expectedMatrix.AssertEquals(resultMatrix);
        }
Ejemplo n.º 7
0
        //To generate QRCode
        public string GenerateQRCode(string BookID, string BookName)
        {
            string qr_id = "";

            try
            {
                var  qrEncoder = new QrEncoder(ErrorCorrectionLevel.H);
                var  qrCode    = qrEncoder.Encode(BookID + BookName);
                long i         = 1;
                foreach (byte b in Guid.NewGuid().ToByteArray())
                {
                    i *= ((int)b + 1);
                }
                qr_id = String.Format("{0:d9}", (DateTime.Now.Ticks / 10) % 1000000000);
                var    renderer = new GraphicsRenderer(new FixedModuleSize(5, QuietZoneModules.Two), Brushes.Black, Brushes.White);
                string path     = "F:/k_dev/QRCodes/" + BookID + ".png";
                using (var stream = new FileStream(path, FileMode.Create))
                    renderer.WriteToStream(qrCode.Matrix, ImageFormat.Png, stream);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return(qr_id + ".png");
        }
Ejemplo n.º 8
0
        private void button4_Click(object sender, EventArgs e)
        {
            QrEncoder qrEncoder = new QrEncoder(ErrorCorrectionLevel.M);
            QrCode    qrCode    = qrEncoder.Encode(_demoString);
            //保存成png文件
            string filename = @"QRCodeResize.png";
            //ModuleSize 设置图片大小
            //QuietZoneModules 设置周边padding

            /*
             * 5----150*150    padding:5 最终165*165
             * 10----300*300   padding:10 最终330 * 330
             * 20----600*600   padding:20 最终660 * 660
             */
            //GraphicsRenderer render = new GraphicsRenderer(new FixedModuleSize(10, QuietZoneModules.Two), Brushes.Black, Brushes.White);
            GraphicsRenderer render = new GraphicsRenderer(new FixedModuleSize(20, QuietZoneModules.Two), Brushes.Black, Brushes.White);


            using (FileStream stream = new FileStream(filename, FileMode.Create))
            {
                render.WriteToStream(qrCode.Matrix, ImageFormat.Png, stream);
            }

            //Point padding = new Point(10, 10);
            //DrawingSize dSize = render.SizeCalculator.GetSize(qrCode.Matrix.Width);
            //Bitmap map = new Bitmap(dSize.CodeWidth + padding.X, dSize.CodeWidth + padding.Y);
            //Graphics g = Graphics.FromImage(map);
            //render.Draw(g, qrCode.Matrix, padding);
            //map.Save(filename, ImageFormat.Png);
        }
Ejemplo n.º 9
0
        private clsResponse QRCode(string content)
        {
            clsResponse objResponse = new clsResponse();

            try
            {
                QrEncoder enc  = new QrEncoder(ErrorCorrectionLevel.H);
                var       code = enc.Encode(content);

                //---------------------------------------------------------------
                GraphicsRenderer r = new GraphicsRenderer(new FixedCodeSize(5, QuietZoneModules.Zero), Brushes.Black, Brushes.White);

                using (MemoryStream ms = new MemoryStream())
                {
                    r.WriteToStream(code.Matrix, ImageFormat.Png, ms);

                    byte[] image = ms.ToArray();

                    objResponse.Base64String = string.Format(@"<img src=""data:image/png;base64,{0}"" alt=""{1}"" />", Convert.ToBase64String(image), content);
                }
                //---------------------------------------------------------------

                objResponse.StatusCode = 200;
            }
            catch (Exception ex)
            {
                objResponse.StatusCode = 404;
                objResponse.StatusText = ex.Message.ToString() + ", Inner : " + ex.InnerException.Message.ToString();
            }
            return(objResponse);
        }
        public void Generate(byte[] privateKey)
        {
            var account  = new Neo.Wallets.KeyPair(privateKey);
            var contract = Neo.SmartContract.Contract.CreateSignatureContract(account.PublicKey);
            var address  = contract.Address;
            var wif      = account.Export();

            File.AppendAllText("export.txt", $"{address}\t{wif}\r\n", Encoding.Default);

            QrEncoder qrEncoder = new QrEncoder(ErrorCorrectionLevel.M);
            QrCode    qrCode    = qrEncoder.Encode(wif);

            int w = (int)Math.Sqrt(qrCode.Matrix.InternalArray.Length);

            bool[,] qr = Zoom(qrCode.Matrix.InternalArray, 10, w);
            w          = (int)Math.Sqrt(qr.Length);

            byte[] data = new byte[qr.Length];

            for (int j = 0; j < w; j++)
            {
                for (int i = 0; i < w; i++)
                {
                    data[j * w + i] = (byte)(qr[i, j] ? 0 : 255);
                }
            }
            var dpi = 144;

            BitmapSource  qrBitSource   = BitmapSource.Create(w, w, dpi, dpi, PixelFormats.Gray8, null, data, w);
            DrawingVisual drawingVisual = new DrawingVisual();

            using (DrawingContext drawingContext = drawingVisual.RenderOpen())
            {
                drawingContext.DrawRectangle(new SolidColorBrush(Colors.White), new Pen(new SolidColorBrush(Colors.White), 0), new Rect(new Point(0, 0), new Size(1000, 1000)));
                drawingContext.DrawText(
                    new FormattedText(
                        address,
                        System.Globalization.CultureInfo.CurrentCulture, FlowDirection.LeftToRight,
                        new Typeface(new FontFamily("微软雅黑"), FontStyles.Normal, FontWeights.Regular, FontStretches.Normal),
                        9, new SolidColorBrush(Colors.Black)
                        ),
                    new Point(30, 10));

                //图片-二维码
                drawingContext.DrawImage(qrBitSource, new Rect(new Point(30, 30), new Size(200, 200)));
            }
            try
            {
                RenderTargetBitmap bmp = new RenderTargetBitmap(390, 390, dpi, dpi, PixelFormats.Pbgra32);
                bmp.Render(drawingVisual);
                //canvas1.Children.Add(new Image());
                //(canvas1.Children[0] as Image).Source = bmp;
                var fileName = $"code/{address}.jpg";
                Save(bmp, fileName);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
Ejemplo n.º 11
0
        public static byte[] Encode(string str)
        {
            var qrEncoder = new QrEncoder(ErrorCorrectionLevel.H);
            var qrCode    = qrEncoder.Encode(str);

            var render = new GraphicsRenderer(new FixedModuleSize(3, QuietZoneModules.Zero));
            var ms     = new MemoryStream();
            //render.WriteToStream(qrCode.Matrix, ImageFormat.Png, ms);


            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);

            int logosize = 20;

            using (Image img = Image.FromFile(AppDomain.CurrentDomain.BaseDirectory + @"Images\innerWhite-logo.png"))
            {
                Point imgPoint = new Point((map.Width - logosize) / 2, (map.Height - logosize) / 2);
                g.DrawImage(img, imgPoint.X, imgPoint.Y, logosize, logosize);
                map.Save(ms, ImageFormat.Png);
            }

            return(ms.GetBuffer());
        }
Ejemplo n.º 12
0
        //直接在控制台上用黑白方块打印出QrCode码
        static void printQrCode(string str)
        {
            QrEncoder qrEncoder = new QrEncoder();
            QrCode    qrCode    = qrEncoder.Encode(str);

            for (int i = 0; i < qrCode.Matrix.Width + 2; i++)
            {
                Console.Write("█");
            }
            Console.WriteLine();
            for (int j = 0; j < qrCode.Matrix.Width; j++)
            {
                Console.Write("█");
                for (int i = 0; i < qrCode.Matrix.Width; i++)
                {
                    char charToPrint = qrCode.Matrix[j, i] ? ' ' : '█';
                    Console.Write(charToPrint);
                }
                Console.Write("█");
                Console.WriteLine();
            }
            for (int i = 0; i < qrCode.Matrix.Width + 2; i++)
            {
                Console.Write("█");
            }
            Console.WriteLine();
        }
Ejemplo n.º 13
0
        //编码QRCode
        static QrCode EnCode(char level, String content)
        {
            if (content.Length > 100)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("待编码信息超过可编码的最大长度");
                Console.ResetColor();
                return(null);
            }
            QrEncoder qrEncoder;

            switch (level)
            {
            case 'L':
                qrEncoder = new QrEncoder(ErrorCorrectionLevel.L);
                break;

            case 'M':
                qrEncoder = new QrEncoder(ErrorCorrectionLevel.M);
                break;

            case 'Q':
                qrEncoder = new QrEncoder(ErrorCorrectionLevel.Q);
                break;

            case 'H':
                qrEncoder = new QrEncoder(ErrorCorrectionLevel.H);
                break;

            default:
                goto case 'M';
            }
            return(qrEncoder.Encode(content));
        }
Ejemplo n.º 14
0
        /// <summary>
        /// Genera codigo QR
        /// </summary>
        /// <param name="link"></param>
        /// <param name="ruc"></param>
        /// <param name="tipoCFE"></param>
        /// <param name="serie"></param>
        /// <param name="nroCFE"></param>
        /// <param name="monto"></param>
        /// <param name="fecha"></param>
        /// <param name="hash1"></param>
        /// <returns></returns>
        //public bool generadorQR(string link, string ruc, string tipoCFE,
        //    string serie, string nroCFE, string monto, string fecha, string hash1)
        public bool generadorQR(string link, CFE pComprobante, string monto)
        {
            bool   resultado = false;
            string rutaQ     = RutasCarpetas.RutaCarpetaComprobantes + Mensaje.nomImagenQr;

            try
            {
                DateTime fechaFormateada = DateTime.Parse(pComprobante.FechaComprobante);

                //hash1 = Uri.EscapeDataString(hash1);
                //string informacion = link + "?" + ruc + "," + tipoCFE + "," + serie +
                //    "," + nroCFE + "," + monto + "," + fecha + "," + hash1;
                pComprobante.CodigoSeguridad = Uri.EscapeDataString(pComprobante.CodigoSeguridad);
                string informacion = link + "?" + pComprobante.RucEmisor + "," + pComprobante.TipoCFEInt + "," + pComprobante.SerieComprobante +
                                     "," + pComprobante.NumeroComprobante + "," + monto + "," + fechaFormateada.ToString("dd/MM/yyyy") + "," + pComprobante.CodigoSeguridad;
                var qrEncoder = new QrEncoder(ErrorCorrectionLevel.H);
                var qrCode    = qrEncoder.Encode(informacion);

                var renderer = new GraphicsRenderer(new FixedModuleSize
                                                        (10, QuietZoneModules.Two), Brushes.Black, Brushes.White);
                using (var stream = new FileStream(rutaQ, FileMode.Create))
                    renderer.WriteToStream(qrCode.Matrix, ImageFormat.Png, stream);
                resultado = true;
            }
            catch (Exception)
            {
            }

            return(resultado);
        }
Ejemplo n.º 15
0
        //生成中文二维码-支持中文(自定义大小)
        //暂时未完善 只定义了背景大小
        static void Generate(string url, string filename, string savapath, ImgType type = ImgType.Png, int?width = null, int?high = null)
        {
            QrEncoder qrEncoder = new QrEncoder();
            var       qrCode    = qrEncoder.Encode(url);
            //保存成png文件
            //string filename = @"H:\桌面\截图\cn.png";
            string suffix = ImgSuffix.Getsuffix(type);; //后缀

            filename = $"{savapath}{filename}{suffix}";
            GraphicsRenderer render = new GraphicsRenderer(new FixedModuleSize(5, QuietZoneModules.Two), Brushes.Black, Brushes.White);
            int w = 500;
            int h = 500;

            if (width != null)
            {
                w = (int)width;
            }
            if (high != null)
            {
                h = (int)high;
            }
            Bitmap   map = new Bitmap(w, h);
            Graphics g   = Graphics.FromImage(map);

            g.FillRectangle(Brushes.White, 0, 0, w, h);
            render.Draw(g, qrCode.Matrix, new Point(20, 20));
            map.Save(filename, ImageFormat.Png);
        }
Ejemplo n.º 16
0
        /// <summary>
        /// create qrcode photoes in .png format and output in console
        /// </summary>
        /// <param name="rows"><number of pictures to be created/param>
        /// <param name="stringData"><string array to store data/param>
        public static void PhotoOutput(int rows, string[] stringData)
        {
            FileStream[] resultFile = new FileStream[rows]; // declear qrcode phote files array
            string[]     photoname  = new string[rows];

            QrEncoder qrEncoder = new QrEncoder(ErrorCorrectionLevel.M);

            for (int r = 0; r < rows; r++)
            {
                // if the input data are valid (numbers), create photoes
                if (CorrectInput(stringData[r]))
                {
                    photoname[r]  = string.Format("{0:D3}", r) + stringData[r].Substring(0, 4) + ".png";
                    resultFile[r] = new FileStream(photoname[r], FileMode.Create);
                    QrCode qrCode = qrEncoder.Encode(stringData[r]);
                    ConsoleOutput(qrCode);
                    GraphicsRenderer renderer = new GraphicsRenderer(new FixedModuleSize(30, QuietZoneModules.Four), Brushes.Black, Brushes.White);
                    renderer.WriteToStream(qrCode.Matrix, ImageFormat.Png, resultFile[r]);
                }

                // if the input data are invalid, throw an exception and return
                else
                {
                    Console.WriteLine("Invalid input of txt(sql) data.\n'-help' for some help on readme.md");
                    return;
                }
            }
        }
Ejemplo n.º 17
0
        /// <summary>
        /// 生成二维码
        /// </summary>
        /// <param name="code">字符串</param>
        /// <param name="eSize">二维码尺寸</param>
        /// <param name="img">小图</param>
        /// <param name="iSize">小图尺寸</param>
        /// <param name="bColor">二维码背景颜色</param>
        /// <param name="fColor">二维码颜色</param>
        /// <returns></returns>
        public static Image GetQrcode(string code, int eSize, Image img, int iSize, Brush bColor, Brush fColor)
        {
            var qrcoder = new QrEncoder(ErrorCorrectionLevel.H);
            var qrCode  = qrcoder.Encode(code);

            var render = new GraphicsRenderer(new FixedModuleSize(5, QuietZoneModules.Four), fColor, bColor);

            using (Stream stream = new MemoryStream())
            {
                eSize = eSize > 0 ? eSize : 200;

                render.WriteToStream(qrCode.Matrix, ImageFormat.Png, stream, new Point(10, 10));

                var be = new Bitmap(stream);
                be = ResizeImage(be, eSize, eSize);
                Graphics ge = Graphics.FromImage(be);

                if (img != null)
                {
                    iSize = iSize > 0 ? iSize : 50;
                    img   = ResizeImage(img, iSize, iSize);

                    //小图白色边框
                    var      bi = new Bitmap(iSize + 10, iSize + 10);
                    Graphics gi = Graphics.FromImage(bi);
                    gi.Clear(Color.White);
                    gi.DrawImage(img, 5, 5, iSize, iSize);

                    //将小图插入到二维码图片中
                    ge.DrawImage(bi, (eSize - iSize) / 2, (eSize - iSize) / 2, iSize, iSize);
                }
                return(be);
            }
        }
Ejemplo n.º 18
0
 private void EncodeNewBitMatrix(string content)
 {
     if (!String.IsNullOrEmpty(content))
     {
         qrCode    = qrEncoder.Encode(content);
         bitMatrix = qrCode.Matrix;
     }
 }
Ejemplo n.º 19
0
        /// <summary>
        /// 开始绘制(仅覆盖)
        /// </summary>
        /// <param name="text">内容文字</param>
        /// <param name="pictureSize">图片大小</param>
        public void Draw(string text, int pictureSize)
        {
            QrCode           qrCode     = qrEncoder.Encode(text);
            FixedModuleSize  moduleSize = new FixedModuleSize(pictureSize, QuietZoneModules.Zero);
            GraphicsRenderer render     = new GraphicsRenderer(moduleSize, darkBrush, lightBrush);

            render.Draw(graphics, qrCode.Matrix);
        }
Ejemplo n.º 20
0
        public void generar(Compra compra)
        {
            QrEncoder qrEncoder = new QrEncoder(ErrorCorrectionLevel.H);
            QrCode    qrCode    = qrEncoder.Encode(compra.Id.ToString());
            Renderer  renderer  = new Renderer(5, Brushes.Black, Brushes.White);

            renderer.CreateImageFile(qrCode.Matrix, "c:/Qr" + compra.Id.ToString() + ".png", ImageFormat.Png);
        }
Ejemplo n.º 21
0
        public void Encode_InvalidEncoding_ShouldThrowException()
        {
            // Act
            Action action = () => QrEncoder.Encode("test", ErrorCorrectionLevel.H, (Encoding)255);

            // Assert
            action.Should().Throw <InvalidOperationException>()
            .WithMessage("Unknown encoding type 255");
        }
Ejemplo n.º 22
0
        private void ShowCode(Graphics g)
        {
            QrEncoder qrEncoder = new QrEncoder(ErrorCorrectionLevel.L);
            QrCode    qrCode    = qrEncoder.Encode(str);

            FixedModuleSize  moduleSize = new FixedModuleSize(2, QuietZoneModules.Two);
            GraphicsRenderer render     = new GraphicsRenderer(moduleSize, Brushes.Black, Brushes.White);

            render.Draw(g, qrCode.Matrix);
        }
Ejemplo n.º 23
0
        public WriteableBitmap generateQRCode(Ticket t)
        {
            QrEncoder encoder = new QrEncoder(ErrorCorrectionLevel.H);
            var       res     = encoder.Encode(t.TicketID + "");

            WriteableBitmapRenderer wRenderer = new WriteableBitmapRenderer(new FixedModuleSize(2, QuietZoneModules.Two), Colors.Black, Colors.White);
            WriteableBitmap         wBitmap   = new WriteableBitmap(51, 51, 5, 5, PixelFormats.Gray8, null);

            wRenderer.Draw(wBitmap, res.Matrix);
            return(wBitmap);
        }
        private string GetQrCode(string cadena)
        {
            QrEncoder        qrEncoder = new QrEncoder(ErrorCorrectionLevel.M);
            QrCode           qrCode    = qrEncoder.Encode(cadena);
            MemoryStream     salida    = new MemoryStream();
            GraphicsRenderer renderer  = new GraphicsRenderer(new FixedModuleSize(2, QuietZoneModules.Two), Brushes.Black, Brushes.White);

            renderer.WriteToStream(qrCode.Matrix, ImageFormat.Png, salida);
            salida.Close();
            return(Convert.ToBase64String(salida.ToArray()));
        }
Ejemplo n.º 25
0
        private static MemoryStream QrStream(string url)
        {
            QrEncoder qrEncoder = new QrEncoder(ErrorCorrectionLevel.M);
            QrCode    qrCode    = qrEncoder.Encode(url);
            var       renderer  = new GraphicsRenderer(new FixedModuleSize(9, QuietZoneModules.Two));
            var       ms        = new MemoryStream();

            renderer.WriteToStream(qrCode.Matrix, ImageFormat.Jpeg, ms);
            ms.Position = 0;
            return(ms);
        }
Ejemplo n.º 26
0
        static void Main(string[] args)
        {
            ParseArgs(args);
            var qrEncoder = new QrEncoder(ErrorCorrectionLevel.H);

            if (Directory.Exists(DestinationFolder))
            {
                Directory.Delete(DestinationFolder, recursive: true);
            }
            Directory.CreateDirectory(DestinationFolder);
            using (conn)
            {
                SqlCommand _query = new SqlCommand(SQLQuery, conn);
                conn.Open();
                SqlDataReader _reader = _query.ExecuteReader();
                if (_reader.HasRows)
                {
                    while (_reader.Read())
                    {
                        string _fileName = "";
                        string RS        = ((char)030).ToString();
                        string GS        = ((char)029).ToString();
                        string EOT       = ((char)004).ToString();

                        string _text = "[)>" + RS;
                        for (var i = 0; i < _reader.FieldCount; i++)
                        {
                            _text += _reader.GetString(i);
                            if (i == _reader.FieldCount - 1)
                            {
                                _text += RS + EOT;
                            }
                            else
                            {
                                _text += GS;
                            }
                            if (_reader.GetName(i) == FileNameField)
                            {
                                _fileName = _reader.GetString(i);
                            }
                        }
                        if (_fileName == "")
                        {
                            var ex = new Exception("FileName field not found");
                            throw (ex);
                        }
                        var _qrCode  = qrEncoder.Encode(_text);
                        var renderer = new GraphicsRenderer(new FixedModuleSize(5, QuietZoneModules.Two), Brushes.Black, Brushes.White);
                        using (var stream = new FileStream(string.Format("{0}{1}.bmp", DestinationFolder, _fileName), FileMode.Create))
                            renderer.WriteToStream(_qrCode.Matrix, ImageFormat.Bmp, stream);
                    }
                }
            }
        }
Ejemplo n.º 27
0
        private void ShowCode(Graphics g)
        {
            QrEncoder qrEncoder = new QrEncoder(ErrorCorrectionLevel.L);
            QrCode    qrCode    = qrEncoder.Encode(str);

            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);
        }
Ejemplo n.º 28
0
        public void CalculatePenaltyRule3(string content, uint expectedPenalty)
        {
            // Arrange
            var qr = QrEncoder.Encode(content, ErrorCorrectionLevel.L, Encoding.AlphaNumeric) as QrCode;

            // Act
            var penalty = qr.CalculatePenaltyRule3();

            // Assert
            penalty.Should().Be(expectedPenalty);
        }
Ejemplo n.º 29
0
        void how_to_print_page_handle(object sender, PrintPageEventArgs e)
        {
            int h = (int)(e.PageSettings.PrintableArea.Height);
            int w = (int)(e.PageSettings.PrintableArea.Width);

            QrEncoder qrEncoder = new QrEncoder(ErrorCorrectionLevel.M);

            float side = e.PageSettings.PrintableArea.Width;

            side = 100; //=> 1"
            if (e.PageSettings.PrintableArea.Height < e.PageSettings.PrintableArea.Width)
            {
                side = e.PageSettings.PrintableArea.Height;
            }
            float modesize = side / 100 * e.Graphics.DpiX;

            QrCode qrCode = qrEncoder.Encode("0123456789");


            //ISizeCalculation iSizeCal = new FixedModuleSize(2, QuietZoneModules.Zero);
            // This works with the Brady on a very small label
            ISizeCalculation iSizeCal = new FixedCodeSize((int)modesize - 16, QuietZoneModules.Zero);

            DrawingBrushRenderer dRenderer = new DrawingBrushRenderer(iSizeCal,
                                                                      System.Windows.Media.Brushes.Black, System.Windows.Media.Brushes.White);

            string test = "test1";

            if (test == "test1")
            {
                MemoryStream mem_stream = new MemoryStream();
                dRenderer.WriteToStream(qrCode.Matrix, ImageFormatEnum.BMP, mem_stream);

                Bitmap bitmap = new Bitmap(mem_stream);
                bitmap.SetResolution(e.Graphics.DpiX, e.Graphics.DpiY);
                //Graphics graphics = Graphics.FromImage(bitmap);
                e.Graphics.DrawImage(bitmap, 0, 0);
            }
            else
            {
                System.Windows.Point dpipoint     = new System.Windows.Point(e.Graphics.DpiX, e.Graphics.DpiY);
                BitmapSource         bitmapsource = dRenderer.WriteToBitmapSource(qrCode.Matrix, dpipoint);
                BitmapFrame          bitmapframe  = BitmapFrame.Create(bitmapsource);

                BitmapEncoder bitmapencoder = new BmpBitmapEncoder();
                bitmapencoder.Frames.Add(bitmapframe);

                MemoryStream mem_stream = new MemoryStream();
                bitmapencoder.Save(mem_stream);

                System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(mem_stream);
                e.Graphics.DrawImage(bitmap, 0, 0);
            }
        }
Ejemplo n.º 30
0
        public Image DrawQRCode(int qrImageSize, ImageFormat imgFormat)
        {
            QrEncoder qrEncoder = new QrEncoder(ErrorCorrectionLevel.M);
            QrCode    qrCode    = qrEncoder.Encode(this.BarCodeValue);

            GraphicsRenderer renderer = new GraphicsRenderer(new FixedCodeSize(qrImageSize, QuietZoneModules.Two), Brushes.Black, Brushes.White);
            MemoryStream     stream   = new MemoryStream();

            renderer.WriteToStream(qrCode.Matrix, imgFormat, stream);
            return(Image.FromStream(stream));
        }
Ejemplo n.º 31
0
		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]);
			
		}
Ejemplo n.º 32
0
 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);
 }