コード例 #1
0
		public static void QRCode(string data, int size)
		{
			QRCode qrbarcode = new QRCode();

			// Select QR Code data encoding type: numeric, alphanumeric, byte, and Kanji to select from.
			qrbarcode.Encoding = QRCodeEncoding.Auto;
			qrbarcode.Data = data;

			// Adjusting QR Code barcode module size and quiet zones on four sides.
			qrbarcode.ModuleSize = size;
			qrbarcode.LeftMargin = 12;
			qrbarcode.RightMargin = 12;
			qrbarcode.TopMargin = 12;
			qrbarcode.BottomMargin = 12;

			// Select QR Code Version (Symbol Size), available from V1 to V40, i.e. 21 x 21 to 177 x 177 modules.
			qrbarcode.Version = QRCodeVersion.V1;

			// Set QR-Code bar code Reed Solomon Error Correction Level: L(7%), M (15%), Q(25%), H(30%)
			qrbarcode.ECL = QRCodeErrorCorrectionLevel.L;
			qrbarcode.ImageFormat = System.Drawing.Imaging.ImageFormat.Png;

			// More barcode settings here, like ECI, FNC1, Structure Append, etc.

			// save barcode image into your system
			qrbarcode.drawBarcode(filepath);
		}
コード例 #2
0
ファイル: QrViewModel.cs プロジェクト: GiTechLab/QrCode4cs
        private void Generate()
        {
            try
            {
                var qrcode = new QRCode(new Options(Text));
                qrcode.Make();
                var c = qrcode.GetModuleCount();
                var bitmap = new bool[c][];

                for (var row = 0; row < c; row++)
                {
                    bitmap[row] = new bool[c];

                    for (var col = 0; col < c; col++)
                    {
                        var isDark = qrcode.IsDark(row, col);
                        bitmap[row][col] = isDark;
                    }
                }

                Bitmap = bitmap;
            }
            catch (Exception ex)
            {
                Text = "Sorry, an error: " + ex.Message;
                Bitmap = null;
            }
        }
コード例 #3
0
ファイル: QRCodeTestCase.cs プロジェクト: n1rvana/ZXing.NET
      public void test()
      {
         var qrCode = new QRCode();

         // First, test simple setters and getters.
         // We use numbers of version 7-H.
         qrCode.Mode = Mode.BYTE;
         qrCode.ECLevel = ErrorCorrectionLevel.H;
         qrCode.Version = Version.getVersionForNumber(7);
         qrCode.MaskPattern = 3;

         Assert.AreEqual(Mode.BYTE, qrCode.Mode);
         Assert.AreEqual(ErrorCorrectionLevel.H, qrCode.ECLevel);
         Assert.AreEqual(7, qrCode.Version.VersionNumber);
         Assert.AreEqual(3, qrCode.MaskPattern);

         // Prepare the matrix.
         var matrix = new ByteMatrix(45, 45);
         // Just set bogus zero/one values.
         for (int y = 0; y < 45; ++y)
         {
            for (int x = 0; x < 45; ++x)
            {
               matrix.set(x, y, (y + x) % 2 == 1);
            }
         }

         // Set the matrix.
         qrCode.Matrix = matrix;
         Assert.AreEqual(matrix, qrCode.Matrix);
      }
コード例 #4
0
        public ByteMatrix encode(System.String contents, BarcodeFormat format, int width, int height, System.Collections.Generic.Dictionary<Object,Object> hints)
        {
            if (contents == null || contents.Length == 0)
            {
                throw new System.ArgumentException("Found empty contents");
            }

            if (format != BarcodeFormat.QR_CODE)
            {
                throw new System.ArgumentException("Can only encode QR_CODE, but got " + format);
            }

            if (width < 0 || height < 0)
            {
                throw new System.ArgumentException("Requested dimensions are too small: " + width + 'x' + height);
            }

            ErrorCorrectionLevel errorCorrectionLevel = ErrorCorrectionLevel.L;
            if (hints != null && hints.ContainsKey(EncodeHintType.ERROR_CORRECTION))
            {
                errorCorrectionLevel = (ErrorCorrectionLevel)hints[EncodeHintType.ERROR_CORRECTION]; //UPGRADE: Fixed dictionary key grab issue
            }

            QRCode code = new QRCode();
            Encoder.encode(contents, errorCorrectionLevel, hints, code);
            return renderResult(code, width, height);
        }
コード例 #5
0
ファイル: Encoder.cs プロジェクト: marinehero/ThinkAway.net
		public static void  Encode(System.String content, ErrorCorrectionLevel ecLevel, System.Collections.Hashtable hints, QRCode qrCode)
		{
			
			System.String encoding = hints == null?null:(System.String) hints[EncodeHintType.CHARACTER_SET];
			if (encoding == null)
			{
				encoding = DEFAULT_BYTE_MODE_ENCODING;
			}
			
			// Step 1: Choose the mode (encoding).
			Mode mode = ChooseMode(content, encoding);
			
			// Step 2: Append "bytes" into "dataBits" in appropriate encoding.
			BitVector dataBits = new BitVector();
			appendBytes(content, mode, dataBits, encoding);
			// Step 3: Initialize QR code that can contain "dataBits".
			int numInputBytes = dataBits.sizeInBytes();
			InitQrCode(numInputBytes, ecLevel, mode, qrCode);
			
			// Step 4: Build another bit vector that contains header and data.
			BitVector headerAndDataBits = new BitVector();
			
			// Step 4.5: Append ECI message if applicable
			if (mode == Mode.BYTE && !DEFAULT_BYTE_MODE_ENCODING.Equals(encoding))
			{
				CharacterSetECI eci = CharacterSetECI.getCharacterSetECIByName(encoding);
				if (eci != null)
				{
					AppendECI(eci, headerAndDataBits);
				}
			}
			
			appendModeInfo(mode, headerAndDataBits);
			
			int numLetters = mode.Equals(Mode.BYTE)?dataBits.sizeInBytes():content.Length;
			appendLengthInfo(numLetters, qrCode.Version, mode, headerAndDataBits);
			headerAndDataBits.appendBitVector(dataBits);
			
			// Step 5: Terminate the bits properly.
			TerminateBits(qrCode.NumDataBytes, headerAndDataBits);
			
			// Step 6: Interleave data bits with error correction code.
			BitVector finalBits = new BitVector();
			InterleaveWithEcBytes(headerAndDataBits, qrCode.NumTotalBytes, qrCode.NumDataBytes, qrCode.NumRSBlocks, finalBits);
			
			// Step 7: Choose the mask pattern and set to "qrCode".
			ByteMatrix matrix = new ByteMatrix(qrCode.MatrixWidth, qrCode.MatrixWidth);
			qrCode.MaskPattern = ChooseMaskPattern(finalBits, qrCode.ECLevel, qrCode.Version, matrix);
			
			// Step 8.  Build the matrix and set it to "qrCode".
			MatrixUtil.buildMatrix(finalBits, qrCode.ECLevel, qrCode.Version, qrCode.MaskPattern, matrix);
			qrCode.Matrix = matrix;
			// Step 9.  Make sure we have a valid QR Code.
			if (!qrCode.Valid)
			{
				throw new WriterException(string.Format("Invalid QR code: {0}", qrCode));
			}
		}
コード例 #6
0
        /// <summary>
        /// Writes QRCode to file
        /// </summary>
        /// <param name="dealerQrCode">object containing filename and qrcodeImage to write if Lincoln for layering</param>
        /// <param name="qrCode">other vendor QRCode (straight write)</param>
        public void WriteQrCode(ref DealerQRCode dealerQrCode, QRCode qrCode)
        {
            using (var outerStream = new MemoryStream())
            {
                qrCode.drawBarcode(outerStream);
                dealerQrCode.QRCodeImage = outerStream.ToArray();
                outerStream.Flush();

                var basePath = dealerQrCode.IsGeneric
                                      ? (_backEndType == BackEndType.CatalogAdminDev
                                             ? EnviornmentPath.GenericDev
                                             : _backEndType == BackEndType.CatalogAdminStaging
                                                   ? EnviornmentPath.GenericStaging
                                                   : EnviornmentPath.GenericProduction)
                                      : (_backEndType == BackEndType.CatalogAdminDev
                                             ? EnviornmentPath.Dev
                                             : _backEndType == BackEndType.CatalogAdminStaging
                                                   ? EnviornmentPath.Staging
                                                   : EnviornmentPath.Production);

                using (var fileStream = new FileStream(string.Format(@"{0}\{1}", basePath, dealerQrCode.FileName), FileMode.OpenOrCreate, FileAccess.ReadWrite))
                {
                    qrCode.drawBarcode(fileStream);
                }

                //Must Layer Lincoln logo
                //if (dealerQrCode.Brand.ToLower() == "lincoln")
                //{
                //    var layerStream = new MemoryStream();
                //    using (var innerStream = new MemoryStream(dealerQrCode.QRCodeImage))
                //    {
                //        var bmp = new Bitmap(innerStream);
                //        var logoImg = Resources.lincolnlogo;
                //        using (var layeredBitMap = ImageImpose.SuperImpose(bmp, logoImg))
                //        {
                //            layeredBitMap.Save(layerStream, ImageFormat.Jpeg);

                //            dealerQrCode.QRCodeImage = layerStream.ToArray();

                //            using (var fileStream =new FileStream(string.Format("{0}/{1}", basePath, dealerQrCode.FileName),FileMode.OpenOrCreate, FileAccess.ReadWrite))
                //            {
                //                bmp.Save(fileStream, ImageFormat.Jpeg);
                //            }
                //        }
                //    }

                //}
                //else
                //{
                //    using (var fileStream = new FileStream(string.Format(@"{0}\{1}", basePath, dealerQrCode.FileName), FileMode.OpenOrCreate, FileAccess.ReadWrite))
                //    {
                //        qrCode.drawBarcode(fileStream);
                //    }
                //}
            }
        }
コード例 #7
0
ファイル: Form1.cs プロジェクト: Charliiee/QRCoder
 private void renderQRCode()
 {
     string level = comboBoxECC.SelectedItem.ToString();
     QRCodeGenerator.ECCLevel eccLevel = (QRCodeGenerator.ECCLevel)(level == "L" ? 0 : level == "M" ? 1 : level == "Q" ? 2 : 3);
     QRCodeGenerator qrGenerator = new QRCodeGenerator();
     QRCodeData qrCodeData = qrGenerator.CreateQrCode(textBoxQRCode.Text, eccLevel);
     QRCode qrCode = new QRCode(qrCodeData);
     
     pictureBoxQRCode.BackgroundImage = qrCode.GetGraphic(20, Color.Black, Color.White, getIconBitmap(), (int)iconSize.Value);
 }
コード例 #8
0
ファイル: QRCodeTestCase.cs プロジェクト: n1rvana/ZXing.NET
 public void testToString1()
 {
    {
       var qrCode = new QRCode();
       const string expected = "<<\n" +
                               " mode: \n" +
                               " ecLevel: \n" +
                               " version: null\n" +
                               " maskPattern: -1\n" +
                               " matrix: null\n" +
                               ">>\n";
       Assert.AreEqual(expected, qrCode.ToString());
    }
 }
コード例 #9
0
        public QRLinkWindow(PedroFileDownload fileData)
        {

            InitializeComponent();
            //PayloadGenerator.Url url2 = new PayloadGenerator.Url("www.google.es");
            PayloadGenerator.Url url = new PayloadGenerator.Url(fileData.Url + @"/index.html");
            //PayloadGenerator.WiFi wifiPayload = new PayloadGenerator.WiFi("MyWiFi-SSID", "MyWiFi-Pass", PayloadGenerator.WiFi.Authentication.WPA);
            QRCodeGenerator.ECCLevel  eccLevel= QRCodeGenerator.ECCLevel.L;
            QRCodeGenerator qrGenerator = new QRCodeGenerator();
            //QRCodeData qrCodeData = qrGenerator.CreateQrCode(@fileData.Url+@"\index.html", eccLevel);
            QRCodeData qrCodeData = qrGenerator.CreateQrCode(url.ToString(), eccLevel);
            QRCode qrCode = new QRCode(qrCodeData);
            Bitmap qrCodeBitmap = qrCode.GetGraphic(20, "#000000", "#ffffff");

            ImageSource qrImageSource =ConvertBitmapToBitmapImage(qrCodeBitmap);
            imgQrCode.Source = qrImageSource;
        }
コード例 #10
0
        /// <summary>
        /// Создать растровое изображение с QR Code массив более твердый или люк фон
        /// </summary>
        /// <param name="QRCode">QRCode</param>
        /// <param name="ModuleSize">Размер модуля в пикселях</param>
        /// <param name="QuietZone">Тихая зона в пикселях</param>
        /// <param name="Background">Фон растрового изображения</param>
        /// <param name="QRCodeCenterPosX">QRCode позиция X </param>
        /// <param name="QRCodeCenterPosY">QRCode позиция Y</param>
        /// <param name="Rotation">Вращение QRCode в градусах</param>
        /// <returns>Растровое изображение QRCode</returns>
        public static Bitmap CreateBitmap(QRCode QRCode, Int32 ModuleSize, Int32 QuietZone, Bitmap Background, Double QRCodeCenterPosX, Double QRCodeCenterPosY, Double Rotation)
		{
            // Размер растрового изображения QRCode
            Int32 QRCodeImageDimension = QRCode.QRCodeImageDimension(ModuleSize, QuietZone);

		    // transformation matrix
		    Matrix Matrix = new Matrix();
		    Matrix.Translate((float) QRCodeCenterPosX , (float) QRCodeCenterPosY);
		    if (Rotation != 0) Matrix.Rotate((float) Rotation);

            // Создание копии фона
            Bitmap OutputImage = new Bitmap(Background);

            // Создание графического объекта
            Graphics Graphics = Graphics.FromImage(OutputImage);

            // Присоединить матрицу преобразования
            Graphics.Transform = Matrix;

            // Положение верхнего левого угла QRCode относительно центра QRCode
            Double QRCodePos = -0.5 * QRCodeImageDimension;

            // очистить область для QRCode
            Graphics.FillRectangle(BrushWhite, (float) QRCodePos, (float) QRCodePos, QRCodeImageDimension, QRCodeImageDimension);

		    // Ярлык
		    Int32 Dimension = QRCode.QRCodeDimension;
		    Boolean[,] Code = QRCode.QRCodeMatrix;

            // Добавить тихую зону
            QRCodePos += QuietZone;

            // Краска QR-код изображения
            for (int Row = 0; Row < Dimension; Row++)
			    for (int Col = 0; Col < Dimension; Col++)
			    {
			        if (Code[Row, Col]) Graphics.FillRectangle(BrushBlack, (float) (QRCodePos + Col * ModuleSize), (float) (QRCodePos + Row * ModuleSize), ModuleSize, ModuleSize);
			    }

		    return OutputImage;
		}
コード例 #11
0
        /// <summary>
        /// Создать растровое изображение с QR Code массив более твердый или люк фон
        /// </summary>
        /// <param name="QRCode">QRCode</param>
        /// <param name="ModuleSize">Размер модуля в пикселях</param>
        /// <param name="QuietZone">Quiet zone in pixels</param>
        /// <param name="Background">Фон растрового изображения</param>
        /// <param name="QRCodeCenterPosX">QRCode позиция X </param>
        /// <param name="QRCodeCenterPosY">QRCode позиция Y</param>
        /// <param name="Rotation">Вращение QRCode в градусах</param>
        /// <param name="CameraDistance">Расстояние перспективной камеры в пикселях</param>
        /// <param name="ViewXRotation">Вид камеры вращение оси X в градусах</param>
        /// <returns>Растровое изображение QRCode</returns>
        public static Bitmap CreateBitmap(QRCode QRCode, Int32 ModuleSize, Int32 QuietZone, Bitmap Background, Double QRCodeCenterPosX, Double QRCodeCenterPosY, Double Rotation, Double CameraDistance, Double ViewXRotation)
		{
            // Cоздать перспективный объект
            Perspective Perspective = new Perspective(QRCodeCenterPosX, QRCodeCenterPosY, Rotation, CameraDistance, ViewXRotation);

            // Cоздание графического объекта
            Graphics Graphics = Graphics.FromImage(Background);

            // размер растрового изображения QRCode
            Int32 QRCodeImageDimension = QRCode.QRCodeImageDimension(ModuleSize, QuietZone);

            // Половинный размер изображения
            Double HalfDimension = 0.5 * QRCodeImageDimension;

            // Полигон
            PointF[] Polygon = new PointF[4];
		    Perspective.GetPolygon(-HalfDimension, -HalfDimension, QRCodeImageDimension, Polygon);

            // Очистить область для QRCode
            Graphics.FillPolygon(BrushWhite, Polygon);

		    // Ярлык
		    Int32 Dimension = QRCode.QRCodeDimension;
		    Boolean[,] Code = QRCode.QRCodeMatrix;

            // Добавить тихую зону
            Double QRCodePos = -HalfDimension + QuietZone;

            // краска QRCode изображения
            for (int Row = 0; Row < Dimension; Row++)
			    for (int Col = 0; Col < Dimension; Col++)
			    {
			        if (Code[Row, Col])
				    {
				        Perspective.GetPolygon(QRCodePos + Col * ModuleSize, QRCodePos + Row * ModuleSize, ModuleSize, Polygon);
				        Graphics.FillPolygon(BrushBlack, Polygon);
				    }
			    }

		    return Background;
		}
コード例 #12
0
        public async Task <string> GetQRCodeAsync(Reservation reservation)
        {
            // var qrText = "maimuta";
            Random       random = new Random();
            const string chars  = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
            var          qrText = new string(Enumerable.Repeat(chars, 10)
                                             .Select(s => s[random.Next(s.Length)]).ToArray());

            // Console.Write(qrText);
            QRCoder.QRCodeGenerator qrGenerator = new QRCodeGenerator();
            QRCodeData qrCodeData  = qrGenerator.CreateQrCode(qrText, QRCodeGenerator.ECCLevel.Q);
            QRCode     qrCode      = new QRCode(qrCodeData);
            Bitmap     qrCodeImage = qrCode.GetGraphic(20);

            // Image qrImage = (Image)qrCodeImage;
            using (MemoryStream ms = new MemoryStream())
            {
                qrCodeImage.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
                byte[] byteArr = ms.ToArray();
                string b64Txt  = Convert.ToBase64String(byteArr);
                string message;

                string hrefText = "data:image/png;base64," + b64Txt;

                message = "Dear " + reservation.OwnerName + ",<br/><br/>We are glad to inform you that you won a 25% discount voucher because you made an appointment in " + reservation.ReservationDate.ToString("dd/MM/yyyy") + " for " + reservation.NumberPersons + "  people for " + reservation.ClassName + " class ! " +
                          "Your code is right here:" + "<p><img src='" + hrefText + "'</p> " + " <br/><br/>You can use it only on our site in the online shopping section." + " <br/><br/>Enjoy your prize and thank you for your appointment, " + "<br/><br/>Just Move team. ";
                SaleQRCode code = new SaleQRCode
                {
                    Id     = Guid.NewGuid().ToString(),
                    QRText = qrText,
                    Image  = hrefText,
                };
                _qrCodeRepository.Create(code);
                //aici

                await _emailSender.SendEmailAsync(reservation.Email, "25% OFF VOUCHER",
                                                  message);

                return(hrefText);
            }
        }
コード例 #13
0
        public async Task <ReceiptDto> Handle(FetchReceiptQuery request, CancellationToken cancellationToken)
        {
            if (String.IsNullOrWhiteSpace(request.BarcodeString))
            {
                throw new ValidationException($"{nameof(request.BarcodeString)} is invalid");
            }

            var qrcode = QRCode.Parse(request.BarcodeString);

            var receipt = await _fiscalDataService.GetReceipt(qrcode);

            var result = new ReceiptDto
            {
                ID = receipt.ID,
                FiscalDocumentNumber = receipt.FiscalDocumentNumber,
                FiscalDriveNumber    = receipt.FiscalDriveNumber,
                FiscalType           = receipt.FiscalType,
                DateTime             = receipt.DateTime,
                TotalSum             = receipt.TotalSum,
                OperationType        = receipt.OperationType,
                Place        = receipt.Place,
                Organization = new OrganizationDto
                {
                    INN  = receipt.Organization.INN,
                    Name = receipt.Organization.Name
                },
                ProductItems = receipt.ProductItems.Select(pi => new ProductItemDto
                {
                    ID        = pi.ID,
                    Name      = pi.Name,
                    Price     = pi.Price,
                    Quantity  = pi.Quantity,
                    Sum       = pi.Sum,
                    NDS       = pi.NDS,
                    ReceiptID = pi.ReceiptID,
                    ProductID = pi.ProductID
                }).ToArray()
            };

            return(result);
        }
コード例 #14
0
        private static void GenerateQRCode(string payloadString, QRCodeGenerator.ECCLevel eccLevel, string outputFileName, SupportedImageFormat imgFormat, int pixelsPerModule, string foreground, string background)
        {
            using (var generator = new QRCodeGenerator())
            {
                using (var data = generator.CreateQrCode(payloadString, eccLevel))
                {
                    switch (imgFormat)
                    {
                    case SupportedImageFormat.Png:
                    case SupportedImageFormat.Jpg:
                    case SupportedImageFormat.Gif:
                    case SupportedImageFormat.Bmp:
                    case SupportedImageFormat.Tiff:
                        using (var code = new QRCode(data))
                        {
                            using (var bitmap = code.GetGraphic(pixelsPerModule, foreground, background, true))
                            {
                                var actualFormat = new OptionSetter().GetImageFormat(imgFormat.ToString());
                                bitmap.Save(outputFileName, actualFormat);
                            }
                        }
                        break;

                    case SupportedImageFormat.Svg:
                        using (var code = new SvgQRCode(data))
                        {
                            var test = code.GetGraphic(pixelsPerModule, foreground, background, true);
                            using (var f = File.CreateText(outputFileName))
                            {
                                f.Write(test);
                                f.Flush();
                            }
                        }
                        break;

                    default:
                        throw new ArgumentOutOfRangeException(nameof(imgFormat), imgFormat, null);
                    }
                }
            }
        }
コード例 #15
0
        /// <summary>
        /// Create Bitmap image from QR code array
        /// </summary>
        /// <param name="QRCode">QR Code</param>
        /// <param name="ModuleSize">Module size in pixels</param>
        /// <param name="QuietZone">Quiet zone in pixels</param>
        /// <returns>Bitmap image of QR code</returns>
        public static Bitmap CreateBitmap
        (
            QRCode QRCode,
            int ModuleSize,
            int QuietZone
        )
        {
            // qr code bitmap dimension
            int BitmapDimension = QRCode.QRCodeImageDimension(ModuleSize, QuietZone);

            // create picture object and make it white
            Bitmap   ImageBitmap = new Bitmap(BitmapDimension, BitmapDimension);
            Graphics Graphics    = Graphics.FromImage(ImageBitmap);

            Graphics.FillRectangle(BrushWhite, 0, 0, BitmapDimension, BitmapDimension);

            // shortcut
            int Dimension = QRCode.QRCodeDimension;

            bool[,] Code = QRCode.QRCodeMatrix;
            int PosX = QuietZone;
            int PosY = QuietZone;

            // paint QR Code image
            for (int Row = 0; Row < Dimension; Row++)
            {
                for (int Col = 0; Col < Dimension; Col++)
                {
                    if (Code[Row, Col])
                    {
                        Graphics.FillRectangle(BrushBlack, PosX, PosY, ModuleSize, ModuleSize);
                    }
                    PosX += ModuleSize;
                }
                PosX  = QuietZone;
                PosY += ModuleSize;
            }

            // return bitmap
            return(ImageBitmap);
        }
コード例 #16
0
        public JsonResult QrOlustur()
        {
            var result = (from p in db.Product
                          join a in db.QrcodeInfo on p.ProductID equals a.QrCodeInfoID

                          select new QrProductViewModels
            {
                ProductID = p.ProductID,
                QrCodeInfoID = a.QrCodeInfoID,
                ProductName = p.ProductName,
                ProductionDate = a.ProductionDate,
                Size = p.Size,
                SKT = a.SKT,
                TETT = a.TETT,
                CategoryID = p.CategoryID,
                UnitsInStock = p.UnitsInStock
            }).ToList().FirstOrDefault();



            ViewBag.QrCode = result.SKT.ToString();

            QRCodeGenerator qrGenerator = new QRCodeGenerator();
            QRCodeData      qrCodeData  = qrGenerator.CreateQrCode(ViewBag.QrCode, QRCodeGenerator.ECCLevel.Q);
            QRCode          qrCode      = new QRCode(qrCodeData);
            //System.Web.UI.WebControls.Image imgBarCode = new System.Web.UI.WebControls.Image();
            //imgBarCode.Height = 150;
            //imgBarCode.Width = 150;
            Bitmap bitMap = qrCode.GetGraphic(20);

            MemoryStream ms = new MemoryStream();

            bitMap.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
            ViewBag.imageBytes = ms.ToArray();

            //imgBarCode.ImageUrl = "data:image/png;base64," + Convert.ToBase64String(byteImage);



            return(Json(ms.ToArray(), JsonRequestBehavior.AllowGet));
        }
コード例 #17
0
        public ActionResult Index(string txtQRCode)
        {
            ViewBag.txtQRCode = txtQRCode;
            QRCodeGenerator qrGenerator = new QRCodeGenerator();
            QRCodeData      qrCodeData  = qrGenerator.CreateQrCode(txtQRCode, QRCodeGenerator.ECCLevel.Q);
            QRCode          qrCode      = new QRCode(qrCodeData);

            System.Web.UI.WebControls.Image imgBarCode = new System.Web.UI.WebControls.Image();
            imgBarCode.Height = 150;
            imgBarCode.Width  = 150;
            using (Bitmap bitMap = qrCode.GetGraphic(20))
            {
                using (MemoryStream ms = new MemoryStream())
                {
                    bitMap.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
                    ViewBag.imageBytes = ms.ToArray();
                    //imgBarCode.ImageUrl = "data:image/png;base64," + Convert.ToBase64String(byteImage);
                }
            }
            return(View());
        }
コード例 #18
0
        private void GenerateCode_Click(object sender, EventArgs e)
        {
            var credentials = new WifiCredentials {
                Ssid = Ssid.Text.Trim(), Pwd = Password.Text.Trim()
            };
            string base40 = credentials.ToBase40();

            using (var generator = new QRCodeGenerator())
                using (var codeData = generator.CreateQrCode(base40, QRCodeGenerator.ECCLevel.Q))
                    using (var qrCode = new QRCode(codeData))
                    {
                        Bitmap codeImage   = qrCode.GetGraphic(20);
                        float  resizeScale = Math.Min((float)(QrCodePic.Width - 2) / codeImage.Width, (float)(QrCodePic.Height - 2) / codeImage.Height);
                        Bitmap resized     = new Bitmap(QrCodePic.Width, QrCodePic.Height);
                        var    graphics    = Graphics.FromImage(resized);
                        graphics.FillRectangle(new SolidBrush(Color.White), new RectangleF(0, 0, resized.Width, resized.Height));
                        graphics.DrawImage(codeImage, ((int)resized.Width - ((int)(codeImage.Width * resizeScale))) / 2,
                                           ((int)resized.Height - ((int)(codeImage.Height * resizeScale))) / 2, ((int)(codeImage.Width * resizeScale)), ((int)(codeImage.Height * resizeScale)));
                        QrCodePic.Image = resized;
                    }
        }
コード例 #19
0
        public ActionResult Encode(string msg = "http://bit.bitdao.cn/")
        {
            try
            {
                QRCodeGenerator qrGenerator = new QRCodeGenerator();
                QRCodeData      qrCodeData  = qrGenerator.CreateQrCode(msg, QRCodeGenerator.ECCLevel.L);
                QRCode          qrCode      = new QRCode(qrCodeData);
                Bitmap          qrCodeImage = qrCode.GetGraphic(20);

                MemoryStream ms = new MemoryStream();
                qrCodeImage.Save(ms, ImageFormat.Png);
                byte[] bytes = ms.GetBuffer();
                ms.Close();
                return(File(bytes, "image/jpeg"));
            }
            catch (Exception ex)
            {
                LogHelper.SaveLog(ex);
                return(Json(new { Code = 1, Msg = "服务器异常,请联系管理员!" }));
            }
        }
コード例 #20
0
        /// <summary>
        /// 创建二维码
        /// </summary>
        /// <param name="content">内容</param>
        /// <returns></returns>
        public virtual byte[] CreateQrCode(string content)
        {
            QRCodeGenerator generator = new QRCodeGenerator();
            QRCodeData      data      = generator.CreateQrCode(content, _level);
            //if (string.IsNullOrWhiteSpace(_logoPath))
            //{
            //    BitmapByteQRCode bitmapByteQrCode = new BitmapByteQRCode(data);
            //    return bitmapByteQrCode.GetGraphic(_size);
            //}

            QRCode qrCode = new QRCode(data);

            using (var bitmap = qrCode.GetGraphic(_size, _foregroundColor, _backgroundColor, GetLogo()))
            {
                using (var ms = new MemoryStream())
                {
                    bitmap.Save(ms, ImageFormat.Png);
                    return(ms.ToArray());
                }
            }
        }
コード例 #21
0
        private void RenderQrCode()
        {
            QRCodeGenerator.ECCLevel eccLevel = QRCodeGenerator.ECCLevel.M;
            using (QRCodeGenerator qrGenerator = new QRCodeGenerator())
            {
                using (QRCodeData qrCodeData = qrGenerator.CreateQrCode(address, eccLevel))
                {
                    using (QRCode qrCode = new QRCode(qrCodeData))
                    {
                        pbQrCode.BackgroundImage = qrCode.GetGraphic(10, Color.Black, Color.White,
                                                                     null, 1);

                        this.pbQrCode.Size = new System.Drawing.Size(pbQrCode.Width, pbQrCode.Height);
                        //Set the SizeMode to center the image.
                        this.pbQrCode.SizeMode = PictureBoxSizeMode.CenterImage;

                        pbQrCode.SizeMode = PictureBoxSizeMode.StretchImage;
                    }
                }
            }
        }
コード例 #22
0
        static void Main(string[] args)
        {
            // Create and activate QRCode component instance
            using (QRCode barcode = new QRCode())
            {
                barcode.RegistrationName = "demo";
                barcode.RegistrationKey  = "demo";

                // Sample byte array to use as value
                byte[] byteArray = new byte[] { 0, 10, 11, 12, 13, 14, 15, 0xFF };

                // Set value by converting byte array to string
                barcode.Value = Encoding.ASCII.GetString(byteArray);

                // Save barcode image
                barcode.SaveImage("result.png");

                // Open the image in default associated application (for the demo purpose)
                Process.Start("result.png");
            }
        }
コード例 #23
0
    private MarkerData GetMarkerDataByQrCode(QRCode qrCode)
    {
        _tmpCoordinateSystem.SpatialNodeId = qrCode.SpatialGraphNodeId;

        if (_tmpCoordinateSystem.ComputePose(out Pose spongyPose))
        {
            Pose frozenPose = WorldLockingManager.GetInstance().FrozenFromSpongy.Multiply(spongyPose);
            MyPositionMarkerHelper.SetGlobalPose(frozenPose);

            Pose localPose = MyPositionMarkerHelper.GetLocalPose();

            return(new MarkerData(
                       true,
                       qrCode.Data,
                       localPose.position,
                       localPose.rotation,
                       qrCode.PhysicalSideLength
                       ));
        }
        return(null);
    }
コード例 #24
0
        public void InsertQrCodeGeolocation(int userId, string latitude, string longtitude)
        {
            Geolocation generator = new Geolocation(latitude, longtitude);
            string      location  = generator.ToString();

            QRCodeGenerator qrGenerator = new QRCodeGenerator();
            QRCodeData      qrCodeData  = qrGenerator.CreateQrCode(location, QRCodeGenerator.ECCLevel.Q);
            QRCode          qrCode      = new QRCode(qrCodeData);
            var             qrCodeImage = qrCode.GetGraphic(20);

            using (MemoryStream ms = new MemoryStream())
            {
                qrCodeImage.Save(ms, ImageFormat.Png);
                qrCodeGeoRepository.Insert(new QrCodeGeoEntity()
                {
                    UserId     = userId,
                    QrCodeType = QrCodeType.LocationEncodedQrCode,
                    Content    = ms.ToArray()
                });
            }
        }
コード例 #25
0
ファイル: Window.cs プロジェクト: xize/Cipher
        private void button1_Click(object sender, EventArgs e)
        {
            cipherResult1.code.Text = ""; //clear it.
            cipherResult1.code.Hide();

            DialogResult r = qrprompt.ShowDialog();

            if (r == DialogResult.OK)
            {
                string formatQR = (qrprompt.GetAccount() == null ? Crypto.Decrypt(textBox1.Text, textBox2.Text) : "otpauth://totp/" + qrprompt.GetServiceName() + ":" + qrprompt.GetAccount() + "?secret=" + Crypto.Decrypt(textBox1.Text, textBox2.Text) + "&issuer=" + qrprompt.GetServiceName());

                if (textBox1.Text.Length > 0 && textBox2.Text.Length > 0)
                {
                    cipherResult1.qrpanel.BackgroundImage = QRCode.getFactory().generateQR(formatQR, 130, 130);
                }
                else
                {
                    MessageBox.Show("both fields \"text\" and \"phrase\" needs to be filled in!", "Error!");
                }
            }
        }
        /// <summary>
        /// 二维码显示
        /// </summary>
        void viewModel_CodeChange()
        {
            Dispatcher.Invoke(new Action(() =>
            {
                string url               = viewModel.ClientObject.CodeUrl + "?param=";
                string AESCode           = string.Format("schoolNo={0}&clientNo={1}&codeTime={2}", viewModel.ClientObject.ClientSetting.ClientNo.Substring(0, viewModel.ClientObject.ClientSetting.ClientNo.Length - 2), viewModel.ClientObject.ClientSetting.ClientNo, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                Bitmap bitmap            = QRCode.GetDimensionalCode(url + AESAlgorithm.AESEncrypt(AESCode, "SeatManage_WeiCharCode"), 6, 8);
                IntPtr hBitmap           = bitmap.GetHbitmap();
                BitmapSource bitmapImage = new BitmapImage();

                try
                {
                    bitmapImage = Imaging.CreateBitmapSourceFromHBitmap(hBitmap, IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());
                }
                finally
                {
                    DeleteObject(hBitmap);
                }
                imgCode.Fill = new ImageBrush(bitmapImage);
            }));
        }
コード例 #27
0
ファイル: ColorsDemo.cs プロジェクト: tomekziel/QRCoder
        private static void RysowankiMaska()
        {
            QRCodeGenerator qrGenerator = new QRCodeGenerator();
            int             i           = 0;

            foreach (int version in new int[] { 2, 7, 14 })
            {
                QRCodeData qrCodeData = qrGenerator.CreateQrCode(
                    "Maska pattern",
                    QRCodeGenerator.ECCLevel.L,
                    requestedVersion: version);;

                QRCode qrc = new QRCode(qrCodeData);

                var b = qrc.GetGraphic(
                    new int[] { 20, 20, 10 }[i++],
                    new ColorProviders.ColorProviderRysowankiAllReserved(),
                    drawQuietZones: false, drawThinLines: true);
                b.Save(String.Format("RysowankiMaska{0:00}.png", version));
            }
        }
コード例 #28
0
        public void GenerateQr(string data)
        {
            QRCodeData qrCodeData = _qrGenerator.CreateQrCode(data, QRCodeGenerator.ECCLevel.Q);
            QRCode     qrCode     = new QRCode(qrCodeData);
            Bitmap     qrCodeImage;

            if (qrCode.GetGraphic(10).Height > Screen.PrimaryScreen.Bounds.Height - 80)
            {
                qrCodeImage = new Bitmap(qrCode.GetGraphic(10), new Size(Screen.PrimaryScreen.Bounds.Height - 80, Screen.PrimaryScreen.Bounds.Height - 80));
            }
            else
            {
                qrCodeImage = qrCode.GetGraphic(20);
            }

            Form form = new QRCodeWindow(qrCodeImage, qrCodeImage.Width, qrCodeImage.Height);
            Size s    = new Size(qrCodeImage.Width, qrCodeImage.Height);

            form.Size = s;
            form.ShowDialog();
        }
コード例 #29
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="url">存储内容</param>
        /// <param name="pixel">像素大小</param>
        /// <returns></returns>
        public static Bitmap GetLogoQRCode(string url, string logoPath, int pixel)
        {
            QRCodeGenerator generator = new QRCodeGenerator();
            QRCodeData      codeData  = generator.CreateQrCode(url, QRCodeGenerator.ECCLevel.M, true);

            QRCoder.QRCode qrcode  = new QRCode(codeData);
            Bitmap         icon    = new Bitmap(logoPath);
            Bitmap         qrImage = qrcode.GetGraphic(pixel, Color.Black, Color.White, icon, 15, 6, true);

            #region 参数介绍
            //GetGraphic方法参数介绍
            //pixelsPerModule //生成二维码图片的像素大小 ,我这里设置的是5
            //darkColor       //暗色   一般设置为Color.Black 黑色
            //lightColor      //亮色   一般设置为Color.White  白色
            //icon             //二维码 水印图标 例如:Bitmap icon = new Bitmap(context.Server.MapPath("~/images/zs.png")); 默认为NULL ,加上这个二维码中间会显示一个图标
            //iconSizePercent  //水印图标的大小比例 ,可根据自己的喜好设置
            //iconBorderWidth  // 水印图标的边框
            //drawQuietZones   //静止区,位于二维码某一边的空白边界,用来阻止读者获取与正在浏览的二维码无关的信息 即是否绘画二维码的空白边框区域 默认为true
            #endregion
            return(qrImage);
        }
コード例 #30
0
        // GET api/values

        public ImageUploadResult GetValues(String message)
        {
            QRCodeData qrCodeData  = qrGenerator.CreateQrCode(" {'Code': '1' }", QRCodeGenerator.ECCLevel.Q);
            QRCode     qrCode      = new QRCode(qrCodeData);
            Bitmap     qrCodeImage = qrCode.GetGraphic(20);

            System.IO.MemoryStream stream = new MemoryStream();
            qrCodeImage.Save(stream, ImageFormat.Png);

            var bytes = ((MemoryStream)stream).ToArray();

            System.IO.Stream  inputStream = new MemoryStream(bytes);
            ImageUploadParams a           = new ImageUploadParams
            {
                File     = new FileDescription(Guid.NewGuid().ToString(), inputStream),
                PublicId = "4"
            };
            ImageUploadResult uploadResult = _cloudinary.Upload(a);

            return(uploadResult);
        }
コード例 #31
0
        public ServiceResult <bool> Login(FiiiEXLoginIM im)
        {
            var  codeEntity = QRCode.Deserialize(im.Code);
            bool result     = false;

            if (codeEntity.SystemPlatform == SystemPlatform.FiiiEX)
            {
                if (codeEntity.QRCodeBusiness == QRCodeBusiness.FiiiPayLogin)
                {
                    result = new FiiiEXLoginComponent().FiiiPayLogin(im.Code.Replace('-', ':'), this.GetUser());
                }
            }
            if (!result)
            {
                throw new Framework.Exceptions.CommonException(ReasonCode.INVALID_QRCODE, Framework.Properties.R.无效二维码);
            }
            return(new ServiceResult <bool>
            {
                Data = result
            });
        }
コード例 #32
0
        private string GetQRCode(string code)
        {
            string str = "";
            QRCodeGenerator.ECCLevel eccLevel = (QRCodeGenerator.ECCLevel)3;
            using (QRCodeGenerator qrGenerator = new QRCodeGenerator())
            {
                using (QRCodeData qrCodeData = qrGenerator.CreateQrCode(code, eccLevel))
                {
                    using (QRCode qrCode = new QRCode(qrCodeData))
                    {

                       Bitmap img = qrCode.GetGraphic(20, Color.Black, Color.White,
                            null, 15);
                        str = ImageToBase64((Image)img, System.Drawing.Imaging.ImageFormat.Png);
                        str = "data:image/jpeg;base64," + str;
                    }
                }
            }

            return str;
        }
コード例 #33
0
        private async void UpdateUi()
        {
            var address = await this.gucciInterface.AddressAsync();

            // Update wallet address
            this.addressBox.Text = address;

            // Update payment ID
            this.paymentIdBox.Text = paymentId;

            // Update QR code
            var generator = new QRCodeGenerator();
            var data      = generator.CreateQrCode(
                $"guccicoin:{address}?amount=10&id={this.paymentId}",
                QRCodeGenerator.ECCLevel.Q);
            var qr          = new QRCode(data);
            var bitmap      = qr.GetGraphic(5);
            var bitmapImage = BitmapConverter.ToBitmapImage(bitmap);

            this.qrImage.Source = bitmapImage;
        }
コード例 #34
0
ファイル: QRCoderHelper.cs プロジェクト: Poepon/DC.Libraries
 /// <summary>
 /// 渲染二维码
 /// </summary>
 /// <param name="str"></param>
 /// <returns></returns>
 public static Bitmap RenderQrCode(string str, string logoPath = null, bool drawQuietZones = true)
 {
     using (QRCodeGenerator qrGenerator = new QRCodeGenerator())
     {
         using (QRCodeData qrCodeData = qrGenerator.CreateQrCode(str, QRCodeGenerator.ECCLevel.Q))
         {
             using (QRCode qrCode = new QRCode(qrCodeData))
             {
                 if (!string.IsNullOrEmpty(logoPath) && File.Exists(logoPath))
                 {
                     return(qrCode.GetGraphic(20, Color.Black, Color.White, (Bitmap)Image.FromFile(logoPath),
                                              drawQuietZones: drawQuietZones));
                 }
                 else
                 {
                     return(qrCode.GetGraphic(20, Color.Black, Color.White, drawQuietZones));
                 }
             }
         }
     }
 }
コード例 #35
0
        static void Main(string[] args)
        {
            // Create and activate QRCode instance 
            using (QRCode barcode = new QRCode("demo", "demo"))
            {
                // Set the character encoding to UTF8
                barcode.CharacterEncoding = Encoding.UTF8;

                // Set Unicode barcode value
                barcode.Value = "日本";

                // Show barcode caption (optional)
                barcode.DrawCaption = true;

                // Save barcode image to file
                barcode.SaveImage("result.png");
            }

            // Open the image in default image viewer (for the demo purpose)
            Process.Start("result.png");
        }
コード例 #36
0
        /// <summary>
        /// 二维码画布
        /// </summary>
        /// <param name="url">链接地址</param>
        /// <param name="pixel"像素大小></param>
        /// <param name="img">是否带logo</param>
        /// <returns></returns>
        public static Bitmap GetQrCode(string url, int pixel, string img = "")
        {
            using (QRCodeGenerator generator = new QRCodeGenerator())
            {
                QRCodeData codeData = generator.CreateQrCode(url, QRCodeGenerator.ECCLevel.M, true);
                using (QRCode qrcode = new QRCode(codeData))
                {
                    Bitmap qrImage;
                    if (string.IsNullOrEmpty(img))
                    {
                        qrImage = qrcode.GetGraphic(pixel);
                    }
                    else
                    {
                        qrImage = qrcode.GetGraphic(pixel, Color.Black, Color.White, new Bitmap(img), 15, 6, true);
                    }

                    return(qrImage);
                }
            }
        }
コード例 #37
0
ファイル: QR.cs プロジェクト: tonovarela/goepowerWS
        // Genera QR con iTextSharp
        public void generate()
        {
            QRCodeGenerator qrGenerator = new QRCodeGenerator();
            QRCodeData      qrCodeData  = qrGenerator.CreateQrCode("Este es un texto", QRCodeGenerator.ECCLevel.Q);
            QRCode          qrCode      = new QRCode(qrCodeData);
            //Image i = new Image();
            //Bitmap qrCodeImage = qrCode.GetGraphic(20);
            string v = string.Empty;

            using (Bitmap bitMap = qrCode.GetGraphic(20))
            {
                using (MemoryStream ms = new MemoryStream())
                {
                    bitMap.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
                    byte[] byteImage = ms.ToArray();
                    v = "data:image/png;base64," + Convert.ToBase64String(byteImage);
                    Console.WriteLine(v);
                }
                // plBarCode.Controls.Add(imgBarCode);
            }
        }
コード例 #38
0
 private void QrId()
 {
     try
     {
         ////////////////////////////////////////////////////////////////////////////////////////////
         TbQRID.Text = TbPASSPORTID.Text + DdlNATIONALITY.SelectedValue.ToUpper().Substring(0, 4);
         QRCodeGenerator qrGenerator = new QRCodeGenerator();
         QRCodeData      qrCodeData  = qrGenerator.CreateQrCode(TbQRID.Text, QRCodeGenerator.ECCLevel.Q);
         QRCode          qrCode      = new QRCode(qrCodeData);
         Bitmap          qrCodeImage = qrCode.GetGraphic(20);
         string          strPath     = Server.MapPath(@"~\hajj\QrImg\" + TbQRID.Text + ".jpg");
         //Bitmap resized = new Bitmap(qrCodeImage, new Size(100, 100));
         qrCodeImage.Save(strPath, ImageFormat.Jpeg);
         ImgQRID.ImageUrl = @"~\hajj\QrImg\" + TbQRID.Text + ".jpg";
         /////////////////////////////////////////////////////////////////////////////////////////////
     }
     catch (Exception ex)
     {
         Response.Write("<script>alert('" + "حدث خطأ : " + ex.Message + "')</script>");
     }
 }
コード例 #39
0
        /// <summary>
        /// 创建二维码图片
        /// </summary>
        /// <param name="message">消息内容</param>
        /// <param name="eccLevel">容错级别</param>
        /// <param name="pixelsPerModule">平均像素点</param>
        /// <param name="darkColorHtmlHex">暗色值 默认值 #000000</param>
        /// <param name="lightColorHtmlHex">亮色值 默认值 #FFFFFF</param>
        /// <param name="iconFileFullPath">二维码中间logo文件全路径</param>
        /// <param name="iconSizePercent">二维码中间logo显示尺寸</param>
        /// <param name="iconBorderWidth">二维码中间logo边框</param>
        /// <param name="drawQuietZones"></param>
        /// <returns></returns>
        public static Bitmap CreateQrCodeBitmap(string message, QRCodeGenerator.ECCLevel eccLevel = QRCodeGenerator.ECCLevel.L, int pixelsPerModule = 20, string darkColorHtmlHex = "#000000", string lightColorHtmlHex = "#FFFFFF", string iconFileFullPath = null, int iconSizePercent = 15, int iconBorderWidth = 6, bool drawQuietZones = true)
        {
            Bitmap qrCodeBitmap;

            var darkColor  = ColorTranslator.FromHtml(darkColorHtmlHex);
            var lightColor = ColorTranslator.FromHtml(lightColorHtmlHex);
            var iconBitmap = new Bitmap(iconFileFullPath);

            using (var qrGenerator = new QRCodeGenerator())
            {
                using (var qrCodeData = qrGenerator.CreateQrCode(message, eccLevel))
                {
                    using (var qrCode = new QRCode(qrCodeData))
                    {
                        qrCodeBitmap = qrCode.GetGraphic(pixelsPerModule, darkColor, lightColor, iconBitmap, iconSizePercent, iconBorderWidth, drawQuietZones);
                    }
                }
            }

            return(qrCodeBitmap);
        }
コード例 #40
0
 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' ? false : true));
     for (int x = size - 1; x >= 0; x = x - 2)
     {
         if (x == 7 || x == 6)
             x = 5;
         for (int yMod = 1; yMod <= size; yMod++)
         {
             int y = 0;
             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;
     }
 }
コード例 #41
0
ファイル: ShowQR.cs プロジェクト: SERVCUBED/Scriptmonkey
        private void Draw()
        {
            int typeNumber;
            if (_text.Length < 26)
                typeNumber = 2;
            else if (_text.Length < 72)
                typeNumber = 5;
            else if (_text.Length < 125)
                typeNumber = 7;
            else if (_text.Length < 203)
                typeNumber = 10;
            else if (_text.Length < 298)
                typeNumber = 12;
            else if (_text.Length < 407)
                typeNumber = 15;
            else if (_text.Length < 534)
                typeNumber = 17;
            else if (_text.Length < 669)
                typeNumber = 20;
            else
            {
                Close();
                return;
            }

            QRCode qr;
            try
            {
                qr = new QRCode(typeNumber, QRErrorCorrectLevel.M);
                qr.AddData(_text);
                qr.Make();
            }
            catch (Exception)
            {
                Close();
                return;
            }

            var c = qr.GetModuleCount();
            var b = new Bitmap(c, c);

            for (var row = 0; row < c; row++)
            {
                for (var col = 0; col < c; col++)
                {
                    var isDark = qr.IsDark(row, col);
                    b.SetPixel(row, col, isDark ? _darkColour : _backColour);
                }
            }

            var newImage = new Bitmap(_size, _size, PixelFormat.Format24bppRgb);
            var g = Graphics.FromImage(newImage);
            g.InterpolationMode = InterpolationMode.NearestNeighbor;
            g.CompositingQuality = CompositingQuality.HighQuality;
            g.SmoothingMode = SmoothingMode.None;
            if (_border)
            {
                g.DrawImage(b, _borderWidth, _borderWidth, _size - _borderWidth * 2, _size - _borderWidth * 2);
                RectangleF[] r = {new RectangleF(0, 0, _size, _borderWidth), // Top
                    new RectangleF(0, 0, _borderWidth, _size), // Left
                    new RectangleF(_size - _borderWidth, 0, _borderWidth, _size), // Right
                    new RectangleF(0, _size - _borderWidth, _size, _borderWidth)}; // Bottom
                g.DrawRectangles(new Pen(_borderColour, _borderWidth), r);
            }
            else
                g.DrawImage(b, 0, 0, _size, _size);
            panel1.BackgroundImage = newImage;
        }
コード例 #42
0
ファイル: QRCoder.cs プロジェクト: fqybzhangji/QRCoder
        private void renderQRCode()
        {
            string level = comboBox1.SelectedItem.ToString();
            QRCodeGenerator.ECCLevel eccLevel = (QRCodeGenerator.ECCLevel)(level == "L" ? 0 : level == "M" ? 1 : level == "Q" ? 2 : 3);
            QRCodeGenerator qrGenerator = new QRCodeGenerator();
            QRCodeData qrCodeData = qrGenerator.CreateQrCode(textBoxQRCode.Text, eccLevel);
            QRCode qrCode = new QRCode(qrCodeData);

            pictureBoxQRCode.BackgroundImage = qrCode.GetGraphic(20, Color.Black, Color.White, getIconBitmap());

            //Image card = qrCode.GetGraphic(20, Color.Black, Color.White, getIconBitmap());

            //using (FileStream fs = new FileStream(@"D:\图片\58.png", FileMode.OpenOrCreate, FileAccess.Write))
            //{
            //    card.Save(fs, System.Drawing.Imaging.ImageFormat.Jpeg);
            //    fs.Close();
            //}
        }
コード例 #43
0
        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.Where(x => x.Version == version && x.ErrorCorrectionLevel.Equals(eccLevel)).Single();
            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
            List<CodewordBlock> codeWordWithECC = new List<CodewordBlock>();
            for (int 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 (int 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
            StringBuilder interleavedWordsSb = new StringBuilder();
            for (int i = 0; i < Math.Max(eccInfo.CodewordsInGroup1, eccInfo.CodewordsInGroup2); i++)
            {
                foreach (var codeBlock in codeWordWithECC)
                    if (codeBlock.CodeWords.Count > i)
                        interleavedWordsSb.Append(codeBlock.CodeWords[i]);
            }

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

            //Place interleaved data on module matrix
            QRCode qr = new QRCode(version);
            List<Rectangle> 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;
        }
コード例 #44
0
ファイル: UserController.cs プロジェクト: Teknikode/Teknik
        public ActionResult GenerateAuthQrCode(string key)
        {
            var ProvisionUrl = string.Format("otpauth://totp/{0}:{1}?secret={2}", Config.Title, User.Identity.Name, key);

            QRCodeGenerator qrGenerator = new QRCodeGenerator();
            QRCodeData qrCodeData = qrGenerator.CreateQrCode(ProvisionUrl, QRCodeGenerator.ECCLevel.Q);
            QRCode qrCode = new QRCode(qrCodeData);
            Bitmap qrCodeImage = qrCode.GetGraphic(20);
            return File(Helpers.Utility.ImageToByte(qrCodeImage), "image/png");
        }
コード例 #45
0
        // Note that the input matrix uses 0 == white, 1 == black, while the output matrix uses
        // 0 == black, 255 == white (i.e. an 8 bit greyscale bitmap).
        private static ByteMatrix renderResult(QRCode code, int width, int height)
        {
            ByteMatrix input = code.Matrix;
            int inputWidth = input.Width;
            int inputHeight = input.Height;
            int qrWidth = inputWidth + (QUIET_ZONE_SIZE << 1);
            int qrHeight = inputHeight + (QUIET_ZONE_SIZE << 1);
            int outputWidth = System.Math.Max(width, qrWidth);
            int outputHeight = System.Math.Max(height, qrHeight);

            int multiple = System.Math.Min(outputWidth / qrWidth, outputHeight / qrHeight);
            // Padding includes both the quiet zone and the extra white pixels to accommodate the requested
            // dimensions. For example, if input is 25x25 the QR will be 33x33 including the quiet zone.
            // If the requested size is 200x160, the multiple will be 4, for a QR of 132x132. These will
            // handle all the padding from 100x100 (the actual QR) up to 200x160.
            int leftPadding = (outputWidth - (inputWidth * multiple)) / 2;
            int topPadding = (outputHeight - (inputHeight * multiple)) / 2;

            ByteMatrix output = new ByteMatrix(outputWidth, outputHeight);
            sbyte[][] outputArray = output.Array;

            // We could be tricky and use the first row in each set of multiple as the temporary storage,
            // instead of allocating this separate array.
            sbyte[] row = new sbyte[outputWidth];

            // 1. Write the white lines at the top
            for (int y = 0; y < topPadding; y++)
            {
                setRowColor(outputArray[y], (sbyte) SupportClass.Identity(255));
            }

            // 2. Expand the QR image to the multiple
            sbyte[][] inputArray = input.Array;
            for (int y = 0; y < inputHeight; y++)
            {
                // a. Write the white pixels at the left of each row
                for (int x = 0; x < leftPadding; x++)
                {
                    row[x] = (sbyte) SupportClass.Identity(255);
                }

                // b. Write the contents of this row of the barcode
                int offset = leftPadding;
                for (int x = 0; x < inputWidth; x++)
                {
                    // Redivivus.in Java to c# Porting update - Type cased sbyte
                    // 30/01/2010
                    // sbyte value_Renamed = (inputArray[y][x] == 1)?0:(sbyte) SupportClass.Identity(255);
                    sbyte value_Renamed = (sbyte)((inputArray[y][x] == 1) ? 0 : SupportClass.Identity(255));
                    for (int z = 0; z < multiple; z++)
                    {
                        row[offset + z] = value_Renamed;
                    }
                    offset += multiple;
                }

                // c. Write the white pixels at the right of each row
                offset = leftPadding + (inputWidth * multiple);
                for (int x = offset; x < outputWidth; x++)
                {
                    row[x] = (sbyte) SupportClass.Identity(255);
                }

                // d. Write the completed row multiple times
                offset = topPadding + (y * multiple);
                for (int z = 0; z < multiple; z++)
                {
                    Array.Copy(row, 0, outputArray[offset + z], 0, outputWidth);
                }
            }

            // 3. Write the white lines at the bottom
            int offset2 = topPadding + (inputHeight * multiple);
            for (int y = offset2; y < outputHeight; y++)
            {
                setRowColor(outputArray[y], (sbyte) SupportClass.Identity(255));
            }

            return output;
        }
コード例 #46
0
            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 (int i = 0; i < 6; i = i + 2)
                {
                    for (int x = 0; x < 7; x++)
                    {
                        for (int 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));
                }
            }
コード例 #47
0
 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));
 }
コード例 #48
0
ファイル: QRCodeHtmlBuilder.cs プロジェクト: wanaxe/Study
 /// <summary>
 /// Initializes a new instance of the <see cref="QRCodeHtmlBuilder" /> class.
 /// </summary>
 /// <param name="component">The QRCode component.</param>
 public QRCodeHtmlBuilder(QRCode component)
 {
     qrCode = component;
 }
コード例 #49
0
            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")
                    {
                        QRCode qrTemp = new QRCode(version);
                        for (int y = 0; y < size; y++)
                        {
                            for (int x = 0; x < size; x++)
                            {
                                qrTemp.ModuleMatrix[y][x] = qrCode.ModuleMatrix[y][x];
                            }

                        }

                        for (int x = 0; x < size; x++)
                        {
                            for (int 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)
                        {
                            patternName = pattern.Name;
                            patternScore = score;
                        }

                    }
                }
                var patterMethod = typeof(MaskPattern).GetMethods().Where(x => x.Name == patternName).First();
                for (int x = 0; x < size; x++)
                {
                    for (int 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;
            }
コード例 #50
0
            public static void PlaceVersion(ref QRCode qrCode, string versionStr)
            {
                var size = qrCode.ModuleMatrix.Count;
                var vStr = new string(versionStr.Reverse().ToArray());

                for (int x = 0; x < 6; x++)
                {
                    for (int y = 0; y < 3; y++)
                    {
                        qrCode.ModuleMatrix[y + size - 11][x] = vStr[x * 3 + y] == '1' ? true : false;
                        qrCode.ModuleMatrix[x][y + size - 11] = vStr[x * 3 + y] == '1' ? true : false;
                    }
                }
            }
コード例 #51
0
ファイル: Program.cs プロジェクト: yurikus/QRCoder
 private static void GenerateQRCode(string payloadString, QRCodeGenerator.ECCLevel eccLevel, string outputFileName, ImageFormat imgFormat)
 {
     using (var generator = new QRCodeGenerator())
     {
         using (var data = generator.CreateQrCode(payloadString, eccLevel))
         {
             using (var code = new QRCode(data))
             {
                 using (var bitmap = code.GetGraphic(20))
                 {
                     bitmap.Save(outputFileName, imgFormat);
                 }
             }
         }
     }
 }
コード例 #52
0
            public static void PlaceAlignmentPatterns(ref QRCode qrCode, List<Point> alignmentPatternLocations, ref List<Rectangle> blockedModules)
            {
                foreach (var loc in alignmentPatternLocations)
                {
                    var alignmentPatternRect = new Rectangle(loc.X, loc.Y, 5, 5);
                    var blocked = false;
                    foreach (var blockedRect in blockedModules)
                    {
                        if (Intersects(alignmentPatternRect, blockedRect))
                        {
                            blocked = true;
                            break;
                        }
                    }
                    if (blocked)
                        continue;

                    for (int x = 0; x < 5; x++)
                    {
                        for (int 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));
                }
            }
コード例 #53
0
ファイル: Encoder.cs プロジェクト: marinehero/ThinkAway.net
		/// <summary>  Encode "bytes" with the error correction level "ecLevel". The encoding mode will be chosen
		/// internally by chooseMode(). On success, store the result in "qrCode".
		/// 
		/// We recommend you to use QRCode.EC_LEVEL_L (the lowest level) for
		/// "getECLevel" since our primary use is to show QR code on desktop screens. We don't need very
		/// strong error correction for this purpose.
		/// 
		/// Note that there is no way to encode bytes in MODE_KANJI. We might want to add EncodeWithMode()
		/// with which clients can specify the encoding mode. For now, we don't need the functionality.
		/// </summary>
		public static void  Encode(System.String content, ErrorCorrectionLevel ecLevel, QRCode qrCode)
		{
			Encode(content, ecLevel, null, qrCode);
		}
コード例 #54
0
 public static void AddQuietZone(ref QRCode qrCode)
 {
     bool[] quietLine = new bool[qrCode.ModuleMatrix.Count + 8];
     for (int i = 0; i < quietLine.Length; i++)
         quietLine[i] = false;
     for (int i = 0; i < 4; i++)
         qrCode.ModuleMatrix.Insert(0, new BitArray(quietLine));
     for (int i = 0; i < 4; i++)
         qrCode.ModuleMatrix.Add(new BitArray(quietLine));
     for (int i = 4; i < qrCode.ModuleMatrix.Count - 4; i++)
     {
         bool[] quietPart = new bool[4] { false, false, false, false };
         List<bool> tmpLine = new List<bool>(quietPart);
         foreach (bool module in qrCode.ModuleMatrix[i])
             tmpLine.Add(module);
         tmpLine.AddRange(quietPart);
         qrCode.ModuleMatrix[i] = new BitArray(tmpLine.ToArray());
     }
 }
コード例 #55
0
ファイル: Form1.cs プロジェクト: yurikus/QRCoder
        private void RenderQrCode()
        {
            string level = comboBoxECC.SelectedItem.ToString();
            QRCodeGenerator.ECCLevel eccLevel = (QRCodeGenerator.ECCLevel)(level == "L" ? 0 : level == "M" ? 1 : level == "Q" ? 2 : 3);
            using (QRCodeGenerator qrGenerator = new QRCodeGenerator())
            {
                using (QRCodeData qrCodeData = qrGenerator.CreateQrCode(textBoxQRCode.Text, eccLevel))
                {
                    using (QRCode qrCode = new QRCode(qrCodeData))
                    {

                        pictureBoxQRCode.BackgroundImage = qrCode.GetGraphic(20, Color.Black, Color.White,
                            GetIconBitmap(), (int) iconSize.Value);

                         this.pictureBoxQRCode.Size = new System.Drawing.Size(pictureBoxQRCode.Width, pictureBoxQRCode.Height);
                        //Set the SizeMode to center the image.
                        this.pictureBoxQRCode.SizeMode = PictureBoxSizeMode.CenterImage;

                        pictureBoxQRCode.SizeMode = PictureBoxSizeMode.StretchImage;
                    }
                }
            }
        }
コード例 #56
0
 public static void PlaceTimingPatterns(ref QRCode qrCode, ref List<Rectangle> blockedModules)
 {
     var size = qrCode.ModuleMatrix.Count;
     for (int i = 8; i < size - 8; i++)
     {
         if (i % 2 == 0)
         {
             qrCode.ModuleMatrix[6][i] = true;
             qrCode.ModuleMatrix[i][6] = true;
         }
     }
     blockedModules.AddRange(new Rectangle[]{
         new Rectangle(6, 8, 1, size-16),
         new Rectangle(8, 6, size-16, 1)
     });
 }
コード例 #57
0
ファイル: Encoder.cs プロジェクト: marinehero/ThinkAway.net
		/// <summary> Initialize "qrCode" according to "numInputBytes", "ecLevel", and "mode". On success,
		/// modify "qrCode".
		/// </summary>
		private static void  InitQrCode(int numInputBytes, ErrorCorrectionLevel ecLevel, Mode mode, QRCode qrCode)
		{
			qrCode.ECLevel = ecLevel;
			qrCode.Mode = mode;
			
			// In the following comments, we use numbers of Version 7-H.
			for (int versionNum = 1; versionNum <= 40; versionNum++)
			{
				Version version = Version.getVersionForNumber(versionNum);
				// numBytes = 196
				int numBytes = version.TotalCodewords;
				// getNumECBytes = 130
				Version.ECBlocks ecBlocks = version.getECBlocksForLevel(ecLevel);
				int numEcBytes = ecBlocks.TotalECCodewords;
				// getNumRSBlocks = 5
				int numRSBlocks = ecBlocks.NumBlocks;
				// getNumDataBytes = 196 - 130 = 66
				int numDataBytes = numBytes - numEcBytes;
				// We want to choose the smallest version which can contain data of "numInputBytes" + some
				// extra bits for the header (mode info and length info). The header can be three bytes
				// (precisely 4 + 16 bits) at most. Hence we do +3 here.
				if (numDataBytes >= numInputBytes + 3)
				{
					// Yay, we found the proper rs block info!
					qrCode.Version = versionNum;
					qrCode.NumTotalBytes = numBytes;
					qrCode.NumDataBytes = numDataBytes;
					qrCode.NumRSBlocks = numRSBlocks;
					// getNumECBytes = 196 - 66 = 130
					qrCode.NumECBytes = numEcBytes;
					// matrix width = 21 + 6 * 4 = 45
					qrCode.MatrixWidth = version.DimensionForVersion;
					return ;
				}
			}
			throw new WriterException("Cannot find proper rs block info (input data too big?)");
		}
コード例 #58
0
                public static int Score(ref QRCode qrCode)
                {
                    var score = 0;
                    var size = qrCode.ModuleMatrix.Count;

                    //Penalty 1
                    for (int y = 0; y < size; y++)
                    {
                        var modInRow = 0;
                        var modInColumn = 0;
                        var lastValRow = qrCode.ModuleMatrix[y][0];
                        var lastValColumn = qrCode.ModuleMatrix[0][y];
                        for (int 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 (int y = 0; y < size - 1; y++)
                    {
                        for (int 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 (int y = 0; y < size; y++)
                    {
                        for (int 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 = 0;
                    foreach (var row in qrCode.ModuleMatrix)
                        foreach (bool bit in row)
                            if (bit)
                                blackModules++;

                    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;
                }
コード例 #59
0
ファイル: Program.cs プロジェクト: ejperez/qrcodemakerfromcsv
        static void Main(string[] args)
        {
            if (args.Length == 0)
            {
                Console.WriteLine("No source file location parameter provided.");
            }
            else
            {
                try
                {
                    string sourceFile = args[0];
                    Console.WriteLine("Source file: " + args[0]);

                    TextFieldParser parser = new TextFieldParser(sourceFile);
                    parser.HasFieldsEnclosedInQuotes = true;
                    parser.SetDelimiters(",");

                    // Get headers
                    string[] headerArray = parser.ReadFields();

                    // Get contents
                    List<string[]> rowList = new List<string[]>();
                    while (!parser.EndOfData)
                    {
                        rowList.Add(parser.ReadFields());
                    }

                    Parallel.ForEach(rowList, (row) =>
                    {
                        try
                        {
                            string line = "";

                            for (int i = 0; i < row.Length; i++)
                            {
                                line += String.Format("{0}: {1}\n", headerArray[i], row[i]).ToUpper();
                            }

                            Console.Write(line);

                            // Create identifier
                            string identifier = String.Format("{0}, {1} {2}", row[2], row[0], row[1]).ToUpper().Replace("N/A", String.Empty);

                            // Generate qr code image
                            QRCodeGenerator qrGenerator = new QRCodeGenerator();
                            QRCodeData qrCodeData = qrGenerator.CreateQrCode(line, QRCodeGenerator.ECCLevel.Q);
                            QRCode qrCode = new QRCode(qrCodeData);
                            Bitmap qrCodeImage = qrCode.GetGraphic(20);

                            Directory.CreateDirectory("output");

                            // Save image to file
                            qrCodeImage.Save(String.Format("output\\{0}.jpg", identifier));
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine(ex.Message);
                        }      
                    });
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }                           
            }

            Console.Write("Press any key to continue...");
            Console.ReadKey();
        }
コード例 #60
0
 public static void PlaceFormat(ref QRCode qrCode, string formatStr)
 {
     var size = qrCode.ModuleMatrix.Count;
     var fStr = new string(formatStr.Reverse().ToArray());
     int[,] modules = new int[15, 4] { { 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 (int 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' ? true : false;
         qrCode.ModuleMatrix[p2.Y][p2.X] = fStr[i] == '1' ? true : false;
     }
 }