Beispiel #1
0
        public static Texture2D Generate(string data, int size)
        {
            var writer = new BarcodeWriter()
            {
                Format = BarcodeFormat.QR_CODE,

                Options = new EncodingOptions()
                {
                    Height = size,
                    Width  = size,
                    Margin = 0
                }
            };

            var matrix = writer.Encode(data);

            var colors = BitMatrixToColors(matrix);

            Texture2D tex = new Texture2D(matrix.Width, matrix.Height);

            tex.filterMode = FilterMode.Point;
            tex.SetPixels(colors);

            tex.Apply();

            return(tex);
        }
Beispiel #2
0
        private Bitmap GetQRCodeByZXingNet(String strMessage, Int32 width, Int32 height)
        {
            String imagePath = System.Windows.Forms.Application.StartupPath + "\\ICON.png";
            Bitmap result    = null;

            try
            {
                BarcodeWriter barCodeWriter = new BarcodeWriter();
                barCodeWriter.Format = BarcodeFormat.QR_CODE;                                                                   //barcode格式
                barCodeWriter.Options.Hints.Add(EncodeHintType.CHARACTER_SET, "UTF-8");                                         //編碼字元utf-8
                barCodeWriter.Options.Hints.Add(EncodeHintType.ERROR_CORRECTION, ZXing.QrCode.Internal.ErrorCorrectionLevel.H); //錯誤校正等級
                barCodeWriter.Options.Height = height;                                                                          //高度
                barCodeWriter.Options.Width  = width;                                                                           //寬度
                barCodeWriter.Options.Margin = 0;                                                                               //外邊距
                ZXing.Common.BitMatrix bm = barCodeWriter.Encode(strMessage);                                                   //將訊息寫入
                result = barCodeWriter.Write(bm);

                Bitmap overlay = new Bitmap(imagePath);                           //載入圖片

                int deltaHeigth = result.Height - overlay.Height;                 //圖片y
                int deltaWidth  = result.Width - overlay.Width;                   //圖片x

                Graphics g = Graphics.FromImage(result);                          //圖型
                g.DrawImage(overlay, new Point(deltaWidth / 2, deltaHeigth / 2)); //畫出圖片
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
            return(result);
        }
Beispiel #3
0
        /// <summary>
        ///     生成二维码图片
        /// </summary>
        /// <param name="strMessage"> 要生成二维码的字符串 </param>
        /// <param name="width">      二维码图片宽度 </param>
        /// <param name="height">     二维码图片高度 </param>
        /// <returns>  </returns>
        public static Bitmap GenerateQRCode(
            string strMessage,
            int width,
            int height)
        {
            Bitmap result = null;

            try
            {
                var barCodeWriter = new BarcodeWriter {
                    Format = BarcodeFormat.QR_CODE
                };
                barCodeWriter.Options.Hints.Add(EncodeHintType.CHARACTER_SET, "UTF-8");
                barCodeWriter.Options.Hints.Add(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
                barCodeWriter.Options.Height = height;
                barCodeWriter.Options.Width  = width;
                barCodeWriter.Options.Margin = 0;
                var bm = barCodeWriter.Encode(strMessage);
                result = barCodeWriter.Write(bm);
            }
            catch
            {
                //异常输出
            }

            return(result);
        }
Beispiel #4
0
        /// <summary>
        /// 生成二维码
        /// </summary>
        /// <returns></returns>

        public Bitmap creatQcode(string path)
        {
            try
            {
                int           width         = 232;                                      //图片宽度
                int           height        = 232;                                      //图片长度
                BarcodeWriter barCodeWriter = new BarcodeWriter();
                barCodeWriter.Format = BarcodeFormat.QR_CODE;                           // 生成码的方式(这里设置的是二维码),有条形码\二维码\还有中间嵌入图片的二维码等
                barCodeWriter.Options.Hints.Add(EncodeHintType.CHARACTER_SET, "UTF-8"); // 支持中文字符串
                barCodeWriter.Options.Hints.Add(EncodeHintType.ERROR_CORRECTION, ZXing.QrCode.Internal.ErrorCorrectionLevel.H);
                barCodeWriter.Options.Height = height;
                barCodeWriter.Options.Width  = width;
                barCodeWriter.Options.Margin = 0;                                                                    //设置的白边大小
                ZXing.Common.BitMatrix bm = barCodeWriter.Encode(path);                                              //DNS为要生成的二维码字符串
                Bitmap result             = barCodeWriter.Write(bm);
                Bitmap Qcbmp = result.Clone(new Rectangle(Point.Empty, result.Size), PixelFormat.Format1bppIndexed); //位深度
                                                                                                                     // SaveImg(currentPath, Qcbmp); //图片存储自己写的函数
                                                                                                                     //Qcbmp=WhiteUp(Qcbmp,10);
                return(Qcbmp);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
                return(null);
            }
        }
Beispiel #5
0
        /// <summary>
        /// 生成二维码
        /// </summary>
        /// <param name="msg">二维码信息</param>
        /// <returns>图片</returns>
        private Bitmap GenByZXingNet(string msg)
        {
            BarcodeWriter writer = new BarcodeWriter();

            writer.Format = BarcodeFormat.QR_CODE;
            writer.Options.Hints.Add(EncodeHintType.CHARACTER_SET, "UTF-8"); //编码问题
            writer.Options.Hints.Add(EncodeHintType.ERROR_CORRECTION, ZXing.QrCode.Internal.ErrorCorrectionLevel.H);
            const int codeSizeInPixels = 250;                                //设置图片长宽

            writer.Options.Height = writer.Options.Width = codeSizeInPixels;
            writer.Options.Margin = 0;//设置边框
            ZXing.Common.BitMatrix bm = writer.Encode(msg);
            Bitmap img = writer.Write(bm);



            //获取文本
            string texts = this.textBox2.Text;
            //得到Bitmap(传入Rectangle.Empty自动计算宽高)
            Bitmap bmp = TextToBitmap(texts, this.textBox2.Font, Rectangle.Empty, this.textBox2.ForeColor, this.textBox2.BackColor);

            /*//上下合并
             * int iWidth = bmp.Width > img.Width ? bmp.Width : img.Width;
             * int iHeight = bmp.Height + img.Height;
             * Bitmap bitmap = new Bitmap(iWidth, iHeight);
             *
             * Graphics g = Graphics.FromImage(bitmap);
             * g.DrawImage(bmp, new Rectangle(0, 0, bmp.Width, bmp.Height), new Rectangle(0, 0, bmp.Width, bmp.Height), GraphicsUnit.Pixel);
             * g.DrawImage(img, new Rectangle(0, bmp.Height, img.Width, img.Height), new Rectangle(0, 0, img.Width, img.Height), GraphicsUnit.Pixel);
             * g.Dispose();
             *
             * pictureBox1.Image = bitmap;*/


            //上下合并
            int    iWidth  = img.Width > bmp.Width ? img.Width : bmp.Width;
            int    iHeight = img.Height + bmp.Height;
            Bitmap bitmap  = new Bitmap(iWidth, iHeight);

            Graphics g = Graphics.FromImage(bitmap);

            g.DrawImage(img, new Rectangle(0, 0, img.Width, img.Height), new Rectangle(0, 0, img.Width, img.Height), GraphicsUnit.Pixel);
            g.DrawImage(bmp, new Rectangle(0, img.Height, bmp.Width, bmp.Height), new Rectangle(0, 0, bmp.Width, bmp.Height), GraphicsUnit.Pixel);
            g.Dispose();

            pictureBox1.Image = bitmap;

            return(img);

            /*
             * //用PictureBox显示
             * this.pictureBox2.Image = bmp;
             *
             * pictureBox1.Image = img;
             *
             */
        }
Beispiel #6
0
        /// <summary>
        /// 生成二维码
        /// </summary>
        /// <param name="content">内容文本</param>
        /// <param name="size">图片尺寸(像素),0表示不设置</param>
        /// <param name="margin">二维码的边距,图片尺寸大于0生效</param>
        /// <param name="errorCorrection">纠错码等级</param>
        /// <param name="characterSet">内容编码</param>
        /// <returns></returns>
        public static System.Drawing.Image EncodeQrCode(string content, int size = 10, int margin = 2, string errorCorrection = "L", string characterSet = "utf-8")
        {
            BarcodeWriter barCodeWriter = new BarcodeWriter();

            barCodeWriter.Format = BarcodeFormat.QR_CODE;
            QrCodeEncodingOptions options = new QrCodeEncodingOptions()
            {
                // DisableECI = true,
                CharacterSet = characterSet, // 设置内容编码
                // QrVersion = 8,
            };

            errorCorrection = errorCorrection.ToUpper();
            IDictionary <string, int> dic = new Dictionary <string, int>()
            {
                { "L", 1 },
                { "M", 0 },
                { "Q", 3 },
                { "H", 2 }
            };

            if (!dic.ContainsKey(errorCorrection))
            {
                errorCorrection = "L";
            }


            if (size != 0)
            {
                int s;
                if (errorCorrection == "L" || errorCorrection == "M")
                {
                    s = size * 27;
                }
                else
                {
                    s = size * 31;
                }

                s += (margin - 1) * (size * 2);

                options.Width  = s;
                options.Height = s;
                options.Margin = margin; // 设置二维码的边距,单位不是固定像素
            }


            options.ErrorCorrection = ErrorCorrectionLevel.forBits(dic[errorCorrection]);


            barCodeWriter.Options = options;
            ZXing.Common.BitMatrix bm = barCodeWriter.Encode(content);
            Bitmap result             = barCodeWriter.Write(bm);

            return(result);
        }
Beispiel #7
0
        public static void ConvertByteQrCodeToWriteableBitmap(string content, string fileName, int width, string filePath)
        {
            BarcodeWriter writer = new BarcodeWriter();

            writer.Format         = BarcodeFormat.QR_CODE;
            writer.Options.Height = writer.Options.Width = width;
            writer.Options.Margin = 0;//设置边框
            ZXing.Common.BitMatrix bm = writer.Encode(content);
            Bitmap bmap = writer.Write(bm);

            bmap.Save(filePath + @"\" + fileName, ImageFormat.Png);
        }
Beispiel #8
0
        /// <summary>
        /// Code128
        /// </summary>
        /// <param name="content"></param>
        /// <param name="fileName"></param>
        /// <param name="width"></param>
        /// <param name="filePath"></param>
        public static void GetCode128ToBitmap(string content, string fileName, int width, string filePath)
        {
            BarcodeWriter writer = new BarcodeWriter();

            writer.Format         = BarcodeFormat.CODE_128;
            writer.Options.Height = width / 4;
            writer.Options.Width  = width;
            writer.Options.Margin = 0;//设置边框
            ZXing.Common.BitMatrix bm = writer.Encode(content);
            Bitmap bmap = writer.Write(bm);

            bmap.Save(filePath + @"\" + fileName, ImageFormat.Png);
        }
Beispiel #9
0
        /// <summary>
        /// Creates barcode
        /// </summary>
        /// <param name="content">Content string</param>
        /// <param name="bf">Barcode Format</param>
        /// <param name="width">width (standard value 100)</param>
        /// <param name="height">height (standard value 100)</param>
        /// <param name="margin">Margin (standard value 0)</param>
        /// <returns></returns>
        public static Bitmap CreateBarcode(string content, BarcodeFormat bf = BarcodeFormat.QR_CODE,
                                           int width = 100, int height = 100, int margin = 0)
        {
            var barcodeWriter = new BarcodeWriter
            {
                Options = new EncodingOptions
                {
                    Width = width, Height = height, Margin = margin, PureBarcode = true
                },
                Format = bf
            };

            return(barcodeWriter.Write(barcodeWriter.Encode(content)));
        }
Beispiel #10
0
        public static Bitmap GenByZxingNet(string InputString, int WeightHeight)
        {
            BarcodeWriter writer = new BarcodeWriter();

            writer.Format = BarcodeFormat.QR_CODE;
            writer.Options.Hints.Add(EncodeHintType.CHARACTER_SET, "UTF-8");
            writer.Options.Hints.Add(EncodeHintType.ERROR_CORRECTION, ZXing.QrCode.Internal.ErrorCorrectionLevel.H);
            writer.Options.Height = writer.Options.Width = WeightHeight;
            writer.Options.Margin = 1;
            ZXing.Common.BitMatrix bm = writer.Encode(InputString);
            Bitmap img = writer.Write(bm);

            return(img);
        }
Beispiel #11
0
        private void button_toVector_Click(object sender, EventArgs e)
        {
            StartEvent();
            SvgRenderer svg = new SvgRenderer();

            SvgRenderer.SvgImage si = svg.Render(qrCodeWriter.Encode(qCode), qrCodeWriter.Format, qCode);
            var file = File.Open("D:\\a.eps", FileMode.OpenOrCreate);

            byte[] b = Encoding.UTF8.GetBytes(si.ToString());
            file.Write(b, 0, b.Length);
            file.Close();
            application.ActiveLayer.Import("D:\\a.eps");
            //File.Delete("D:\\a.eps");
            EndEvent();
        }
        /// <summary>
        /// Generating Barcode Label
        /// </summary>
        /// <param name="form"></param>
        /// <returns></returns>
        byte[] GenerateBarcodeLabel(string pathType, string ID)
        {
            BarcodeWriter b = new BarcodeWriter();

            BarcodeEnum.TYPE type = BarcodeEnum.TYPE.CODE128;
            b.BarCodeData = ID;
            b.ImgWidth    = 120;
            b.ImgHeight   = 40;
            System.Drawing.Image img = b.Encode(type);
            img = b.Generate_Labels(img);

            ImageConverter converter = new ImageConverter();

            return((byte[])converter.ConvertTo(img, typeof(byte[])));
            //return img;
        }
Beispiel #13
0
        public void ZXingNet()
        {
            var text = nameof(ZXingNet);

            var barCodeWriter = new BarcodeWriter();

            barCodeWriter.Format = BarcodeFormat.QR_CODE;
            barCodeWriter.Options.Hints.Add(EncodeHintType.CHARACTER_SET, "UTF-8");
            barCodeWriter.Options.Hints.Add(EncodeHintType.ERROR_CORRECTION, ZXing.QrCode.Internal.ErrorCorrectionLevel.H);
            barCodeWriter.Options.Height = 100;
            barCodeWriter.Options.Width  = 100;
            barCodeWriter.Options.Margin = 0;
            var bm = barCodeWriter.Encode(text);
            var b  = barCodeWriter.Write(bm);
            //b.Save(Path.Combine(zxingNetfolders, $"{DateTime.Now.ToString("mmssms")}.jpg"), ImageFormat.Jpeg);
        }
Beispiel #14
0
        /// <summary>
        /// 生成二维码
        /// </summary>
        /// <param name="msg">二维码信息</param>
        /// <returns>图片</returns>
        private Bitmap GenByZXingNet(string msg)
        {
            BarcodeWriter writer = new BarcodeWriter();

            writer.Format = BarcodeFormat.QR_CODE;
            writer.Options.Hints.Add(EncodeHintType.CHARACTER_SET, "UTF-8"); //编码问题
            writer.Options.Hints.Add(EncodeHintType.ERROR_CORRECTION, ZXing.QrCode.Internal.ErrorCorrectionLevel.H);
            const int codeSizeInPixels = 150;                                //设置图片长宽

            writer.Options.Height = writer.Options.Width = codeSizeInPixels;
            writer.Options.Margin = 0;//设置边框
            ZXing.Common.BitMatrix bm = writer.Encode(msg);
            Bitmap img = writer.Write(bm);

            //pictureBox1.Image = img;
            return(img);
        }
Beispiel #15
0
        /// <summary>
        /// 生成条码
        ///
        /// </summary>
        /// <param name="content">加密内容,不能为空</param>
        /// <param name="w">宽</param>
        /// <param name="h">高</param>
        /// <returns></returns>
        public static Bitmap GenerateBarCode(String content, int w = 80, int h = 30)
        {
            if (string.IsNullOrEmpty(content))
            {
                return(null);
            }
            Bitmap        bitmap        = null;
            BarcodeWriter barcodeWriter = new BarcodeWriter();

            barcodeWriter.Format = BarcodeFormat.EAN_13;
            barcodeWriter.Options.Hints.Add(EncodeHintType.CHARACTER_SET, "UTF-8");
            barcodeWriter.Options.Hints.Add(EncodeHintType.ERROR_CORRECTION, ZXing.QrCode.Internal.ErrorCorrectionLevel.H);
            barcodeWriter.Options.Width  = w;
            barcodeWriter.Options.Height = h;
            barcodeWriter.Options.Margin = 0;
            ZXing.Common.BitMatrix bitMatrix = barcodeWriter.Encode(content);
            bitmap = barcodeWriter.Write(bitMatrix);
            return(bitmap);
        }
Beispiel #16
0
        public static Bitmap Createwm(string asset, int x, int y)
        {
            Bitmap result = null;

            try {
                BarcodeWriter barCodeWriter = new BarcodeWriter();
                barCodeWriter.Format = BarcodeFormat.QR_CODE;
                barCodeWriter.Options.Hints.Add(EncodeHintType.CHARACTER_SET, "UTF-8");
                barCodeWriter.Options.Hints.Add(EncodeHintType.ERROR_CORRECTION, ZXing.QrCode.Internal.ErrorCorrectionLevel.H);
                barCodeWriter.Options.Height = y;
                barCodeWriter.Options.Width  = x;
                barCodeWriter.Options.Margin = 0;
                ZXing.Common.BitMatrix bm = barCodeWriter.Encode(asset);
                result = barCodeWriter.Write(bm);
                return(result);
            } catch {
                return(null);
            }
        }
Beispiel #17
0
        /// <summary>
        ///     生成二维码
        /// </summary>
        /// <param name="msg">二维码信息</param>
        /// <returns>图片</returns>
        public static Bitmap GenByZXingNet(string msg)
        {
            var writer = new BarcodeWriter {
                Format = BarcodeFormat.QR_CODE
            };

            writer.Options.Hints.Add(EncodeHintType.CHARACTER_SET, "UTF-8"); //编码问题
            writer.Options.Hints.Add(
                EncodeHintType.ERROR_CORRECTION,
                ErrorCorrectionLevel.H
                );
            const int codeSizeInPixels = 250; //设置图片长宽

            writer.Options.Height = writer.Options.Width = codeSizeInPixels;
            writer.Options.Margin = 0; //设置边框
            var bm  = writer.Encode(msg);
            var img = writer.Write(bm);

            return(img);
        }
Beispiel #18
0
        public static ImageSource CodelImgsBit(string str, int size)
        {
            BarcodeWriter writer = new BarcodeWriter
            {
                Format = BarcodeFormat.QR_CODE,
            };

            writer.Options.Hints.Add(EncodeHintType.CHARACTER_SET, "UTF-8"); // 编码问题
            writer.Options.Hints.Add(EncodeHintType.ERROR_CORRECTION, ZXing.QrCode.Internal.ErrorCorrectionLevel.H);
            int codeSizeInPixels = size;                                     // 设置图片长宽

            writer.Options.Height = codeSizeInPixels;
            writer.Options.Width  = codeSizeInPixels;
            writer.Options.Margin = 0;
            // 设置边框
            BitMatrix bm  = writer.Encode(str);
            Bitmap    img = writer.Write(bm);

            return(BitmapToBitmapImage(img));
        }
        void ProcessarQR()
        {
            var dim    = 130;
            var writer = new BarcodeWriter(BarcodeFormat.QR_CODE)
            {
                Options = new EncodingOptions
                {
                    Width  = dim,
                    Height = dim,
                    Margin = 0
                }
            };
            var encoded = writer.Encode(NFCe.InfoSuplementares.Uri);

            MargemQR = new Thickness(13);
            foreach (var item in writer.WriteToUI(encoded))
            {
                imgQR.Children.Add(item);
            }
        }
        /// <summary>
        /// 生成条码图片
        /// </summary>
        /// <param name="strMessage">要生成二维码的字符串</param>
        /// <param name="width">二维码图片宽度</param>
        /// <param name="height">二维码图片高度</param>
        /// <returns></returns>
        private Bitmap GetBarCodeByZXingNet(String strMessage, Int32 width, Int32 height)
        {
            Bitmap result = null;

            try
            {
                BarcodeWriter barCodeWriter = new BarcodeWriter();
                barCodeWriter.Format = BarcodeFormat.CODE_128;
                barCodeWriter.Options.Hints.Add(EncodeHintType.CHARACTER_SET, "UTF-8");
                barCodeWriter.Options.Height = height;
                barCodeWriter.Options.Width  = width;
                barCodeWriter.Options.Margin = 0;
                ZXing.Common.BitMatrix bm = barCodeWriter.Encode(strMessage);
                result = barCodeWriter.Write(bm);
            }
            catch
            {
                throw;
            }
            return(result);
        }
Beispiel #21
0
        // 二维码生成函数
        private System.Drawing.Image GeneratorQRCode(string txt)
        {
            //BarcodeWriter一个智能类来编码一些内容的二维码、条形码图像
            BarcodeWriter writer = new BarcodeWriter
            {
                Format = BarcodeFormat.QR_CODE//设置二维码的格式
            };

            writer.Options.Hints.Add(EncodeHintType.CHARACTER_SET, "UTF-8"); // 编码格式
            writer.Options.Hints.Add(EncodeHintType.ERROR_CORRECTION, ZXing.QrCode.Internal.ErrorCorrectionLevel.H);
            int codeSizeInPixels = 260;                                      // 二维码长宽

            writer.Options.Height = codeSizeInPixels;
            writer.Options.Width  = codeSizeInPixels;
            writer.Options.Margin = 0;                   // 设置边框
            BitMatrix bm  = writer.Encode(txt);
            Bitmap    img = writer.Write(bm);            //对指定内容进行编码,并返回该码的呈现实例(渲染属性、实例使用,在方法之前调用)

            QrCodeImg.Source = BitmapToBitmapImage(img); //将图片控件的数据源设为生成后的二维码
            return(img);
        }
Beispiel #22
0
        static void Generate(int width, int height, string content, string filename = null)
        {
            BarcodeWriter barCodeWriter = new BarcodeWriter();

            barCodeWriter.Format = BarcodeFormat.QR_CODE;
            barCodeWriter.Options.Hints.Add(EncodeHintType.CHARACTER_SET, "UTF-8");
            barCodeWriter.Options.Hints.Add(EncodeHintType.ERROR_CORRECTION, ZXing.QrCode.Internal.ErrorCorrectionLevel.H);
            barCodeWriter.Options.Height = height;
            barCodeWriter.Options.Width  = width;
            barCodeWriter.Options.Margin = 0;

            BitMatrix bm     = barCodeWriter.Encode(content);
            var       bitmap = barCodeWriter.Write(bm);

            if (string.IsNullOrWhiteSpace(filename))
            {
                filename = $"QR_{DateTime.Now.ToString("yyyyMMddHHmmssfff")}.png";
            }

            bitmap.Save(filename, System.Drawing.Imaging.ImageFormat.Png);
        }
Beispiel #23
0
        /// <summary>
        /// 生成二维码图片
        /// </summary>
        /// <param name="strMessage">要生成二维码的字符串</param>
        /// <param name="width">二维码图片宽度</param>
        /// <param name="height">二维码图片高度</param>
        /// <returns></returns>
        private Bitmap GetQRCodeByZXingNet(String strMessage, Int32 width, Int32 height)
        {
            Bitmap result = null;

            try
            {
                BarcodeWriter barCodeWriter = new BarcodeWriter();
                barCodeWriter.Format = BarcodeFormat.QR_CODE;
                barCodeWriter.Options.Hints.Add(EncodeHintType.CHARACTER_SET, "UTF-8");
                barCodeWriter.Options.Hints.Add(EncodeHintType.ERROR_CORRECTION, ZXing.QrCode.Internal.ErrorCorrectionLevel.H);
                barCodeWriter.Options.Height = height;
                barCodeWriter.Options.Width  = width;
                barCodeWriter.Options.Margin = 0;
                ZXing.Common.BitMatrix bm = barCodeWriter.Encode(strMessage);
                result = barCodeWriter.Write(bm);
            }
            catch (Exception ex)
            {
                //异常输出
            }
            return(result);
        }
Beispiel #24
0
        /// <summary>
        /// 生成二维码
        /// </summary>
        /// <param name="content">二维码内容</param>
        /// <param name="width">宽度</param>
        /// <param name="height">高度</param>
        /// <param name="saveFileName">二维码保存路径</param>
        /// <param name="logoImgPath">logo图片路径</param>
        /// <returns>位图</returns>
        public static Bitmap Encoder(string content, int width, int height, string saveFileName = "", string logoImgPath = "")
        {
            Bitmap        qrCodeImage   = null;
            BarcodeWriter barCodeWriter = new BarcodeWriter
            {
                Format = BarcodeFormat.QR_CODE
            };

            barCodeWriter.Options.Hints.Add(EncodeHintType.CHARACTER_SET, "UTF-8");
            barCodeWriter.Options.Hints.Add(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
            barCodeWriter.Options.Height = height;
            barCodeWriter.Options.Width  = width;
            barCodeWriter.Options.Margin = 0;
            BitMatrix bm = barCodeWriter.Encode(content);

            qrCodeImage = barCodeWriter.Write(bm);

            //Logo
            Bitmap logoImg = null;

            if (!logoImgPath.IsNullOrWhiteSpace())
            {
                logoImg = new Bitmap(logoImgPath);

                qrCodeImage = MergeLogo(qrCodeImage, logoImg, bm.getEnclosingRectangle());
            }

            if (!saveFileName.IsNullOrWhiteSpace())
            {
                qrCodeImage.Save(saveFileName, ImageFormat.Jpeg);
                qrCodeImage.Dispose();
                if (logoImg != null)
                {
                    logoImg.Dispose();
                }
            }
            return(qrCodeImage);
        }
Beispiel #25
0
 /// <summary>
 /// 把文本转换成Bitmap
 /// </summary>
 /// <param name="content">文本内容</param>
 /// <param name="size">图片大小</param>
 /// <param name="barcodeFormat">条码种类</param>
 /// <param name="margin">外边距</param>
 /// <param name="encoding">编码模式</param>
 /// <param name="errorCorrectionLevel">错误修正等级</param>
 /// <returns></returns>
 public static Bitmap TextToBitmap(
     string content, Size size, BarcodeFormat barcodeFormat, int margin = 0, string encoding = "UTF-8", ErrorCorrectionLevel errorCorrectionLevel = null)
 {
     try
     {
         //在生成图片之前先处理下Size然后在下方加上数据
         BarcodeWriter barcodeWriter = new BarcodeWriter();
         barcodeWriter.Format         = barcodeFormat;
         barcodeWriter.Options.Width  = size.Width;
         barcodeWriter.Options.Height = size.Height;
         barcodeWriter.Options.Margin = margin;
         barcodeWriter.Options.Hints.Add(EncodeHintType.CHARACTER_SET, encoding);
         barcodeWriter.Options.Hints.Add(EncodeHintType.ERROR_CORRECTION, errorCorrectionLevel ?? ErrorCorrectionLevel.H);
         ///bit矩阵??
         ZXing.Common.BitMatrix bitMatrix = barcodeWriter.Encode(content);
         Bitmap     bitmap     = barcodeWriter.Write(bitMatrix);
         RectangleF rectangleF = new RectangleF()
         {
             X      = 0,
             Y      = bitmap.Size.Height,
             Width  = bitmap.Size.Width,
             Height = (bitmap.Size.Height / 10),
         };
         bitmap = (Bitmap)QRCodeCommon.QRCodeAddContent(bitmap, content, rectangleF);
         if (bitmap == null)
         {
             throw new Exception("生成二维码失败");
         }
         else
         {
             return(bitmap);
         }
     }
     catch (Exception)
     {
         throw;
     }
 }
Beispiel #26
0
        /// <summary>
        /// 生成二维码图片
        /// </summary>
        /// <param name="strMessage">要生成二维码的字符串</param>
        /// <param name="width">二维码图片宽度(单位:像素)</param>
        /// <param name="height">二维码图片高度(单位:像素)</param>
        /// <returns></returns>
        private Bitmap GetQRCodeByZXingNet(String strMessage, Int32 width, Int32 height)
        {
            Bitmap result = null;

            try
            {
                BarcodeWriter barCodeWriter = new BarcodeWriter();
                //设置生成彩色二维码
                barCodeWriter.Renderer = new ZXing.Rendering.BitmapRenderer {
                    Background = Color.White, Foreground = setGolor()
                };
                barCodeWriter.Format = BarcodeFormat.QR_CODE;
                barCodeWriter.Options.Hints.Add(EncodeHintType.CHARACTER_SET, "UTF-8");
                barCodeWriter.Options.Hints.Add(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
                barCodeWriter.Options.Height = height;
                barCodeWriter.Options.Width  = width;
                barCodeWriter.Options.Margin = 0;
                BitMatrix bm = barCodeWriter.Encode(strMessage);
                result = barCodeWriter.Write(bm);
            }
            catch { }
            return(result);
        }
Beispiel #27
0
        /// <summary>
        /// Generates the barcode.
        /// </summary>
        /// <param name="barcodeType">Type of the barcode.</param>
        /// <param name="value">The value.</param>
        /// <returns></returns>
        public BarcodeObject GenerateBarcode(string barcodeType, string value)
        {
            // Determine the barcode type
            BarcodeFormat codeType = CalculateType(barcodeType);

            try
            {
                BarcodeWriter writer = new BarcodeWriter();
                writer.Format  = codeType;
                writer.Options = new EncodingOptions {
                    Height = 100, Width = 300
                };
                BitMatrix bitMatrix = writer.Encode(value);
                Bitmap    bitmap    = writer.Write(value);

                // Convert to the image bytes
                return(ConvertToBase64String(bitmap));
            }
            catch (Exception exception)
            {
                throw new Exception("GenerateBarcode is failing", exception);
            }
        }
        public static async Task <IActionResult> QrGenerator(
            [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = null)] HttpRequest req,
            ILogger log,
            ExecutionContext context)
        {
            log.LogInformation("QRGenerator API is being used.");

            try
            {
                var configBuilder = new ConfigurationBuilder()
                                    .SetBasePath(context.FunctionAppDirectory)
                                    .AddJsonFile("local.settings.json", optional: true, reloadOnChange: true)
                                    .AddEnvironmentVariables();
                var config = configBuilder.Build();
            }
            catch (Exception)
            {
                log.LogWarning("Local.Settings.json file could not be read");
            }

            string phone         = req.Query["phone"];
            string email         = req.Query["email"];
            string blobContainer = req.Query["blobContainer"];

            string  requestBody = await new StreamReader(req.Body).ReadToEndAsync();
            dynamic data        = JsonConvert.DeserializeObject(requestBody);

            phone         = phone ?? data?.phone;
            email         = email ?? data?.email;
            blobContainer = blobContainer ?? data?.blobContainer;

            if (phone != null && email != null && blobContainer != null)
            {
                CloudStorageAccount cloudStorageAccount;
                CloudBlobClient     cloudBlobClient;
                CloudBlobContainer  cloudBlobContainer;
                CloudBlockBlob      cloudBlockBlob;

                try
                {
                    log.LogInformation("Connecting to storage account");

                    cloudStorageAccount = CloudStorageAccount.Parse(Environment.GetEnvironmentVariable("AzureWebJobsStorage"));

                    cloudBlobClient = cloudStorageAccount.CreateCloudBlobClient();

                    cloudBlobContainer = cloudBlobClient.GetContainerReference(blobContainer);

                    await cloudBlobContainer.CreateIfNotExistsAsync();

                    cloudBlockBlob = cloudBlobContainer.GetBlockBlobReference($"{email} {phone}.svg");
                    cloudBlockBlob.Properties.ContentType = "image/svg+xml";
                }
                catch (Exception e)
                {
                    log.LogError("Could not connect to storage account");
                    return(new BadRequestObjectResult(e.Message));
                }

                log.LogInformation("Starting QrCode Configuration");

                ZXing.Rendering.SvgRenderer renderer = new ZXing.Rendering.SvgRenderer();
                var barcodeWriter = new BarcodeWriter <Stream>();
                barcodeWriter.Format = BarcodeFormat.QR_CODE;
                var options = new QrCodeEncodingOptions
                {
                    DisableECI   = true,
                    CharacterSet = "UTF-8",
                    Width        = 512,
                    Height       = 512,
                    Margin       = 0
                };
                barcodeWriter.Options = options;

                log.LogInformation("Encoding the data");

                string stringToEncode = String.Format(Environment.GetEnvironmentVariable("URL"), phone);
                log.LogInformation(stringToEncode);
                var imageSVG = renderer.Render(barcodeWriter.Encode(stringToEncode), barcodeWriter.Format, phone);

                log.LogInformation($"Creating image \"{email} {phone}.svg\"");

                var          encoding     = new UnicodeEncoding();
                byte[]       imageBytes   = encoding.GetBytes(imageSVG.ToString());
                MemoryStream memoryStream = new MemoryStream(imageBytes);

                try
                {
                    log.LogInformation("Uploading File");
                    await cloudBlockBlob.UploadFromStreamAsync(memoryStream);

                    log.LogInformation("Upload Complete");
                }
                catch (Exception e)
                {
                    log.LogError($"Could not upload image \"{email} {phone}.\" to storage{Environment.NewLine}{e.Message}");
                    return(new BadRequestObjectResult($"Could not upload image \"{email} {phone}.svg\" to storage"));
                }

                return((ActionResult) new OkObjectResult($"Phone: {phone}{Environment.NewLine}Email: {email}"));
            }
            else
            {
                return(phone != null || email != null
                    ?
                       (
                           email == null
                        ? new BadRequestObjectResult("Please provide an email address")
                        :
                           (
                               blobContainer == null
                            ? new BadRequestObjectResult("Please provide a BlobContainer")
                            : new BadRequestObjectResult("Please provide a phone number")
                           )
                       )
                    : new BadRequestObjectResult("Please pass a phone number and an email address"));
            }
        }
Beispiel #29
0
        public JObject QrCodeGenerator()
        {
            JObject jobj;
            string  baseString       = "";
            string  conf_code        = "";
            string  overlayImagePath = System.Web.HttpContext.Current.Server.MapPath("/images/") + ConfigurationManager.AppSettings["QrCodeOverlayImage"].ToString();

            conf_code = "grpTalk" + System.Guid.NewGuid().ToString();
            conf_code = conf_code.Replace("-", "").Replace(" ", "");
            //GENERATE_QR_CODE("12345678910111213456789987456321456987456321");
            ZXing.Common.BitMatrix bitmatrix = default(ZXing.Common.BitMatrix);
            Bitmap         bmp_image         = default(Bitmap);
            string         qr_to_str         = null;
            IBarcodeWriter writer            = default(IBarcodeWriter);


            try
            {
                writer = new BarcodeWriter
                {
                    Format  = BarcodeFormat.QR_CODE,
                    Options = new ZXing.QrCode.QrCodeEncodingOptions
                    {
                        Margin          = 0,
                        Width           = 500,
                        Height          = 500,
                        ErrorCorrection = ZXing.QrCode.Internal.ErrorCorrectionLevel.L
                    }
                };
                qr_to_str = conf_code;//CryptoUtil.Encrypt(conf_code);
                bitmatrix = writer.Encode(qr_to_str);
                bmp_image = new Bitmap(bitmatrix.Width, bitmatrix.Height);
                for (int i = 0; i <= bmp_image.Height - 1; i++)
                {
                    for (int j = 0; j <= bmp_image.Width - 1; j++)
                    {
                        if (bitmatrix[i, j])
                        {
                            bmp_image.SetPixel(i, j, Color.Black);
                        }
                        else
                        {
                            bmp_image.SetPixel(i, j, Color.White);
                        }
                    }
                }
                Bitmap overlay = new Bitmap(overlayImagePath);

                int deltaHeigth = bmp_image.Height - overlay.Height;
                int deltaWidth  = bmp_image.Width - overlay.Width;

                Graphics g = Graphics.FromImage(bmp_image);
                g.DrawImage(overlay, new Point(deltaWidth / 2, deltaHeigth / 2));

                MemoryStream stream = new MemoryStream();
                bmp_image.Save(stream, System.Drawing.Imaging.ImageFormat.Png);
                byte[] imageBytes = stream.ToArray();
                baseString = Convert.ToBase64String(imageBytes);
                jobj       = new JObject(
                    new JProperty("Success", true),
                    new JProperty("Message", "Success"),
                    new JProperty("ConfCode", conf_code),
                    new JProperty("BaseString", baseString));
            }
            catch (Exception ex)
            {
                HttpContext.Current.Response.Write(ex.ToString());
                jobj = new JObject(new JProperty("Success", false),
                                   new JProperty("Message", "Something Went Wrong"));
            }
            Pusher         pusherObj      = new Pusher("99686", "ed522d982044e2680be6", "2d2388bc3972643d5b5b");
            ITriggerResult PusherResponse = null;

            PusherResponse = pusherObj.Trigger(conf_code, "client-myEvent", new
            {
                AccessToken = "outbound"
            });
            Logger.TraceLog("pusher response :" + PusherResponse.ToString());
            return(jobj);
        }
Beispiel #30
0
        public Bitmap BarEncode(string text, BarcodeFormat barFormat = BarcodeFormat.CODE_128, bool isbn = false)
        {
            var width  = 256;
            var height = 128;
            var margin = 0;

            if (string.IsNullOrEmpty(text))
            {
                return(new Bitmap(width, height));
            }

            string barText = text;
            int    maxText = 16;

            switch (barFormat)
            {
            case BarcodeFormat.CODE_128:
                width   = 256;
                height  = 72;
                margin  = 7;
                maxText = 232;
                break;

            case BarcodeFormat.EAN_13:
                //height = (int) ( width * 25.93 / 37.29 );
                height = (int)(width * 26.26 / 37.29);
                if (isbn)
                {
                    string isbn13 = calcISBN_13(barText);
                    string isbn10 = calcISBN_10(barText);
                    if (string.IsNullOrEmpty(isbn13))
                    {
                        return(new Bitmap(width, height));
                    }
                    //if ( string.IsNullOrEmpty( isbn10 ) ) return ( new Bitmap( width, height ) );
                    barText = isbn13;
                }
                break;

            default:
                return(new Bitmap(width, height));
            }
            var bw = new BarcodeWriter();

            bw.Options.Width  = width;
            bw.Options.Height = height;
            //bw.Options.PureBarcode = false;
            bw.Options.Hints.Add(EncodeHintType.MARGIN, margin);
            bw.Options.Hints.Add(EncodeHintType.DISABLE_ECI, true);
            bw.Options.Hints.Add(EncodeHintType.CHARACTER_SET, "UTF-8");

            bw.Renderer = new BitmapRenderer();
            bw.Format   = barFormat;
            if (barText.Length > maxText)
            {
                barText = barText.Substring(0, maxText);
            }
            try
            {
                BitMatrix bm        = bw.Encode(barText);
                int[]     rectangle = bm.getEnclosingRectangle();
                var       bmW       = rectangle[2];
                var       bmH       = rectangle[3];
                //bw.Options.Width = ( bmW <= 256 ) ? ( bmW + 32 ) : (int)( bmW * ( 1 + 32 / 256 ) );
                bw.Options.Width = (int)(bmW * 1.25);

                Bitmap barcodeBitmap = bw.Write(barText);
                return(barcodeBitmap);
            }
            catch (WriterException)
            {
                MessageBox.Show(this, I18N._("Text data can not be encoded to barcode!"), I18N._("Error"), MessageBoxButtons.OK, MessageBoxIcon.Error);
                return(new Bitmap(width, height));
            }
        }