Ejemplo n.º 1
0
        public void testQRCodeWriter()
        {
            // The QR should be multiplied up to fit, with extra padding if necessary
            int          bigEnough = 256;
            QRCodeWriter writer    = new QRCodeWriter();
            BitMatrix    matrix    = writer.encode("http://www.google.com/", BarcodeFormat.QR_CODE, bigEnough,
                                                   bigEnough, null);

            Assert.NotNull(matrix);
            Assert.AreEqual(bigEnough, matrix.Width);
            Assert.AreEqual(bigEnough, matrix.Height);

            // The QR will not fit in this size, so the matrix should come back bigger
            int tooSmall = 20;

            matrix = writer.encode("http://www.google.com/", BarcodeFormat.QR_CODE, tooSmall,
                                   tooSmall, null);
            Assert.NotNull(matrix);
            Assert.IsTrue(tooSmall < matrix.Width);
            Assert.IsTrue(tooSmall < matrix.Height);

            // We should also be able to handle non-square requests by padding them
            int strangeWidth  = 500;
            int strangeHeight = 100;

            matrix = writer.encode("http://www.google.com/", BarcodeFormat.QR_CODE, strangeWidth,
                                   strangeHeight, null);
            Assert.NotNull(matrix);
            Assert.AreEqual(strangeWidth, matrix.Width);
            Assert.AreEqual(strangeHeight, matrix.Height);
        }
Ejemplo n.º 2
0
        // Use this for initialization
        void Start()
        {
            QRCodeWriter writer = new QRCodeWriter();

            GameObject server = GameObject.Find("Server");
            int        port   = server.GetComponent <ServerLoader>().Port;

            size = ((int)(sizePercentage * Screen.height));
            BitMatrix qrcode = writer.encode("BuildingBlocksServer=" + Network.player.ipAddress + ":" + port, BarcodeFormat.QR_CODE, size, size);

            GUITexture GUItexture = GetComponent <GUITexture>();

            GUItexture.pixelInset = new Rect(-size / 2, 0, size, size);

            var texture = new Texture2D(size, size);

            for (int w = 0; w < size; w++)
            {
                for (int h = 0; h < size; h++)
                {
                    texture.SetPixel(h, w, getColorFromBinary(qrcode[w, h]));
                }
            }
            texture.Apply();

            GameObject qrMarkerField = GameObject.FindGameObjectWithTag("qrmarkertag");

            qrMarkerField.guiTexture.texture = texture;
        }
Ejemplo n.º 3
0
        private void QR_Load(object sender, EventArgs e)
        {
            QRCodeWriter qrEncode = new QRCodeWriter();                                            //создание QR кода
            Dictionary <EncodeHintType, object> hints = new Dictionary <EncodeHintType, object>(); //для колекции поведений

            hints.Add(EncodeHintType.CHARACTER_SET, "utf-8");                                      //добавление в коллекцию кодировки utf-8
            BitMatrix qrMatrix = qrEncode.encode(                                                  //создание матрицы QR
                Teacher.idtests.ToString(),                                                        //кодируемая строка
                BarcodeFormat.QR_CODE,                                                             //формат кода, т.к. используется QRCodeWriter применяется QR_CODE
                300,                                                                               //ширина
                300,                                                                               //высота
                hints);                                                                            //применение колекции поведений
            BarcodeWriter qrWrite = new BarcodeWriter();                                           //класс для кодирования QR в растровом файле
            Bitmap        qrImage = qrWrite.Write(qrMatrix);                                       //создание изображения

            pictureBox1.Image = qrImage;
            SaveFileDialog save = new SaveFileDialog();

            save.CreatePrompt    = true;
            save.OverwritePrompt = true;
            save.FileName        = "QR";
            save.Filter          = "PNG|*.png|JPEG|*.jpg|BMP|*.bmp|GIF|*.gif";
            if (save.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                pictureBox1.Image.Save(save.FileName);
                save.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
            }
        }
Ejemplo n.º 4
0
        public static byte[] CreateQr(string content)
        {
            var writer = new QRCodeWriter();
            var matrix = writer.encode(content, BarcodeFormat.QR_CODE, 200, 200);

            int width  = matrix.Width;
            int height = matrix.Height;

            Image img = new Image(width, height);

            using (PixelAccessor <Color, uint> pixels = img.Lock())
            {
                for (int y = 0; y < height; y++)
                {
                    for (int x = 0; x < width; x++)
                    {
                        pixels[y, x] = matrix[y, x] ? Color.Black : Color.White;
                    }
                }
            }

            using (var output = new MemoryStream())
            {
                img.Save(output);
                return(output.ToArray());
            }
        }
Ejemplo n.º 5
0
        public static void GenerateQRCode(string URL, String TargetPath)
        {
            QRCodeWriter writer = new QRCodeWriter();
            Hashtable    hints  = new Hashtable();

            hints.Add(EncodeHintType.ERROR_CORRECTION, com.google.zxing.qrcode.decoder.ErrorCorrectionLevel.M);
            hints.Add("Version", "7");
            ByteMatrix byteIMGNew = writer.encode(URL, BarcodeFormat.QR_CODE, 350, 350, hints);

            sbyte[][] imgNew = byteIMGNew.Array;
            Bitmap    bmp1   = new Bitmap(byteIMGNew.Width, byteIMGNew.Height);
            Graphics  g1     = Graphics.FromImage(bmp1);

            g1.Clear(System.Drawing.Color.White);
            for (int i = 0; i <= imgNew.Length - 1; i++)
            {
                for (int j = 0; j <= imgNew[i].Length - 1; j++)
                {
                    if (imgNew[j][i] == 0)
                    {
                        g1.FillRectangle(System.Drawing.Brushes.Black, i, j, 1, 1);
                    }
                    else
                    {
                        g1.FillRectangle(System.Drawing.Brushes.White, i, j, 1, 1);
                    }
                }
            }
            bmp1.Save(TargetPath, System.Drawing.Imaging.ImageFormat.Jpeg);
        }
Ejemplo n.º 6
0
 private void DoBinToQr(string filename)
 {
     try
     {
         var          byteArray = File.ReadAllBytes(filename);
         var          writer    = new QRCodeWriter();
         const string encoding  = "ISO-8859-1";
         var          str       = Encoding.GetEncoding(encoding).GetString(byteArray);
         var          hints     = new Hashtable {
             { EncodeHintType.CHARACTER_SET, encoding }
         };
         var matrix = writer.encode(str, BarcodeFormat.QR_CODE, 100, 100, hints);
         var img    = new Bitmap(200, 200);
         var g      = Graphics.FromImage(img);
         g.Clear(Color.White);
         for (var y = 0; y < matrix.Height; ++y)
         {
             for (var x = 0; x < matrix.Width; ++x)
             {
                 if (matrix.get_Renamed(x, y) != -1)
                 {
                     g.FillRectangle(Brushes.Black, x * 2, y * 2, 2, 2);
                 }
             }
         }
         ImageBox.ShowDialog(img);
     }
     catch (Exception ex)
     {
         MessageBox.Show(@"Error Loading:" + Environment.NewLine + ex.Message);
     }
 }
Ejemplo n.º 7
0
 private void DoTextToQr(string text)
 {
     try
     {
         var          writer   = new QRCodeWriter();
         const string encoding = "UTF-8";// "ISO-8859-1";
         var          hints    = new Hashtable {
             { EncodeHintType.CHARACTER_SET, encoding }, { EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L }
         };
         var matrix = writer.encode(text, BarcodeFormat.QR_CODE, 100, 100, hints);
         var img    = new Bitmap(200, 200);
         var g      = Graphics.FromImage(img);
         g.Clear(Color.White);
         for (var y = 0; y < matrix.Height; ++y)
         {
             for (var x = 0; x < matrix.Width; ++x)
             {
                 if (matrix.get_Renamed(x, y) != -1)
                 {
                     g.FillRectangle(Brushes.Black, x * 2, y * 2, 2, 2);
                 }
             }
         }
         ImageBox.ShowDialog(img);
     }
     catch (Exception ex)
     {
         MessageBox.Show(@"Error Loading:" + Environment.NewLine + ex.Message);
     }
 }
Ejemplo n.º 8
0
        private Bitmap PathtoBitmap(string inputURL)
        {
            /*Create a codewriter instance*/
            QRCodeWriter qr = new QRCodeWriter();

            /*Encodes the given string into a bitmatrix with the format defined by Zxing: "QR_CODE"*/
            var matrix = qr.encode(inputURL, ZXing.BarcodeFormat.QR_CODE, 200, 200);

            /*Gets the dimensions of the matrix*/
            int height = matrix.Height;
            int width  = matrix.Width;

            /*Creates a new bitmap with the ssame dimensions as the matrix*/
            Bitmap bmp = new Bitmap(width, height);

            /*Fill out the new BMP with the details of the matrix*/
            for (int x = 0; x < width; x++)
            {
                for (int y = 0; y < height; y++)
                {
                    bmp.SetPixel(x, y, matrix[x, y] ? Color.Black : Color.White);
                }
            }

            return(bmp);
        }
Ejemplo n.º 9
0
        public string SaveQrCode(string text)
        {
            var qrCode = new QRCodeWriter();
            var bits   = qrCode.encode(text, BarcodeFormat.QR_CODE, 300, 300);
            var image  = new Image <Rgba32>(bits.Width, bits.Height);

            for (int ii = 0; ii < bits.Width; ii++)
            {
                for (int kk = 0; kk < bits.Height; kk++)
                {
                    if (bits[ii, kk])
                    {
                        image[ii, kk] = new Rgba32(0, 0, 0);
                    }
                    else
                    {
                        image[ii, kk] = new Rgba32(255, 255, 255);
                    }
                }
            }
            var name   = DateTime.UtcNow.Ticks.ToString();
            var nameFP = env.WebRootPath + "/images/" + name + ".png";

            image.Save(nameFP);
            return(name);
        }
Ejemplo n.º 10
0
        public FileContentResult CaptchaImage(string qrcode)
        {
            var rand = new Random((int)DateTime.Now.Ticks);


            //image stream
            FileContentResult img = null;

            using (var mem = new MemoryStream())
            //using (var bmp = new Bitmap(130, 30))
            //using (var gfx = Graphics.FromImage((Image)bmp))
            {
                QRCodeWriter qr = new QRCodeWriter();

                string url = qrcode;

                var matrix = qr.encode(url, ZXing.BarcodeFormat.QR_CODE, 200, 200);

                ZXing.BarcodeWriter w = new ZXing.BarcodeWriter();

                w.Format = ZXing.BarcodeFormat.QR_CODE;

                Bitmap img1 = w.Write(matrix);



                //render as Png
                img1.Save(mem, System.Drawing.Imaging.ImageFormat.Png);
                img = this.File(mem.GetBuffer(), "image/png");
            }

            var file = File(img.FileContents, img.ContentType);

            return(File(img.FileContents, img.ContentType));
        }
Ejemplo n.º 11
0
        /// <summary>
        /// Generate a BitmapSource QRcode from a string.
        /// </summary>
        /// <param name="content">The string to encode</param>
        /// <param name="size">The width/height of the image (in pixels).</param>
        /// <returns>BitmapSource of the QR code</returns>
        public static BitmapSource GenerateQRCode(string content, int size)
        {
            //create buffered image to draw to
            WriteableBitmap writeableBitmap = new WriteableBitmap(size, size);

            if (string.IsNullOrWhiteSpace(content))
            {
                return(writeableBitmap);
            }
            //generate qr code
            QRCodeWriter writer     = new QRCodeWriter();
            ByteMatrix   byteMatrix = writer.encode(content, BarcodeFormat.QR_CODE, size, size);

            sbyte[][] array = byteMatrix.Array;
            //iterate through the matrix and draw the pixels
            int grayValue;

            for (int y = 0; y < size; y++)
            {
                for (int x = 0; x < size; x++)
                {
                    grayValue = array[y][x] & 0xff;
                    writeableBitmap.Pixels[y * size + x] = 255 << 24 | grayValue << 16 | grayValue << 8 | grayValue;
                }
            }
            writeableBitmap.Invalidate();
            return(writeableBitmap);
        }
Ejemplo n.º 12
0
        /// <summary>
        /// Encodes the given message String as QR Barcode and returns the bitmap
        /// </summary>
        /// <param name="_message">Message that should be encoded</param>
        /// <returns>Bitmap that contains the QR Barcode</returns>
        internal static Bitmap Generate(string _message)
        {
            QRCodeWriter writer = new QRCodeWriter();
            ByteMatrix   matrix = writer.encode(_message,
                                                BarcodeFormat.QR_CODE, 240, 240, null);

            sbyte[][] img = matrix.Array;
            Bitmap    bmp = new Bitmap(matrix.Width, matrix.Height);
            Graphics  g   = Graphics.FromImage(bmp);

            g.Clear(Color.White);
            for (int i = 0; i <= img.Length - 1; i++)
            {
                for (int j = 0; j <= img[i].Length - 1; j++)
                {
                    if (img[i][j] == 0)
                    {
                        g.FillRectangle(Brushes.Black, j, i, 1, 1);
                    }
                    else
                    {
                        g.FillRectangle(Brushes.White, j, i, 1, 1);
                    }
                }
            }
            return(bmp);
        }
Ejemplo n.º 13
0
        private byte[] GetBarcodeBytes(string text, BarcodeFormat format)
        {
            var       qrCodeWriter = new QRCodeWriter();
            BitMatrix bm           = qrCodeWriter.encode(text, format, 600, 600);
            int       squareLength = bm.Width;

            //HACK: we are manually creating each pixel? there must be an easier way
            SKBitmap bitmap = new SKBitmap(squareLength, squareLength);

            for (int row = 0; row < squareLength; row++)
            {
                for (int col = 0; col < squareLength; col++)
                {
                    if (bm[row, col])
                    {
                        bitmap.SetPixel(row, col, SKColors.Black);
                    }
                    else
                    {
                        bitmap.SetPixel(row, col, SKColors.White);
                    }
                }
            }

            SKData data = SKImage.FromBitmap(bitmap).Encode();

            return(data.ToArray());
        }
Ejemplo n.º 14
0
        public async static Task <Uri> ToQrDataUri(this ISdp sdp, int width, int height)
        {
            var qrCodeWriter = new QRCodeWriter();
            var bitMatrix    = qrCodeWriter.encode(sdp.ToString(), ZXing.BarcodeFormat.QR_CODE, width, height);

            using (var canvasRenderTarget = new CanvasRenderTarget(CanvasDevice.GetSharedDevice(), 500, 500, 96))
            {
                using (var drawingSession = canvasRenderTarget.CreateDrawingSession())
                {
                    for (var y = 0; y < height; y++)
                    {
                        for (var x = 0; x < width; x++)
                        {
                            drawingSession.DrawRectangle(x, y, 1, 1, bitMatrix.get(x, y) ? Color.FromArgb(0, 0, 0, 0) : Color.FromArgb(255, 255, 255, 255));
                        }
                    }
                }

                using (var inMemoryRandomAccessStream = new InMemoryRandomAccessStream())
                {
                    await canvasRenderTarget.SaveAsync(inMemoryRandomAccessStream, CanvasBitmapFileFormat.Png);

                    inMemoryRandomAccessStream.Seek(0);
                    var buffer = new byte[inMemoryRandomAccessStream.Size];
                    await inMemoryRandomAccessStream.ReadAsync(buffer.AsBuffer(), (uint)inMemoryRandomAccessStream.Size, InputStreamOptions.None);

                    return(new Uri($"data:image/png;base64,{Convert.ToBase64String(buffer)}"));
                }
            }
        }
Ejemplo n.º 15
0
        private void qrCode_Load(object sender, EventArgs e)
        {
            pictureBox1.Size     = new System.Drawing.Size(this.Width, this.Height);
            pictureBox1.Location = new Point(this.Width / 2 - pictureBox1.Width / 2, this.Height / 2 - pictureBox1.Height / 2);

            QRCodeWriter writer = new QRCodeWriter();
            Hashtable    hints  = new Hashtable();

            hints.Add(EncodeHintType.ERROR_CORRECTION, com.google.zxing.qrcode.decoder.ErrorCorrectionLevel.H);
            hints.Add("Version", "7");
            ByteMatrix byteIMGNew = writer.encode(METState.Current.ip, BarcodeFormat.QR_CODE, this.Height, this.Height, hints);

            sbyte[][] imgNew = byteIMGNew.Array;
            Bitmap    bmp1   = new Bitmap(byteIMGNew.Width, byteIMGNew.Height);
            Graphics  g1     = Graphics.FromImage(bmp1);

            g1.Clear(Color.White);
            for (int i = 0; i <= imgNew.Length - 1; i++)
            {
                for (int j = 0; j <= imgNew[i].Length - 1; j++)
                {
                    if (imgNew[j][i] == 0)
                    {
                        g1.FillRectangle(Brushes.Black, i, j, 1, 1);
                    }
                    else
                    {
                        g1.FillRectangle(Brushes.White, i, j, 1, 1);
                    }
                }
            }
            // bmp1.Save("D:\\QREncode.jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
            pictureBox1.Image = bmp1;
        }
Ejemplo n.º 16
0
        public void button1_Click(object sender, EventArgs e)
        {
            QRCodeWriter qrEncode = new QRCodeWriter();                                            //создание QR кода

            string strRUS = textBox1.Text;                                                         //строка на русском языке

            Dictionary <EncodeHintType, object> hints = new Dictionary <EncodeHintType, object>(); //для колекции поведений

            hints.Add(EncodeHintType.CHARACTER_SET, "utf-8");                                      //добавление в коллекцию кодировки utf-8
            BitMatrix qrMatrix = qrEncode.encode(                                                  //создание матрицы QR
                strRUS,                                                                            //кодируемая строка
                BarcodeFormat.QR_CODE,                                                             //формат кода, т.к. используется QRCodeWriter применяется QR_CODE
                300,                                                                               //ширина
                300,                                                                               //высота
                hints);                                                                            //применение колекции поведений

            BarcodeWriter qrWrite = new BarcodeWriter();                                           //класс для кодирования QR в растровом файле
            Bitmap        qrImage = qrWrite.Write(qrMatrix);                                       //создание изображения

            qrImage.Save("1.bmp", System.Drawing.Imaging.ImageFormat.Bmp);                         //сохранение изображения
            BarcodeReader qrDecode = new BarcodeReader();                                          //чтение QR кода
            Result        text     = qrDecode.Decode((Bitmap)Bitmap.FromFile("1.bmp"));            //декодирование растрового изображения

            pictureBox1.Image = Image.FromFile("1.bmp");                                           //вывод результата
        }
Ejemplo n.º 17
0
        private Bitmap getImagenQR(string Content)
        {
            QRCodeWriter qrWriter = new QRCodeWriter();
            BitMatrix    Matrix   = qrWriter.encode(Content, ZXing.BarcodeFormat.QR_CODE, 150, 150);

            BarcodeWriter bcWriter = new BarcodeWriter();

            return(bcWriter.Write(Matrix));
        }
        private void eventCB_SelectedIndexChanged(object sender, EventArgs e)
        {
            var            eventQRCode   = eventList[eventCB.SelectedIndex].qrCodeString;
            var            barcodeWriter = new QRCodeWriter();
            BitMatrix      bm            = barcodeWriter.encode(eventQRCode, ZXing.BarcodeFormat.QR_CODE, 600, 600);
            BitmapRenderer bit           = new BitmapRenderer();
            Bitmap         image         = bit.Render(bm, ZXing.BarcodeFormat.QR_CODE, eventQRCode);

            qrCodePhoto.Image = image;
        }
        private void _SaleCupon_Initialize()
        {
            QRCodeWriter QRWriter = new QRCodeWriter();
            ByteMatrix   QRObject = QRWriter.encode("http://www.curfit.com/mobile/" + cuponhash.Data.hash, BarcodeFormat.QR_CODE, 600, 600);

            SaleCuponControl.imgQRCode.Source = getImageSource(QRObject.ToBitmap());

            SaleCuponControl.btnClose.Click  += new RoutedEventHandler(_SaleCupon_P_RightHandUp);
            SaleCuponControl.btnReturn.Click += new RoutedEventHandler(_SaleCupon_P_LeftHandUp);
        }
Ejemplo n.º 20
0
        private void PrintWalletInfo()
        {
            QRCodeWriter write = new QRCodeWriter();

            int size = 120;

            BitMatrix      matrix = write.encode("", ZXing.BarcodeFormat.QR_CODE, size, size, null);
            BitmapRenderer bit    = new BitmapRenderer();

            Android.Graphics.Bitmap bitmap = bit.Render(matrix, BarcodeFormat.QR_CODE, "");
        }
Ejemplo n.º 21
0
        /// <summary>
        /// 产生二位码图片
        /// </summary>
        /// <param name="qrCode"></param>
        public Bitmap CreateQRCode(string qrCode, int width, int height)
        {
            QRCodeWriter writer = new QRCodeWriter();
            Dictionary <EncodeHintType, object> hints = new Dictionary <EncodeHintType, object>();

            hints.Add(EncodeHintType.CHARACTER_SET, "UTF-8");
            hints.Add(EncodeHintType.MARGIN, 0);
            BitMatrix bm          = writer.encode(qrCode, BarcodeFormat.QR_CODE, width, height, hints);
            Bitmap    imageRQCode = new BarcodeWriter().Write(bm);

            return(imageRQCode);
        }
Ejemplo n.º 22
0
        public static byte[] GenerateQrCodePng(string info, int margin, int width, int height)
        {
            IDictionary <EncodeHintType, object> hints = new Dictionary <EncodeHintType, object>();

            hints.Add(EncodeHintType.MARGIN, margin);

            QRCodeWriter qr = new QRCodeWriter();

            BitMatrix matrix = qr.encode(info, ZXing.BarcodeFormat.QR_CODE, width, height, hints);

            return(matrix.ToPng());
        }
        private void GenerateQRCode()
        {
            var uuid = Intent.GetStringExtra("uuid");

            codeTextView.Text = uuid;
            QRCodeWriter   writer = new QRCodeWriter();
            BitMatrix      bm     = writer.encode(uuid, ZXing.BarcodeFormat.QR_CODE, 600, 600);
            BitmapRenderer bit    = new BitmapRenderer();
            Bitmap         image  = bit.Render(bm, ZXing.BarcodeFormat.QR_CODE, uuid);

            qrCodeImage.SetImageBitmap(image);
        }
Ejemplo n.º 24
0
        public static Bitmap CreateQRCode(string address)
        {
            QRCodeWriter write = new QRCodeWriter();

            int size = 120;

            BitMatrix      matrix = write.encode(address, ZXing.BarcodeFormat.QR_CODE, size, size, null);
            BitmapRenderer bit    = new BitmapRenderer();
            Bitmap         bitmap = bit.Render(matrix, BarcodeFormat.QR_CODE, address);

            return(bitmap);
        }
Ejemplo n.º 25
0
 /// <summary>
 /// What to do when the selection changes in the QR Code site list:
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 private void cmboExportSiteQR_SelectedIndexChanged(object sender, EventArgs e)
 {
     // Asbestos underpants:
     try
     {
         // Get the current selection of the combo box and make sure it
         // isn't empty:
         String site = (string)cmboExportSiteQR.Text;
         if (!String.IsNullOrEmpty(site))
         {
             // Ask the main form to give us the site parameters for this site.
             // Since the main form has all the code to do this, we'll ask it
             // to do the dirty work.
             SiteParameters siteParams = caller.GetSiteParamsForQRCode(site);
             // Now we'll generate the text we'll embed into the QR Code.  We want
             // this to be as compact as we can get it, so our "headings" will be
             // single letters.  We'll start off with an identifying header so the
             // QR Code reader will know the format of our string.  We delimite the
             // string with pipes, which aren't allowed in any of our fields.  We
             // want this to match as closely to the values of the XML export file
             // for consistency.  That means the hash engine and the character
             // limit fields will need some tweaking.
             StringBuilder sb = new StringBuilder();
             sb.Append("CRYPTNOSv1|" +
                       "S:" + siteParams.Site + "|" +
                       "H:" + HashEngine.HashEnumStringToDisplayHash(siteParams.Hash) + "|" +
                       "I:" + siteParams.Iterations.ToString() + "|" +
                       "C:" + siteParams.CharTypes.ToString() + "|L:");
             if (siteParams.CharLimit < 0)
             {
                 sb.Append("0");
             }
             else
             {
                 sb.Append(siteParams.CharLimit.ToString());
             }
             // Now that we've built our string, use the QRCodeWriter from ZXing to
             // build the QR Code image and assign the bitmap to the picture box:
             byteMatrix = qrCodeWriter.encode(sb.ToString(),
                                              BarcodeFormat.QR_CODE, 200, 200);
             pictureBox1.Image = byteMatrix.ToBitmap();
         }
         // If the selection in the combo box wasn't useful, empty the picture box:
         else
         {
             pictureBox1.Image = null;
         }
     }
     // Similarly, if anything blew up, empty the picture box:
     catch { pictureBox1.Image = null; }
 }
Ejemplo n.º 26
0
        private void GenerateQrCode(string text)
        {
            QRCodeWriter qrWriter = new QRCodeWriter();
            Dictionary <ZXing.EncodeHintType, object> hints = new Dictionary <ZXing.EncodeHintType, object>();

            hints.Add(ZXing.EncodeHintType.CHARACTER_SET, "windows-1251");
            hints.Add(ZXing.EncodeHintType.MARGIN, 1);
            ZXing.Common.BitMatrix matrix = qrWriter.encode(text.Trim(), ZXing.BarcodeFormat.QR_CODE, 640, 640, hints);

            ZXing.Presentation.BarcodeWriter writer = new ZXing.Presentation.BarcodeWriter();
            WriteableBitmap wb = writer.Write(matrix);

            this.image.Source = wb;
        }
Ejemplo n.º 27
0
        public static IActionResult Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", Route = null)] HttpRequest req,
            ILogger log,
            ExecutionContext context)
        {
            log.LogInformation("GenerateQRCode received a request.");

            // process input parameters
            string data = req.Query["data"];
            string size = req.Query["size"];
            string dpi  = req.Query["dpi"];

            int sizeValue = 50;

            if (!string.IsNullOrEmpty(size))
            {
                int.TryParse(size, out sizeValue);
            }

            int dpiValue = 600;

            if (!string.IsNullOrEmpty(dpi))
            {
                int.TryParse(dpi, out dpiValue);
            }

            // render QR code into bitmap
            if (!string.IsNullOrEmpty(data))
            {
                var writer    = new QRCodeWriter();
                var pixelData = writer.encode(data, ZXing.BarcodeFormat.QR_CODE, 0, 0);
                var renderer  = new ZXing.CoreCompat.Rendering.BitmapRenderer()
                {
                    DpiX = dpiValue,
                    DpiY = dpiValue
                };
                var bitmap = renderer.Render(pixelData, ZXing.BarcodeFormat.QR_CODE, data, new ZXing.Common.EncodingOptions()
                {
                    Height = sizeValue,
                    Width  = sizeValue
                });

                return(new FileContentResult(ImageToByteArray(bitmap), "image/jpeg"));
            }
            else
            {
                log.LogInformation("No data parameter provided.");
                return(new BadRequestResult());
            }
        }
Ejemplo n.º 28
0
        public string GetBarCodeImageLink(BarSettings barSettings, string BarCodeNumber, string iUsersID, int LocalGenID, string MapPath)
        {
            barSettings.PathFile = MapPath + @"UsersTemp\FileStock\bar_24" + iUsersID + "_" + LocalGenID + ".png";
            //errorProvider1.Clear();
            barSettings.Data = BarCodeNumber;
            int W = barSettings.Width;
            int H = barSettings.Height;

            QRCodeWriter qrEncode = new QRCodeWriter(); //создание QR кода
            //string strRUS = "Привет, мир";  //строка на русском языке

            Dictionary <EncodeHintType, object> hints = new Dictionary <EncodeHintType, object>(); //для колекции поведений

            hints.Add(EncodeHintType.CHARACTER_SET, "utf-8");                                      //добавление в коллекцию кодировки utf-8
            BitMatrix qrMatrix = qrEncode.encode(                                                  //создание матрицы QR
                barSettings.Data,                                                                  //кодируемая строка
                BarcodeFormat.QR_CODE,                                                             //формат кода, т.к. используется QRCodeWriter применяется QR_CODE
                W,                                                                                 //ширина
                H,                                                                                 //высота
                hints);                                                                            //применение колекции поведений

            BarcodeWriter qrWrite = new BarcodeWriter();                                           //класс для кодирования QR в растровом файле

            qrWrite.Options.Width  = W;
            qrWrite.Options.Height = H;
            Bitmap qrImage = qrWrite.Write(qrMatrix);                                   //создание изображения

            qrImage.Save(barSettings.PathFile, System.Drawing.Imaging.ImageFormat.Png); //сохранение изображения

            /*
             * //Вставляем текст в Qr:
             * RectangleF rectf = new RectangleF(70, 90, 90, 50);
             * Graphics g = Graphics.FromImage(qrImage);
             * //g.SmoothingMode = SmoothingMode.AntiAlias;
             * //g.InterpolationMode = InterpolationMode.HighQualityBicubic;
             * //g.PixelOffsetMode = PixelOffsetMode.HighQuality;
             * g.DrawString(barSettings.Data, new Font("Tahoma", 8), Brushes.Black, rectf);
             * g.Flush();
             * qrImage.Save(barSettings.PathFile, System.Drawing.Imaging.ImageFormat.Png);//сохранение изображения
             */

            /*
             * BarcodeReader qrDecode = new BarcodeReader(); //чтение QR кода
             * Result text = qrDecode.Decode((Bitmap)Bitmap.FromFile("1.png")); //декодирование растрового изображения
             * Console.WriteLine(text.Text);   //вывод результата
             */

            return("<img src='" + @"..\..\..\UsersTemp\FileStock\bar_24" + iUsersID + "_" + LocalGenID + ".png" + "' alt='" + BarCodeNumber + "' >"); //width='35%' height='35%'
        }
Ejemplo n.º 29
0
        public static byte[] GenerateQrCodeViaMagick(string info, int margin, int width, int height)
        {
            IDictionary <EncodeHintType, object> hints = new Dictionary <EncodeHintType, object>();

            hints.Add(EncodeHintType.MARGIN, margin);

            QRCodeWriter qr = new QRCodeWriter();

            BitMatrix matrix = qr.encode(info, ZXing.BarcodeFormat.QR_CODE, width, height, hints);

            using (MagickImage magickImage = new MagickImage(matrix.ToPng()))
            {
                return(magickImage.ToByteArray(MagickFormat.Jpeg));
            }
        }
Ejemplo n.º 30
0
        private void GeneratorQR(string nameCompany, string notice, string data_time_now)
        {
            string       qr_string = nameCompany + "_" + notice + "_" + data_time_now;
            QRCodeWriter qrEncoder = new QRCodeWriter();
            Dictionary <EncodeHintType, object> hints = new Dictionary <EncodeHintType, object>
            {
                { EncodeHintType.CHARACTER_SET, "utf-8" }
            };
            BitMatrix qrMatrix = qrEncoder.encode(qr_string,
                                                  BarcodeFormat.QR_CODE, 100, 100, hints);
            BarcodeWriter barcodeWriter = new BarcodeWriter();

            qrImage      = barcodeWriter.Write(qrMatrix);
            viewQR.Image = qrImage;
        }
Ejemplo n.º 31
0
      private static void compareToGoldenFile(String contents,
                                              ErrorCorrectionLevel ecLevel,
                                              int resolution,
                                              String fileName)
      {
         var image = loadImage(fileName);
         Assert.NotNull(image);
         BitMatrix goldenResult = createMatrixFromImage(image);
         Assert.NotNull(goldenResult);

         QRCodeWriter writer = new QRCodeWriter();
         IDictionary<EncodeHintType, Object> hints = new Dictionary<EncodeHintType, Object>();
         hints[EncodeHintType.ERROR_CORRECTION] = ecLevel;
         BitMatrix generatedResult = writer.encode(contents, BarcodeFormat.QR_CODE, resolution,
             resolution, hints);

         Assert.AreEqual(resolution, generatedResult.Width);
         Assert.AreEqual(resolution, generatedResult.Height);
         Assert.AreEqual(goldenResult, generatedResult);
      }
Ejemplo n.º 32
0
      public void testQRCodeWriter()
      {
         // The QR should be multiplied up to fit, with extra padding if necessary
         int bigEnough = 256;
         QRCodeWriter writer = new QRCodeWriter();
         BitMatrix matrix = writer.encode("http://www.google.com/", BarcodeFormat.QR_CODE, bigEnough,
             bigEnough, null);
         Assert.NotNull(matrix);
         Assert.AreEqual(bigEnough, matrix.Width);
         Assert.AreEqual(bigEnough, matrix.Height);

         // The QR will not fit in this size, so the matrix should come back bigger
         int tooSmall = 20;
         matrix = writer.encode("http://www.google.com/", BarcodeFormat.QR_CODE, tooSmall,
             tooSmall, null);
         Assert.NotNull(matrix);
         Assert.IsTrue(tooSmall < matrix.Width);
         Assert.IsTrue(tooSmall < matrix.Height);

         // We should also be able to handle non-square requests by padding them
         int strangeWidth = 500;
         int strangeHeight = 100;
         matrix = writer.encode("http://www.google.com/", BarcodeFormat.QR_CODE, strangeWidth,
             strangeHeight, null);
         Assert.NotNull(matrix);
         Assert.AreEqual(strangeWidth, matrix.Width);
         Assert.AreEqual(strangeHeight, matrix.Height);
      }