Beispiel #1
0
 private void Scanner_OnScanResult(Result result)
 {
     if (!string.IsNullOrWhiteSpace(result.Text))
     {
         Scanner.IsAnalyzing = false; // Stop analysis until we navigate away so we don't keep reading qr codes
         string code = result.Text?.Trim();
         GetViewModel <ScanQrCodeViewModel>().Code = code;
         QrCode.TrySetResultAndClosePage(this.navigationService, this.uiDispatcher, code);
     }
 }
        private void OptimalSegmentCode()
        {
            var segments = QrSegmentAdvanced.MakeSegmentsOptimally(Text1, QrCode.Ecc.High);
            var qrCode   = QrCode.EncodeSegments(segments, QrCode.Ecc.High);

            Assert.Same(QrCode.Ecc.High, qrCode.ErrorCorrectionLevel);
            Assert.Equal(29, qrCode.Size);
            Assert.Equal(0, qrCode.Mask);
            Assert.Equal(Modules1, TestHelper.ToStringArray(qrCode));
        }
        public ActionResult Sharemoney()
        {
            User   userInfo        = SessionTool.Get <User>("user");
            string spreadUrl       = "http://www.jiaodai.online/Me/SpreadRegister?fromUserNo=" + userInfo.No;
            string spreadQrCodeUrl = QrCode.CreateSpreadQrCode(spreadUrl, userInfo.NickName);

            ViewBag.SpreadQrCodeUrl = spreadQrCodeUrl;
            ViewBag.SpreadUrl       = spreadUrl;
            return(View());
        }
Beispiel #4
0
        private void CopyButton_Click(object sender, RoutedEventArgs e)
        {
            // put the QR code on the clipboard as a bitmap
            var qrCode     = QrCode.EncodeText(_text, ErrorCorrection);
            var bitmap     = QrCodeDrawing.CreateBitmapImage(qrCode, 20, BorderWidth);
            var dataObject = new DataObject();

            dataObject.SetData(DataFormats.Bitmap, bitmap);
            Clipboard.SetDataObject(dataObject);
        }
Beispiel #5
0
        public void CalculatePenaltyRule1()
        {
            var qr = new QrCode(7);

            qr.CalculatePenaltyRule1().Should().Be(70);
            qr.Set(0, 0, true);
            qr.CalculatePenaltyRule1().Should().Be(68);
            qr.Set(0, 6, true);
            qr.CalculatePenaltyRule1().Should().Be(66);
        }
Beispiel #6
0
        static void Main(string[] args)
        {
            QrCode code   = new QrCode();
            String ascii  = code.generateAscii("test");
            String base64 = code.generateBase64("test");

            Console.WriteLine(ascii);
            Console.WriteLine(base64);
            Console.ReadLine();
        }
        public async Task <QrCodeDto> CreateQrCodeAsync(QrCodeDto qrCode, long participantID)
        {
            QrCode qrCodeParticipant = _mapper.Map <QrCode>(qrCode);

            qrCodeParticipant.ParticipantID = participantID;
            _context.QrCode.Add(qrCodeParticipant);
            await _context.SaveChangesAsync();

            return(qrCode);
        }
        public static void PrintCredential(object sender, PrintPageEventArgs e, JObject obj, JArray a, float w)
        {
            float      x = 0F, y = 10, height = 0F;
            Font       bold       = new Font("Arial", 8, FontStyle.Bold);
            Font       bold_10    = new Font("Arial", 10, FontStyle.Bold);
            Font       bold_12    = new Font("Arial", 10, FontStyle.Bold);
            Font       bold_14    = new Font("Arial", 14, FontStyle.Bold);
            Font       bold_16    = new Font("Arial", 16, FontStyle.Bold);
            SolidBrush drawBrush  = new SolidBrush(Color.Black);
            Font       regular    = new Font("Arial", 8, FontStyle.Regular);
            Font       regular_10 = new Font("Arial", 10, FontStyle.Regular);
            Font       regular_12 = new Font("Arial", 11, FontStyle.Regular);
            Font       regular_14 = new Font("Arial", 14, FontStyle.Regular);
            Font       regular_16 = new Font("Arial", 16, FontStyle.Regular);

            StringFormat center = new StringFormat();

            center.Alignment = StringAlignment.Center;
            StringFormat left = new StringFormat();

            left.Alignment = StringAlignment.Near;
            StringFormat right = new StringFormat();

            right.Alignment = StringAlignment.Far;
            string name     = (string)(obj["name"]);
            string lastname = (string)(obj["lastname"]);
            string ci       = (string)(obj["ci"]);
            string qrcode   = (string)(obj["qr"]);
            string zone     = (string)(obj["zone"]);
            string id       = (string)(obj["id"]);
            string company  = (string)(obj["company"]);

            if (String.IsNullOrEmpty(qrcode))
            {
                qrcode = "ventickets.com";
            }
            QrEncoder qrEncoder = new QrEncoder(ErrorCorrectionLevel.H);
            QrCode    qrCode    = new QrCode();

            qrEncoder.TryEncode(qrcode, out qrCode);
            GraphicsRenderer renderer = new GraphicsRenderer(new FixedCodeSize(100, QuietZoneModules.Zero), Brushes.Black, Brushes.White);
            MemoryStream     ms       = new MemoryStream();

            renderer.WriteToStream(qrCode.Matrix, ImageFormat.Png, ms);
            var img_temp = new Bitmap(ms);
            var qr       = new Bitmap(img_temp, new Size(new Point(60, 60)));

            e.Graphics.DrawImage(qr, new Rectangle((int)w - 60, (int)Math.Ceiling(0.0F), 60, 60));
            imprimir(ref e, name, regular_12, drawBrush, x, ref y, w, height, left);
            imprimir(ref e, name, regular_12, drawBrush, x, ref y, w, height, left);
            imprimir(ref e, "CI: " + ci, bold_12, drawBrush, x, ref y, w, height, left);
            y += 10;
            imprimir(ref e, zone + " - STAND 00" + id, bold, drawBrush, x, ref y, w, height, center);
            imprimir(ref e, company, regular_12, drawBrush, x, ref y, w, height, center);
        }
Beispiel #9
0
        public static void GenerateQrCode(string text, string file)
        {
            var qrSegment = QrSegment.MakeBytes(Encoding.UTF8.GetBytes(text));
            var qrCode    = QrCode.EncodeSegments(new List <QrSegment>()
            {
                qrSegment
            }, QrCode.Ecc.Low, 10, 40, 0, false);
            var qrCodePng = new QrCodePng(qrCode, 5, 5);

            File.WriteAllBytes(file, qrCodePng.GetBytes());
        }
Beispiel #10
0
        public int Create(string code, Guid tableID)
        {
            var qrCode = new QrCode();

            qrCode.ID      = Guid.NewGuid();
            qrCode.Code    = code;
            qrCode.TableID = tableID;
            QrCodeRepository.Add(qrCode);
            RepositoryContext.Commit();
            return(1);
        }
Beispiel #11
0
        private bool canSendQrCodeCmd()
        {
            bool successFlag = false;

            if (QrCode.Contains("<EOF>"))
            {
                successFlag = true;
            }

            return(successFlag);
        }
Beispiel #12
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);
        }
Beispiel #13
0
        public ActionResult <byte[]> GenerateSvg([FromQuery(Name = "text")] string text,
                                                 [FromQuery(Name = "ecc")] int?ecc, [FromQuery(Name = "border")] int?borderWidth)
        {
            ecc         = Math.Clamp(ecc ?? 1, 0, 3);
            borderWidth = Math.Clamp(borderWidth ?? 3, 0, 999999);

            var qrCode = QrCode.EncodeText(text, errorCorrectionLevels[(int)ecc]);

            byte[] svg = Encoding.UTF8.GetBytes(qrCode.ToSvgString((int)borderWidth));
            return(new FileContentResult(svg, "image/svg+xml; charset=utf-8"));
        }
Beispiel #14
0
        // leer matriz de nombres y generar su Qr
        void generarQrFromTxt()
        {
            // crear una conexion
            this.conexion = new MySqlConnection(this.cadenaConexion);
            this.conexion.Open();

            for (int i = 0; i < this.lineas; i++)
            {
                for (int j = 0; j < 1; j++)
                {
                    // crear un encoder, codificador
                    QrEncoder Codificador = new QrEncoder(ErrorCorrectionLevel.H);

                    // crear un codigo QR
                    QrCode Codigo = new QrCode();

                    string nua    = ListadoNombres[i, j];
                    string nombre = ListadoNombres[i, j + 1];

                    string com = " INSERT INTO registro ( nombre, nua ) VALUES ('" + nombre + "'," + nua + " )";

                    MySqlCommand comando = new MySqlCommand(com, this.conexion);
                    comando.ExecuteNonQuery();



                    // generar generar  un codigo apartir de datos, y pasar el codigo por referencia
                    Codificador.TryEncode(nombre + " " + nua, 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(114, 114));

                    if (!Directory.Exists(this.rutaGuardado))
                    {
                        // crear un directorio
                        Directory.CreateDirectory(this.rutaGuardado);
                    }

                    ImgenSalida.Save(this.rutaGuardado + "/" + nombre + nua + ".png", System.Drawing.Imaging.ImageFormat.Png);
                }
            }
            this.conexion.Close();
            MessageBox.Show("Lectura termiada", " ", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
Beispiel #15
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));
        }
Beispiel #16
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);
        }
Beispiel #17
0
        public ActionResult <byte[]> GeneratePng([FromQuery(Name = "text")] string text,
                                                 [FromQuery(Name = "ecc")] int?ecc, [FromQuery(Name = "border")] int?borderWidth)
        {
            ecc         = Math.Clamp(ecc ?? 1, 0, 3);
            borderWidth = Math.Clamp(borderWidth ?? 3, 0, 999999);

            var qrCode = QrCode.EncodeText(text, errorCorrectionLevels[(int)ecc]);

            byte[] png = qrCode.ToPng(20, (int)borderWidth);
            return(new FileContentResult(png, "image/png"));
        }
Beispiel #18
0
        private void generar_imagen_qr(string texto, string ruta_temp)
        {
            QrEncoder qrEncoder = new QrEncoder(ErrorCorrectionLevel.Q);
            QrCode    qrCode    = new QrCode();

            qrEncoder.TryEncode(texto, out qrCode);

            Renderer renderer = new Renderer(5, Brushes.Black, Brushes.White);

            renderer.CreateImageFile(qrCode.Matrix, ruta_temp, ImageFormat.Bmp);
        }
Beispiel #19
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);
            }
        }
Beispiel #20
0
        // Create a QR code and save it as a PNG.
        internal static void Main()
        {
            var text     = "Hello, world!";
            var filename = "hello-world-QR.png";

            var qr = QrCode.EncodeText(text, QrCode.Ecc.Medium); // Create the QR code symbol

            qr.SaveAsPng(filename, scale: 10, border: 4);

            Console.WriteLine($"The QR code has been saved as {Path.GetFullPath(filename)}");
        }
        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()));
        }
Beispiel #22
0
        /// <summary>
        /// Generates the QR code
        /// </summary>
        /// <param name="data"></param>
        /// <param name="filename"></param>
        private static void GenerateQR(string data, string filename)
        {
            QrEncoder qrEncoder = new QrEncoder(ErrorCorrectionLevel.H);
            QrCode    qrCode    = qrEncoder.Encode(data);

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

            using (FileStream stream = new FileStream(filename, FileMode.Create))
            {
                renderer.WriteToStream(qrCode.Matrix, ImageFormat.Png, stream);
            }
        }
Beispiel #23
0
        public void CalculatePenaltyRule2()
        {
            var qr = new QrCode(3);

            qr.CalculatePenaltyRule2().Should().Be(12);
            qr.Set(0, 0, true);
            qr.Set(1, 1, true);
            qr.Set(2, 0, true);
            qr.CalculatePenaltyRule2().Should().Be(0);
            qr.Set(1, 1, false);
            qr.CalculatePenaltyRule2().Should().Be(6);
        }
Beispiel #24
0
        public Bitmap EncodeToImage(string str, QRCodeSaveSize saveSize)
        {
            QrCode           qrCode = _qrEncoder.Encode(str);
            GraphicsRenderer render = new GraphicsRenderer(new FixedModuleSize(Convert.ToInt32(saveSize), QuietZoneModules.Two), Brushes.Black, Brushes.White);

            MemoryStream ms = new MemoryStream();

            render.WriteToStream(qrCode.Matrix, ImageFormat.Png, ms);
            Bitmap bitmap = new Bitmap(ms);

            return(bitmap);
        }
Beispiel #25
0
        private static void Barcode_LaidOut(object sender, PlaceHolderLaidOutEventArgs e)
        {
            // Retrieve the image bytes from the layout data for the current record
            string url = e.LayoutWriter.Data["Url"].ToString();

            // Create a barcode page element from the data and set its properties
            QrCode qrCode = new QrCode(url, 0, 0, 2);

            // Add the barcode and a link to the placeholder's content area
            e.ContentArea.Add(qrCode);
            e.ContentArea.Add(new Link(0, 0, qrCode.GetSymbolWidth(), qrCode.GetSymbolHeight(), new UrlAction(url)));
        }
Beispiel #26
0
 private QrCode BitmapToBytes(Bitmap img)
 {
     using (MemoryStream stream = new MemoryStream())
     {
         img.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);
         QrCode qrCode = new QrCode
         {
             QrString = stream.ToArray()
         };
         return(qrCode);
     }
 }
Beispiel #27
0
        public ActionResult QrCodex(string con)
        {
            return(RunAction(() =>
            {
                var qr = new QrCode();
                var b = qr.GetQrCodeBytes(con ?? string.Empty);

                this.X.context.Response.SetResponseNoCache();

                return File(b, "image/Png");
            }));
        }
Beispiel #28
0
        public Image getqrcode(string content)
        {
            var              encoder = new QrEncoder(ErrorCorrectionLevel.M);
            QrCode           qrCode  = encoder.Encode(content);
            GraphicsRenderer render  = new GraphicsRenderer(new FixedModuleSize(12, QuietZoneModules.Two), Brushes.Black, Brushes.White);//如需改变二维码大小,调整12即可
            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);
            return(map);
        }
Beispiel #29
0
        public static void RunSample3()
        {
            QrEncoder qrEncoder = new QrEncoder(ErrorCorrectionLevel.H);
            QrCode    qrCode    = qrEncoder.Encode("Hello World!");

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

            using (FileStream stream = new FileStream(@"c:\temp\HelloWorld.png", FileMode.Create))
            {
                renderer.WriteToStream(qrCode.Matrix, ImageFormat.Png, stream);
            }
        }
Beispiel #30
0
        public static void Print(List <String> photos, int angle)
        {
            String templatePath = null;

            //if (angle == 0)
            //{
            if (photos.Count == 1)
            {
                // Photo en mode paysage par défaut
                templatePath = Properties.Settings.Default.LandscapeTemplatePath;
            }
            else if (photos.Count == 4)
            {
                templatePath = Properties.Settings.Default.Landscape4Template;
            }

            //}
            //else if (photos.Count == 1)
            //{
            //    templatePath = Properties.Settings.Default.PortraitTemplatePath;
            //}

            var doc = new Document();

            if (doc.Open(templatePath) != false)
            {
                string    qrCodeString = GetQrCodeString(photos);
                QrEncoder qrEncoder    = new QrEncoder(ErrorCorrectionLevel.M);
                QrCode    qrCode       = qrEncoder.Encode(qrCodeString);

                GraphicsRenderer renderer   = new GraphicsRenderer(new FixedModuleSize(5, QuietZoneModules.Two), Brushes.Black, Brushes.White);
                String           qrCodePath = Directory.GetCurrentDirectory() + @"\qrCode.jpg";
                using (FileStream stream = new FileStream(qrCodePath, FileMode.Create))
                {
                    renderer.WriteToStream(qrCode.Matrix, ImageFormat.Jpeg, stream);
                }
                doc.GetObject("QrCode").SetData(0, qrCodePath, 4);

                for (var i = 0; i < photos.Count; i++)
                {
                    doc.GetObject("Photo" + i).SetData(0, photos[i], 4);
                }

                doc.SetPrinter("Brother QL-500", false);
                doc.Printer.GetInstalledPrinters();
                doc.SetMediaById(doc.Printer.GetMediaId(), true);
                doc.StartPrint("", PrintOptionConstants.bpoHighResolution);
                doc.PrintOut(1, PrintOptionConstants.bpoHighResolution);
                doc.EndPrint();
                doc.Close();
            }
        }
        /// <summary>
        ///     创建二维码,获取二维码的ticket(用ticket可获取二维码的图)
        /// </summary>
        /// <param name="qrCode"></param>
        /// <returns></returns>
        public QrCodeResult Create(QrCode qrCode)
        {
            var s = new HttpHelper(CreateUrl).PostString(JsonConvert.SerializeObject(qrCode), new FormData
            {
                {"access_token", AccessToken}
            });

            var ret = JsonConvert.DeserializeObject<QrCodeResult>(s);

            if (string.IsNullOrEmpty(ret.ticket))
                throw new WxException(JsonConvert.DeserializeObject<BasicResult>(s));

            return ret;
        }
Beispiel #32
0
    /// <summary>
    /// Creates a collection of qrCodes and writes them into a pdf file.
    /// Saves the pdf file given path.
    /// </summary>
    /// <param name="path"></param>
    public void SaveQrPdf(string path)
    {
        Document document = new Document(PageSize.A4, 0, 0, 25, 0);

        Bitmap bitMap = new Bitmap(path + "/Empty Qr Image/emptyQr.png");
        MemoryStream ms = new MemoryStream();
        bitMap.Save(ms, System.Drawing.Imaging.ImageFormat.Png);

        List<QrCode> tmp = this.GetQrCodeList();

        for (int i = 3; i >= tmp.Count % 3; i--)
        {
            QrCode qr = new QrCode();
            qr.QrImage = System.Drawing.Image.FromStream(ms);
            qr.TableName = "";
            qr.CompanyName = "";
            qr.QrString = "";

            tmp.Add(qr);
        }

        try
        {
            PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(path + "/" + this.GetQrPdfName(), FileMode.Create));
            document.Open();

            //Create a master table with 3 columns
            PdfPTable masterTable = new PdfPTable(3);

            masterTable.PaddingTop = 3f;
            masterTable.HorizontalAlignment = Element.ALIGN_CENTER;

            PdfPTable table;
            PdfPCell cell;

            foreach (QrCode q in tmp)
            {
                table = new PdfPTable(1);
                table.DefaultCell.Border = iTextSharp.text.Rectangle.NO_BORDER;
                table.HorizontalAlignment = Element.ALIGN_CENTER;

                Phrase tableName = new Phrase(q.TableName);
                tableName.Font.Size = 16f;

                cell = new PdfPCell(tableName);
                cell.HorizontalAlignment = Element.ALIGN_CENTER;
                cell.BorderColor = BaseColor.WHITE;
                table.AddCell(cell);

                Phrase companyName = new Phrase(q.CompanyName);
                companyName.Font.Size = 10f;

                cell = new PdfPCell(companyName);
                cell.HorizontalAlignment = Element.ALIGN_CENTER;
                cell.BorderColor = BaseColor.WHITE;
                table.AddCell(cell);

                iTextSharp.text.Image pdfImage = iTextSharp.text.Image.GetInstance(q.QrImage, System.Drawing.Imaging.ImageFormat.Png);
                cell = new PdfPCell(pdfImage);
                cell.BorderColor = BaseColor.WHITE;
                table.AddCell(cell);

                //Add the sub-table to our master table instead of the writer
                masterTable.AddCell(table);
            }

            //Add the master table to our document
            document.Add(masterTable);
        }

        catch (Exception)
        {
            //handle errors
        }
        finally
        {
            document.Close();
        }
    }
 public static void PlaceTimingPatterns(ref QrCode qrCode, ref List<Rectangle> blockedModules)
 {
     var size = qrCode.ModuleMatrix.Count;
     for (var i = 8; i < size - 8; i++)
     {
         if (i%2 != 0) continue;
         qrCode.ModuleMatrix[6][i] = true;
         qrCode.ModuleMatrix[i][6] = true;
     }
     blockedModules.AddRange(new []{
         new Rectangle(6, 8, 1, size-16),
         new Rectangle(8, 6, size-16, 1)
     });
 }
 public static void PlaceFormat(ref QrCode qrCode, string formatStr)
 {
     var size = qrCode.ModuleMatrix.Count;
     var fStr = new string(formatStr.Reverse().ToArray());
     var modules = new [,] { { 8, 0, size - 1, 8 }, { 8, 1, size - 2, 8 }, { 8, 2, size - 3, 8 }, { 8, 3, size - 4, 8 }, { 8, 4, size - 5, 8 }, { 8, 5, size - 6, 8 }, { 8, 7, size - 7, 8 }, { 8, 8, size - 8, 8 }, { 7, 8, 8, size - 7 }, { 5, 8, 8, size - 6 }, { 4, 8, 8, size - 5 }, { 3, 8, 8, size - 4 }, { 2, 8, 8, size - 3 }, { 1, 8, 8, size - 2 }, { 0, 8, 8, size - 1 } };
     for (var i = 0; i < 15; i++)
     {
         var p1 = new Point(modules[i, 0], modules[i, 1]);
         var p2 = new Point(modules[i, 2], modules[i, 3]);
         qrCode.ModuleMatrix[p1.Y][p1.X] = fStr[i] == '1';
         qrCode.ModuleMatrix[p2.Y][p2.X] = fStr[i] == '1';
     }
 }
            public static void PlaceFinderPatterns(ref QrCode qrCode, ref List<Rectangle> blockedModules)
            {
                var size = qrCode.ModuleMatrix.Count;
                int[] locations = { 0, 0, size - 7, 0, 0, size - 7 };

                for (var i = 0; i < 6; i = i + 2)
                {
                    for (var x = 0; x < 7; x++)
                        for (var y = 0; y < 7; y++)
                            if (!(((x == 1 || x == 5) && y > 0 && y < 6) || (x > 0 && x < 6 && (y == 1 || y == 5))))
                                qrCode.ModuleMatrix[y + locations[i + 1]][x + locations[i]] = true;

                    blockedModules.Add(new Rectangle(locations[i], locations[i + 1], 7, 7));
                }
            }
 public static void PlaceDataWords(ref QrCode qrCode, string data, ref List<Rectangle> blockedModules)
 {
     var size = qrCode.ModuleMatrix.Count;
     var up = true;
     var datawords = new Queue<bool>();
     data.ToList().ForEach(x => datawords.Enqueue(x != '0'));
     for (var x = size - 1; x >= 0; x = x - 2)
     {
         if (x == 7 || x == 6)
             x = 5;
         for (var yMod = 1; yMod <= size; yMod++)
         {
             int y;
             if (up)
             {
                 y = size - yMod;
                 if (datawords.Count > 0 && !IsBlocked(new Rectangle(x, y, 1, 1), blockedModules))
                     qrCode.ModuleMatrix[y][x] = datawords.Dequeue();
                 if (datawords.Count > 0 && x > 0 && !IsBlocked(new Rectangle(x - 1, y, 1, 1), blockedModules))
                     qrCode.ModuleMatrix[y][x - 1] = datawords.Dequeue();
             }
             else
             {
                 y = yMod - 1;
                 if (datawords.Count > 0 && !IsBlocked(new Rectangle(x, y, 1, 1), blockedModules))
                     qrCode.ModuleMatrix[y][x] = datawords.Dequeue();
                 if (datawords.Count > 0 && x > 0 && !IsBlocked(new Rectangle(x - 1, y, 1, 1), blockedModules))
                     qrCode.ModuleMatrix[y][x - 1] = datawords.Dequeue();
             }
         }
         up = !up;
     }
 }
            public static void PlaceAlignmentPatterns(ref QrCode qrCode, IEnumerable<Point> alignmentPatternLocations, ref List<Rectangle> blockedModules)
            {
                foreach (var loc in alignmentPatternLocations)
                {
                    var alignmentPatternRect = new Rectangle(loc.X, loc.Y, 5, 5);
                    var blocked = blockedModules.Any(blockedRect => Intersects(alignmentPatternRect, blockedRect));
                    if (blocked)
                        continue;

                    for (var x = 0; x < 5; x++)
                        for (var y = 0; y < 5; y++)
                            if (y == 0 || y == 4 || x == 0 || x == 4 || (x == 2 && y == 2))
                                qrCode.ModuleMatrix[loc.Y + y][loc.X + x] = true;

                    blockedModules.Add(new Rectangle(loc.X, loc.Y, 5, 5));
                }
            }
            public static int MaskCode(ref QrCode qrCode, int version, ref List<Rectangle> blockedModules)
            {
                var patternName = string.Empty;
                var patternScore = 0;

                var size = qrCode.ModuleMatrix.Count;

                foreach (var pattern in typeof(MaskPattern).GetMethods())
                {
                    if (pattern.Name.Length != 8 || pattern.Name.Substring(0, 7) != "Pattern") continue;
                    var qrTemp = new QrCode(version);
                    for (var y = 0; y < size; y++)
                        for (var x = 0; x < size; x++)
                            qrTemp.ModuleMatrix[y][x] = qrCode.ModuleMatrix[y][x];

                    for (var x = 0; x < size; x++)
                        for (var y = 0; y < size; y++)
                            if (!IsBlocked(new Rectangle(x, y, 1, 1), blockedModules))
                                qrTemp.ModuleMatrix[y][x] ^= (bool)pattern.Invoke(null, new object[] { x, y });

                    var score = MaskPattern.Score(ref qrTemp);
                    if (!string.IsNullOrEmpty(patternName) && patternScore <= score) continue;
                    patternName = pattern.Name;
                    patternScore = score;
                }
                var patterMethod = typeof(MaskPattern).GetMethods().First(x => x.Name == patternName);
                for (var x = 0; x < size; x++)
                    for (var y = 0; y < size; y++)
                        if (!IsBlocked(new Rectangle(x, y, 1, 1), blockedModules))
                            qrCode.ModuleMatrix[y][x] ^= (bool)patterMethod.Invoke(null, new object[] { x, y });

                return Convert.ToInt32(patterMethod.Name.Substring(patterMethod.Name.Length - 1, 1)) - 1;
            }
 public static void AddQuietZone(ref QrCode qrCode)
 {
     var quietLine = new bool[qrCode.ModuleMatrix.Count + 8];
     for (var i = 0; i < quietLine.Length; i++)
         quietLine[i] = false;
     for (var i = 0; i < 4; i++)
         qrCode.ModuleMatrix.Insert(0, new BitArray(quietLine));
     for (var i = 0; i < 4; i++)
         qrCode.ModuleMatrix.Add(new BitArray(quietLine));
     for (var i = 4; i < qrCode.ModuleMatrix.Count - 4; i++)
     {
         var quietPart = new [] { false, false, false, false };
         var tmpLine = new List<bool>(quietPart);
         tmpLine.AddRange(qrCode.ModuleMatrix[i].Cast<bool>());
         tmpLine.AddRange(quietPart);
         qrCode.ModuleMatrix[i] = new BitArray(tmpLine.ToArray());
     }
 }
        public QrCode CreateQrCode(string plainText, EccLevel eccLevel, bool utf8Bom = false)
        {
            var encoding = GetEncodingFromPlaintext(plainText);
            var codedText = PlainTextToBinary(plainText, encoding, utf8Bom);
            var dataInputLength = GetDataLength(encoding, plainText, codedText);
            var version = GetVersion(dataInputLength, encoding, eccLevel);

            var modeIndicator = DecToBin((int)encoding, 4);
            var countIndicator = DecToBin(dataInputLength, GetCountIndicatorLength(version, encoding));
            var bitString = modeIndicator + countIndicator;

            bitString += codedText;

            //Fill up data code word
            var eccInfo = capacityEccTable.Single(x => x.Version == version && x.ErrorCorrectionLevel.Equals(eccLevel));
            var dataLength = eccInfo.TotalDataCodewords * 8;
            var lengthDiff = dataLength - bitString.Length;
            if (lengthDiff > 0)
                bitString += new string('0', Math.Min(lengthDiff, 4));
            if ((bitString.Length % 8) != 0)
                bitString += new string('0', 8 - (bitString.Length % 8));
            while (bitString.Length < dataLength)
                bitString += "1110110000010001";
            if (bitString.Length > dataLength)
                bitString = bitString.Substring(0, dataLength);

            //Calculate error correction words
            var codeWordWithEcc = new List<CodewordBlock>();
            for (var i = 0; i < eccInfo.BlocksInGroup1; i++)
            {
                var bitStr = bitString.Substring(i * eccInfo.CodewordsInGroup1 * 8, eccInfo.CodewordsInGroup1 * 8);
                codeWordWithEcc.Add(new CodewordBlock()
                {
                    BitString = bitStr,
                    BlockNumber = i + 1,
                    GroupNumber = 1,
                    CodeWords = BinaryStringToBitBlockList(bitStr),
                    ECCWords = CalculateEccWords(bitStr, eccInfo)
                });
            }
            bitString = bitString.Substring(eccInfo.BlocksInGroup1 * eccInfo.CodewordsInGroup1 * 8);
            for (var i = 0; i < eccInfo.BlocksInGroup2; i++)
            {
                var bitStr = bitString.Substring(i * eccInfo.CodewordsInGroup2 * 8, eccInfo.CodewordsInGroup2 * 8);
                codeWordWithEcc.Add(new CodewordBlock()
                {
                    BitString = bitStr,
                    BlockNumber = i + 1,
                    GroupNumber = 2,
                    CodeWords = BinaryStringToBitBlockList(bitStr),
                    ECCWords = CalculateEccWords(bitStr, eccInfo)
                });
            }

            //Interleave code words
            var interleavedWordsSb = new StringBuilder();
            for (var i = 0; i < Math.Max(eccInfo.CodewordsInGroup1, eccInfo.CodewordsInGroup2); i++)
            {
                var i1 = i;
                foreach (var codeBlock in codeWordWithEcc.Where(codeBlock => codeBlock.CodeWords.Count > i1))
                    interleavedWordsSb.Append(codeBlock.CodeWords[i]);
            }

            for (var i = 0; i < eccInfo.ECCPerBlock; i++)
            {
                var i1 = i;
                foreach (var codeBlock in codeWordWithEcc.Where(codeBlock => codeBlock.ECCWords.Count > i1))
                    interleavedWordsSb.Append(codeBlock.ECCWords[i]);
            }
            interleavedWordsSb.Append(new string('0', remainderBits[version - 1]));
            var interleavedData = interleavedWordsSb.ToString();

            //Place interleaved data on module matrix
            var qr = new QrCode(version);
            var blockedModules = new List<Rectangle>();
            ModulePlacer.PlaceFinderPatterns(ref qr, ref blockedModules);
            ModulePlacer.ReserveSeperatorAreas(qr.ModuleMatrix.Count, ref blockedModules);
            ModulePlacer.PlaceAlignmentPatterns(ref qr, alignmentPatternTable.Where(x => x.Version == version).Select(x => x.PatternPositions).First(), ref blockedModules);
            ModulePlacer.PlaceTimingPatterns(ref qr, ref blockedModules);
            ModulePlacer.PlaceDarkModule(ref qr, version, ref blockedModules);
            ModulePlacer.ReserveVersionAreas(qr.ModuleMatrix.Count, version, ref blockedModules);
            ModulePlacer.PlaceDataWords(ref qr, interleavedData, ref blockedModules);
            var maskVersion = ModulePlacer.MaskCode(ref qr, version, ref blockedModules);
            var formatStr = GetFormatString(eccLevel, maskVersion);

            ModulePlacer.PlaceFormat(ref qr, formatStr);
            if (version >= 7)
            {
                var versionString = GetVersionString(version);
                ModulePlacer.PlaceVersion(ref qr, versionString);
            }
            ModulePlacer.AddQuietZone(ref qr);
            return qr;
        }
                public static int Score(ref QrCode qrCode)
                {
                    var score = 0;
                    var size = qrCode.ModuleMatrix.Count;

                    //Penalty 1
                    for (var y = 0; y < size; y++)
                    {
                        var modInRow = 0;
                        var modInColumn = 0;
                        var lastValRow = qrCode.ModuleMatrix[y][0];
                        var lastValColumn = qrCode.ModuleMatrix[0][y];
                        for (var x = 0; x < size; x++)
                        {
                            if (qrCode.ModuleMatrix[y][x] == lastValRow)
                                modInRow++;
                            else
                                modInRow = 1;
                            if (modInRow == 5)
                                score += 3;
                            else if (modInRow > 5)
                                score++;
                            lastValRow = qrCode.ModuleMatrix[y][x];

                            if (qrCode.ModuleMatrix[x][y] == lastValColumn)
                                modInColumn++;
                            else
                                modInColumn = 1;
                            if (modInColumn == 5)
                                score += 3;
                            else if (modInColumn > 5)
                                score++;
                            lastValColumn = qrCode.ModuleMatrix[x][y];
                        }
                    }

                    //Penalty 2
                    for (var y = 0; y < size - 1; y++)
                    {
                        for (var x = 0; x < size - 1; x++)
                        {
                            if (qrCode.ModuleMatrix[y][x] == qrCode.ModuleMatrix[y][x + 1] &&
                                qrCode.ModuleMatrix[y][x] == qrCode.ModuleMatrix[y + 1][x] &&
                                qrCode.ModuleMatrix[y][x] == qrCode.ModuleMatrix[y + 1][x + 1])
                                score += 3;
                        }
                    }

                    //Penalty 3
                    for (var y = 0; y < size; y++)
                    {
                        for (var x = 0; x < size - 10; x++)
                        {
                            if ((qrCode.ModuleMatrix[y][x] &&
                                !qrCode.ModuleMatrix[y][x + 1] &&
                                qrCode.ModuleMatrix[y][x + 2] &&
                                qrCode.ModuleMatrix[y][x + 3] &&
                                qrCode.ModuleMatrix[y][x + 4] &&
                                !qrCode.ModuleMatrix[y][x + 5] &&
                                qrCode.ModuleMatrix[y][x + 6] &&
                                !qrCode.ModuleMatrix[y][x + 7] &&
                                !qrCode.ModuleMatrix[y][x + 8] &&
                                !qrCode.ModuleMatrix[y][x + 9] &&
                                !qrCode.ModuleMatrix[y][x + 10]) ||
                                (!qrCode.ModuleMatrix[y][x] &&
                                !qrCode.ModuleMatrix[y][x + 1] &&
                                !qrCode.ModuleMatrix[y][x + 2] &&
                                !qrCode.ModuleMatrix[y][x + 3] &&
                                qrCode.ModuleMatrix[y][x + 4] &&
                                !qrCode.ModuleMatrix[y][x + 5] &&
                                qrCode.ModuleMatrix[y][x + 6] &&
                                qrCode.ModuleMatrix[y][x + 7] &&
                                qrCode.ModuleMatrix[y][x + 8] &&
                                !qrCode.ModuleMatrix[y][x + 9] &&
                                qrCode.ModuleMatrix[y][x + 10]))
                            {
                                score += 40;
                            }

                            if ((qrCode.ModuleMatrix[x][y] &&
                                !qrCode.ModuleMatrix[x + 1][y] &&
                                qrCode.ModuleMatrix[x + 2][y] &&
                                qrCode.ModuleMatrix[x + 3][y] &&
                                qrCode.ModuleMatrix[x + 4][y] &&
                                !qrCode.ModuleMatrix[x + 5][y] &&
                                qrCode.ModuleMatrix[x + 6][y] &&
                                !qrCode.ModuleMatrix[x + 7][y] &&
                                !qrCode.ModuleMatrix[x + 8][y] &&
                                !qrCode.ModuleMatrix[x + 9][y] &&
                                !qrCode.ModuleMatrix[x + 10][y]) ||
                                (!qrCode.ModuleMatrix[x][x] &&
                                !qrCode.ModuleMatrix[x + 1][y] &&
                                !qrCode.ModuleMatrix[x + 2][y] &&
                                !qrCode.ModuleMatrix[x + 3][y] &&
                                qrCode.ModuleMatrix[x + 4][y] &&
                                !qrCode.ModuleMatrix[x + 5][y] &&
                                qrCode.ModuleMatrix[x + 6][y] &&
                                qrCode.ModuleMatrix[x + 7][y] &&
                                qrCode.ModuleMatrix[x + 8][y] &&
                                !qrCode.ModuleMatrix[x + 9][y] &&
                                qrCode.ModuleMatrix[x + 10][y]))
                            {
                                score += 40;
                            }
                        }
                    }

                    //Penalty 4
                    var blackModules = qrCode.ModuleMatrix.SelectMany(row => row.Cast<bool>()).Count(bit => bit);

                    var percent = (blackModules / (qrCode.ModuleMatrix.Count * qrCode.ModuleMatrix.Count)) * 100;
                    if (percent % 5 == 0)
                        score += Math.Min((Math.Abs(percent - 55) / 5), (Math.Abs(percent - 45) / 5)) * 10;
                    else
                        score += Math.Min((Math.Abs((int)Math.Floor((decimal)percent / 5) - 50) / 5), (Math.Abs(((int)Math.Floor((decimal)percent / 5) + 5) - 50) / 5)) * 10;

                    return score;
                }
            public static void PlaceVersion(ref QrCode qrCode, string versionStr)
            {
                var size = qrCode.ModuleMatrix.Count;
                var vStr = new string(versionStr.Reverse().ToArray());

                for (var x = 0; x < 6; x++)
                {
                    for (var y = 0; y < 3; y++)
                    {
                        qrCode.ModuleMatrix[y + size - 11][x] = vStr[x * 3 + y] == '1';
                        qrCode.ModuleMatrix[x][y + size - 11] = vStr[x * 3 + y] == '1';
                    }
                }
            }
Beispiel #43
0
    /// <summary>
    /// Returns a list of qrCodes.
    /// </summary>
    /// <returns></returns>
    private List<QrCode> GetQrCodeList()
    {
        List<QrCode> QrCodeList = new List<QrCode>();

        List<Table> tableList = this.GetTableList();

        foreach (Table t in tableList)
        {
            QrCode qr = new QrCode();

            qr.CompanyName = this.CompanyName;
            qr.TableName = t.TableName;
            qr.QrString = t.QrCode;
            qr.GenerateQrImage();

            QrCodeList.Add(qr);
        }

        return QrCodeList;
    }
    protected void Button2_Click(object sender, EventArgs e)
    {
        if (Session["id"]== null||Lyz_mc1.Text=="")
        {
        Label23.Text = "获取信息ID失败,无法生成图片。请刷新页面。";
        return;
        }
        string code = Lyz_mc1.Text.Trim();
        string path = Server.MapPath("./") + "ApplyPic\\";
        string FileName =path+ Session["id"].ToString().Trim()+".bmp";

        string codesize = Lyz_mc2.Text.Trim();
        string size = codesize.Substring(codesize.LastIndexOf("*") + 1);
        int cm = int.Parse(size);
        QrEncoder qrEncoder = new QrEncoder(ErrorCorrectionLevel.H);
        QrCode qrCode = new QrCode();
        qrEncoder.TryEncode(code, out qrCode);
        writeToFile(qrCode.Matrix, System.Drawing.Imaging.ImageFormat.Bmp, FileName, cm);

        Label23.Text = "QR图像生成成功";
        //下面修改信息
        SqlConnection con = dacon.getcon();
        SqlCommand myCommand = new SqlCommand("update proApply set  AllocFlag=4 where id='" + Session["id"] + "' ", con);//转为已经生成状态
        myCommand.Connection.Open();
        int i = (int)myCommand.ExecuteNonQuery();
        myCommand.Connection.Close();

        if (i < 1)
        {
        string str_Message = "转为已经生成状态失败。";
        Page.ClientScript.RegisterStartupScript(this.GetType(), "", "<Script>alert('" + str_Message + "');</Script>");
        //Page.RegisterStartupScript("", "<script>alert('" + str_Message + "');</script>");
        return;
        }
        else
        {
        string str_Message = "转为已经生成状态成功。";
        this.Image1.ImageUrl = "~\\client\\ApplyPic\\" + Session["id"].ToString().Trim() + ".bmp";
        Page.ClientScript.RegisterStartupScript(this.GetType(), "", "<Script>alert('" + str_Message + "');</Script>");
        Response.Redirect("ProcInfo.aspx?id=" + Session["id"]);
        //Page.RegisterStartupScript("", "<script>alert('" + str_Message + "');</script>");
        return;
        }
    }
 public static void PlaceDarkModule(ref QrCode qrCode, int version, ref List<Rectangle> blockedModules)
 {
     qrCode.ModuleMatrix[4 * version + 9][8] = true;
     blockedModules.Add(new Rectangle(8, 4 * version + 9, 1, 1));
 }