Beispiel #1
0
        //带LOGO二维码
        private void btnEncodePic_Click(object sender, EventArgs e)
        {
            labShow.Text = "";
            string content = txtMsg.Text.Trim();

            if (String.IsNullOrEmpty(content))
            {
                MessageBox.Show("请输入编码内容");
                return;
            }
            try
            {
                //构造二维码编码器
                MultiFormatWriter writer = new MultiFormatWriter();
                Hashtable         hints  = new Hashtable();
                hints.Add(EncodeHintType.CHARACTER_SET, "UTF-8");
                hints.Add(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.Q);

                //先生成二维码
                ByteMatrix matrix = writer.encode(content, BarcodeFormat.QR_CODE, 300, 300, hints);
                Bitmap     img    = matrix.ToBitmap();

                //再处理要插入到二维码中的图片
                Image middlImg = QRMiddleImg.Image;

                //获取二维码实际尺寸(去掉二维码两边空白后的尺寸)
                Size realSize = writer.GetEncodeSize(content, BarcodeFormat.QR_CODE, 300, 300);

                //计算插入的图片的大小和位置
                int middleImgW = Math.Min((int)(realSize.Width / 4), middlImg.Width);
                int middleImgH = Math.Min((int)(realSize.Height / 4), middlImg.Height);
                int middleImgL = (img.Width - middleImgW) / 2;
                int middleImgT = (img.Height - middleImgH) / 2;

                //将img转换成bmp格式,否则后面无法创建 Graphics对象
                Bitmap bmpimg = new Bitmap(img.Width, img.Height, PixelFormat.Format32bppArgb);
                using (Graphics g = Graphics.FromImage(bmpimg))
                {
                    g.InterpolationMode  = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                    g.SmoothingMode      = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                    g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
                    g.DrawImage(img, 0, 0);
                }

                //在二维码中插入图片
                Graphics MyGraphic = Graphics.FromImage(bmpimg);

                //白底
                MyGraphic.FillRectangle(Brushes.White, middleImgL, middleImgT, middleImgW, middleImgH);
                MyGraphic.DrawImage(middlImg, middleImgL, middleImgT, middleImgW, middleImgH);
                MyGraphic.DrawString(content, this.Font, new SolidBrush(Color.Black), middleImgW * 2 + 20, 300 - middleImgH / 2);
                pictureBox1.Image = bmpimg;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        /// <summary>
        /// 原生支付 模式二
        /// 根据统一订单返回的code_url生成支付二维码。该模式链接较短,生成的二维码打印到结账小票上的识别率较高。
        /// 注意:code_url有效期为2小时,过期后扫码不能再发起支付
        /// </summary>
        /// <returns></returns>
        public ActionResult NativeByCodeUrl()
        {
            //创建支付应答对象
            //RequestHandler packageReqHandler = new RequestHandler(null);

            var sp_billno = DateTime.Now.ToString("HHmmss") + TenPayV3Util.BuildRandomStr(26);
            var nonceStr  = TenPayV3Util.GetNoncestr();

            //商品Id,用户自行定义
            string productId = DateTime.Now.ToString("yyyyMMddHHmmss");

            //创建请求统一订单接口参数
            //packageReqHandler.SetParameter("appid", TenPayV3Info.AppId);
            //packageReqHandler.SetParameter("mch_id", TenPayV3Info.MchId);
            //packageReqHandler.SetParameter("nonce_str", nonceStr);
            //packageReqHandler.SetParameter("body", "test");
            //packageReqHandler.SetParameter("out_trade_no", sp_billno);
            //packageReqHandler.SetParameter("total_fee", "1");
            //packageReqHandler.SetParameter("spbill_create_ip", Request.UserHostAddress);
            //packageReqHandler.SetParameter("notify_url", TenPayV3Info.TenPayV3Notify);
            //packageReqHandler.SetParameter("trade_type", TenPayV3Type.NATIVE.ToString());
            //packageReqHandler.SetParameter("product_id", productId);

            //string sign = packageReqHandler.CreateMd5Sign("key", TenPayV3Info.Key);
            //packageReqHandler.SetParameter("sign", sign);

            //string data = packageReqHandler.ParseXML();
            var xmlDataInfo = new TenPayV3UnifiedorderRequestData(TenPayV3Info.AppId,
                                                                  TenPayV3Info.MchId,
                                                                  "test",
                                                                  sp_billno,
                                                                  1,
                                                                  Request.UserHostAddress,
                                                                  TenPayV3Info.TenPayV3Notify,
                                                                  TenPayV3Type.NATIVE,
                                                                  null,
                                                                  TenPayV3Info.Key,
                                                                  nonceStr,
                                                                  productId: productId);
            //调用统一订单接口
            var result = TenPayV3.Unifiedorder(xmlDataInfo);
            //var unifiedorderRes = XDocument.Parse(result);
            //string codeUrl = unifiedorderRes.Element("xml").Element("code_url").Value;
            string    codeUrl = result.code_url;
            BitMatrix bitMatrix;

            bitMatrix = new MultiFormatWriter().encode(codeUrl, BarcodeFormat.QR_CODE, 600, 600);
            BarcodeWriter bw = new BarcodeWriter();

            var ms     = new MemoryStream();
            var bitmap = bw.Write(bitMatrix);

            bitmap.Save(ms, ImageFormat.Png);
            //return File(ms, "image/png");
            ms.WriteTo(Response.OutputStream);
            Response.ContentType = "image/png";
            return(null);
        }
Beispiel #3
0
    /// <summary>
    /// 显示绘制的二维码,任意尺寸正方形
    /// </summary>
    /// <param name="_str">扫码信息</param>
    Sprite ShowQRCode(string _str, int _width, int _height, Texture2D centerIcon)
    {
        MultiFormatWriter writer = new MultiFormatWriter();
        Dictionary <EncodeHintType, object> hints = new Dictionary <EncodeHintType, object>()
        {
            { EncodeHintType.CHARACTER_SET, "UTF-8" },
            { EncodeHintType.MARGIN, 1 },
            { EncodeHintType.ERROR_CORRECTION, ZXing.QrCode.Internal.ErrorCorrectionLevel.M },
        };
        BitMatrix bitMatrix = writer.encode(_str, BarcodeFormat.QR_CODE, _width, _height, hints);
        int       w         = bitMatrix.Width;
        int       h         = bitMatrix.Height;
        Texture2D texture   = new Texture2D(_width, _height);

        for (int x = 0; x < h; x++)
        {
            for (int y = 0; y < w; y++)
            {
                if (bitMatrix[x, y])
                {
                    texture.SetPixel(y, x, Color.black);
                }
                else
                {
                    texture.SetPixel(y, x, Color.white);
                }
            }
        }

        if (centerIcon != null)
        {
            // 添加小图
            int halfWidth        = texture.width / 2;
            int halfHeight       = texture.height / 2;
            int halfWidthOfIcon  = centerIcon.width / 2;
            int halfHeightOfIcon = centerIcon.height / 2;
            int centerOffsetX    = 0;
            int centerOffsetY    = 0;
            for (int x = 0; x < h; x++)
            {
                for (int y = 0; y < w; y++)
                {
                    centerOffsetX = x - halfWidth;
                    centerOffsetY = y - halfHeight;
                    if (Mathf.Abs(centerOffsetX) <= halfWidthOfIcon && Mathf.Abs(centerOffsetY) <= halfHeightOfIcon)
                    {
                        texture.SetPixel(x, y, centerIcon.GetPixel(centerOffsetX + halfWidthOfIcon, centerOffsetY + halfHeightOfIcon));
                    }
                }
            }
        }

        texture.Apply();
        //创景精灵返回
        return(Sprite.Create(texture, new Rect(0, 0, _width, _height), new Vector2(0.5f, 0.5f)));
    }
Beispiel #4
0
        /// <summary>
        /// 产生条码图片
        /// </summary>
        /// <param name="barCode"></param>
        public Bitmap CreateCode(string codeStr, int width, int height, BarcodeFormat codeFormat)
        {
            // Writer writer = new QRCodeWriter();
            MultiFormatWriter mutiWriter   = new MultiFormatWriter();
            BitMatrix         bm           = mutiWriter.encode(codeStr, codeFormat, width, height);
            Bitmap            imageBarcode = new BarcodeWriter().Write(bm);

            imageBarcode = GetBlackRGB(imageBarcode);
            return(imageBarcode);
        }
Beispiel #5
0
        public static string QrImg(string content, string qrcodeImgPath, int wh, string color, string bgcolor)
        {
            BarcodeWriter writer = new BarcodeWriter();
            BitMatrix     matrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, wh, wh, null);
            Image         image  = Create.toBitmap(matrix, color, bgcolor);

            image.Save(qrcodeImgPath, ImageFormat.Png);
            image.Dispose();
            return(qrcodeImgPath);
        }
Beispiel #6
0
        /// <summary>
        /// 生成二维码
        /// </summary>
        /// <param name="content">二维码的内容</param>
        /// <param name="logo">二维码图标,如果没有则不会生成</param>
        /// <param name="codeMargin">二维码边距</param>
        /// <param name="codeWidth">二维码宽度</param>
        /// <param name="codeHeight">二维码长度</param>
        /// <returns></returns>
        public static Bitmap GenerateQrCode(string content, Bitmap logo, int codeMargin = 1, int codeWidth = 250, int codeHeight = 250)
        {
            //声明二维码生成器
            MultiFormatWriter writer = new MultiFormatWriter();
            //设置生成器的部分参数
            Dictionary <EncodeHintType, object> hints = new Dictionary <EncodeHintType, object>()
            {
                { EncodeHintType.CHARACTER_SET, "UTF-8" },                   //定义二维码字符串编码为UTF-8
                { EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H }, //好像是设置生成器的误差值
                { EncodeHintType.MARGIN, codeMargin },                       //设置二维码边距
                { EncodeHintType.DISABLE_ECI, true },                        //只有使用ISO-8859-1规范才可以不禁用ECI
            };
            //生成二维码
            BitMatrix matrix = writer.encode(content, BarcodeFormat.QR_CODE, codeWidth, codeHeight, hints);
            //声明二维码写入器,将二维码写入到bitmap里
            BarcodeWriter barWriter = new BarcodeWriter();
            Bitmap        result    = barWriter.Write(matrix);//如果没有特殊参数声明,直接用barWriter.Write(content)好像也是可以的

            //插入Logo
            if (logo != null)
            {
                //计算二维码尺寸
                // 第0位:左边距
                // 第1位:上边距
                // 第2位:二维码宽
                // 第3位:二维码高

                //获取二维码矩形区域
                int[] rectangle  = matrix.getEnclosingRectangle();
                int   logoWidth  = Math.Min((int)(rectangle[2] / 3), logo.Width);  //计算logo宽度,并且限制logo最小宽度不能小于二维码宽度的1/3
                int   logoHeight = Math.Min((int)(rectangle[3] / 3), logo.Height); //计算logo高度,并且限制logo最小高度不能小于二维码高度的1/3
                int   logoLeft   = result.Width - logoWidth;                       //计算logo的左边距
                int   logoTop    = result.Height - logoHeight;                     //计算logo的上边距
                //新建一个bitmap用于合并二维码和logo
                Bitmap qrCode = new Bitmap(result.Width, result.Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
                //声明一个GDI+绘图类用来绘制二维码
                using (Graphics graphics = Graphics.FromImage(qrCode))
                {
                    //设置图片的清晰度
                    graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; //高清晰度
                    //设置图片抗锯齿
                    graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;                //高品质的抗锯齿
                    //把二维码画上去作为底色
                    graphics.DrawImage(result, 0, 0, codeWidth, codeHeight);                                    //左边距,上边距为0
                    //在二维码上面再覆盖一层logo
                    //绘制logo的矩形区域
                    graphics.FillRectangle(Brushes.White, logoLeft, logoTop, logoWidth, logoHeight); //矩形填充色为白色,既logo的背景色是白色。
                    //绘制logo
                    graphics.DrawImage(logo, logoLeft, logoTop, logoWidth, logoHeight);
                }
                //覆盖原没有logo的二维码
                result = qrCode;
            }
            return(result);
        }
Beispiel #7
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="content"></param>
        /// <param name="qrcodeImgPath"></param>
        /// <param name="wh"></param>
        /// <param name="centerImg"></param>
        /// <param name="color"></param>
        /// <param name="bgcolor"></param>
        /// <returns></returns>
        public static string QrCodeImg(string content, string qrcodeImgPath, int wh, string centerImg, string color, string bgcolor)
        {
            Color foregroundcolor = (color == null || color == "") ? ColorTranslator.FromHtml("#000000") : ColorTranslator.FromHtml(color);
            Color backgroundcolor = (color == null || color == "") ? Color.Transparent : ColorTranslator.FromHtml(bgcolor);
            //Logo 图片
            Bitmap logo = new Bitmap(centerImg);
            //构造二维码写码器
            MultiFormatWriter writer = new MultiFormatWriter();
            Dictionary <EncodeHintType, object> hint = new Dictionary <EncodeHintType, object>();

            hint.Add(EncodeHintType.CHARACTER_SET, "UTF-8");
            hint.Add(EncodeHintType.ERROR_CORRECTION, ZXing.QrCode.Internal.ErrorCorrectionLevel.H);

            //生成二维码
            BitMatrix     bm            = writer.encode(content, BarcodeFormat.QR_CODE, 300, 300, hint);
            BarcodeWriter barcodeWriter = new BarcodeWriter();

            barcodeWriter.Renderer = new ZXing.Rendering.BitmapRenderer {
                Background = backgroundcolor, Foreground = foregroundcolor
            };                                                                                                                         //设置颜色
            Bitmap map = barcodeWriter.Write(bm);


            //获取二维码实际尺寸(去掉二维码两边空白后的实际尺寸)
            int[] rectangle = bm.getEnclosingRectangle();

            //计算插入图片的大小和位置
            int middleW = Math.Min((int)(rectangle[2] / 3.5), logo.Width);
            int middleH = Math.Min((int)(rectangle[3] / 3.5), logo.Height);
            int middleL = (map.Width - middleW) / 2;
            int middleT = (map.Height - middleH) / 2;

            //将img转换成bmp格式,否则后面无法创建Graphics对象
            Bitmap bmpimg = new Bitmap(map.Width, map.Height, PixelFormat.Format32bppArgb);

            using (Graphics g = Graphics.FromImage(bmpimg))
            {
                g.InterpolationMode  = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                g.SmoothingMode      = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
                g.DrawImage(map, 0, 0);
            }
            //将二维码插入图片
            Graphics myGraphic = Graphics.FromImage(bmpimg);

            //白底
            myGraphic.FillRectangle(Brushes.White, middleL, middleT, middleW, middleH);
            myGraphic.DrawImage(logo, middleL, middleT, middleW, middleH);

            //保存成图片
            bmpimg.Save(qrcodeImgPath, ImageFormat.Png);
            bmpimg.Dispose();
            return(qrcodeImgPath);
        }
Beispiel #8
0
        void setQRcode(string content)
        {
            int           heigth = this.pictureBox1.Height;
            int           width  = this.pictureBox1.Width;
            BarcodeFormat format = BarcodeFormat.QR_CODE;

            ByteMatrix byteMatrix = new MultiFormatWriter().encode(content, format, width, heigth);
            Bitmap     bitmap     = toBitmap(byteMatrix);

            pictureBox1.Image = bitmap;
        }
Beispiel #9
0
        public static string GenerateWithLogo(string path, string str, string logopath, string imgpath)
        {
            var logo_path = DowloadImgByUrl(logopath, imgpath);

            if (logo_path != string.Empty)
            {
                Bitmap logo = new Bitmap(logopath);
                //初始化
                MultiFormatWriter writer = new MultiFormatWriter();
                Dictionary <EncodeHintType, object> hint = new Dictionary <EncodeHintType, object>();
                hint.Add(EncodeHintType.CHARACTER_SET, str);
                hint.Add(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);

                //生成二维码
                BitMatrix     bm            = writer.encode(str, BarcodeFormat.QR_CODE, 150, 150, hint);
                BarcodeWriter barcodeWriter = new BarcodeWriter();
                Bitmap        map           = barcodeWriter.Write(bm);
                //计算尺寸
                int[] rectangle = bm.getEnclosingRectangle();

                if (!string.IsNullOrEmpty(logopath))
                {
                }
                //计算插入Logo的大小位置
                int middleW = Math.Min((int)(rectangle[2] / 3.5), logo.Width);
                int middleH = Math.Min((int)(rectangle[3] / 3.5), logo.Height);
                int middleL = (map.Width - middleW) / 2;
                int middleT = (map.Height - middleH) / 2;

                //将img转换成bmp格式,否则后面无法创建Graphics对象
                Bitmap bmpimg = new Bitmap(map.Width, map.Height, PixelFormat.Format32bppArgb);
                using (Graphics g = Graphics.FromImage(bmpimg))
                {
                    g.InterpolationMode  = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                    g.SmoothingMode      = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                    g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
                    g.DrawImage(map, 0, 0);
                }
                //将二维码插入图片
                Graphics myGraphic = Graphics.FromImage(bmpimg);
                //白底
                myGraphic.FillRectangle(Brushes.White, middleL, middleT, middleW, middleH);
                myGraphic.DrawImage(logo, middleL, middleT, middleW, middleH);

                //保存成图片
                bmpimg.Save(path, System.Drawing.Imaging.ImageFormat.Png);
                return(path);
            }
            else
            {
                return(Generate2Code(path, str));
            }
        }
Beispiel #10
0
        /// <summary>
        /// 生成中间带有图片的二维码图片
        /// </summary>
        /// <param name="contents">要生成二维码包含的信息</param>
        /// <param name="middleImg">要生成到二维码中间的图片</param>
        /// <param name="width">生成的二维码宽度(默认300像素)</param>
        /// <param name="height">生成的二维码高度(默认300像素)</param>
        /// <returns>中间带有图片的二维码</returns>
        public static Bitmap GeneratorQrImage(string contents, Image middleImg, int width = 300, int height = 300)
        {
            if (string.IsNullOrEmpty(contents))
            {
                return(null);
            }
            if (middleImg == null)
            {
                //return null;
                return(GeneratorQrImage(contents));
            }

            //构造二维码写码器
            MultiFormatWriter mutiWriter             = new MultiFormatWriter();
            Dictionary <EncodeHintType, object> hint = new Dictionary <EncodeHintType, object>();

            hint.Add(EncodeHintType.CHARACTER_SET, "UTF-8");
            hint.Add(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
            hint.Add(EncodeHintType.MARGIN, 1);

            //生成二维码
            BitMatrix     bm            = mutiWriter.encode(contents, BarcodeFormat.QR_CODE, width, height, hint);
            BarcodeWriter barcodeWriter = new BarcodeWriter();
            Bitmap        bitmap        = barcodeWriter.Write(bm);

            //获取二维码实际尺寸(去掉二维码两边空白后的实际尺寸)
            int[] rectangle = bm.getEnclosingRectangle();

            //计算插入图片的大小和位置
            int middleImgW = Math.Min((int)(rectangle[2] / 3.5), middleImg.Width);
            int middleImgH = Math.Min((int)(rectangle[3] / 3.5), middleImg.Height);
            int middleImgL = (bitmap.Width - middleImgW) / 2;
            int middleImgT = (bitmap.Height - middleImgH) / 2;

            //将img转换成bmp格式,否则后面无法创建 Graphics对象
            Bitmap bmpimg = new Bitmap(bitmap.Width, bitmap.Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb);

            using (Graphics g = Graphics.FromImage(bmpimg))
            {
                g.InterpolationMode  = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                g.SmoothingMode      = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
                g.DrawImage(bitmap, 0, 0);
            }

            //在二维码中插入图片
            Graphics myGraphic = Graphics.FromImage(bmpimg);

            //白底
            myGraphic.FillRectangle(Brushes.White, middleImgL, middleImgT, middleImgW, middleImgH);
            myGraphic.DrawImage(middleImg, middleImgL, middleImgT, middleImgW, middleImgH);
            return(bmpimg);
        }
        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                string content = textBox1.Text;
                if (content == null || content.Length <= 0)
                {
                    return;
                }
                int           heigth = (int)this.numericHeigth.Value;
                int           width  = (int)this.numericWidth.Value;
                BarcodeFormat format = BarcodeFormat.QR_CODE;
                switch (this.comboBox1.SelectedIndex)
                {
                case 1:
                    format = BarcodeFormat.PDF417;
                    break;

                case 2:
                    format = BarcodeFormat.DATAMATRIX;
                    break;
                }
                ByteMatrix byteMatrix = new MultiFormatWriter().encode(content, format, width, heigth);
                Bitmap     bitmap     = toBitmap(byteMatrix);
                pictureBox1.Image = bitmap;
            }
            catch (System.Exception ex)
            {
                MessageBox.Show("编码出现异常,可能不支持此编码!", "提示");
            }


            //writeToFile(byteMatrix, System.Drawing.Imaging.ImageFormat.Png, sFD.FileName);

            //SaveFileDialog sFD = new SaveFileDialog();
            //sFD.DefaultExt = "*.png|*.png";
            //sFD.AddExtension = true;
            //try
            //{
            //    if (sFD.ShowDialog() == DialogResult.OK)
            //    {



            //    }

            //}
            //catch (Exception ex)
            //{
            //    MessageBox.Show(ex.Message);

            //}
        }
Beispiel #12
0
        public static Bitmap createQRCode(String strCode, int widthAndHeight)
        {
            MultiFormatWriter mfwr   = new MultiFormatWriter();
            ByteMatrix        matrix = mfwr.encode(strCode, BarcodeFormat.QR_CODE, widthAndHeight, widthAndHeight);

            if (matrix != null)
            {
                Bitmap bitmap = matrix.ToBitmap();
                return(bitmap);
            }
            return(null);
        }
    /// <summary>
    /// 生成中心带有小图标二维码
    /// </summary>
    /// <param name="content"></param>
    /// <param name="width"></param>
    /// <param name="height"></param>
    /// <param name="centerIcon"></param>
    /// <returns></returns>
    public Texture2D GenerateQRImageWithIcon(string content, int width, int height, Texture2D centerIcon)
    {
        // 编码成color32
        MultiFormatWriter writer = new MultiFormatWriter();
        Dictionary <EncodeHintType, object> hints = new Dictionary <EncodeHintType, object>();

        hints.Add(EncodeHintType.CHARACTER_SET, "UTF-8");
        hints.Add(EncodeHintType.MARGIN, 1);
        hints.Add(EncodeHintType.ERROR_CORRECTION, ZXing.QrCode.Internal.ErrorCorrectionLevel.H);
        BitMatrix bitMatrix = writer.encode(content, BarcodeFormat.QR_CODE, width, height, hints);
        // 转成texture2d
        int       w       = bitMatrix.Width;
        int       h       = bitMatrix.Height;
        Texture2D texture = new Texture2D(w, h);

        for (int x = 0; x < h; x++)
        {
            for (int y = 0; y < w; y++)
            {
                if (bitMatrix[x, y])
                {
                    texture.SetPixel(y, x, Color.black);
                }
                else
                {
                    texture.SetPixel(y, x, Color.white);
                }
            }
        }
        // 添加小图
        int halfWidth        = texture.width / 2;
        int halfHeight       = texture.height / 2;
        int halfWidthOfIcon  = centerIcon.width / 2;
        int halfHeightOfIcon = centerIcon.height / 2;
        int centerOffsetX    = 0;
        int centerOffsetY    = 0;

        for (int x = 0; x < h; x++)
        {
            for (int y = 0; y < w; y++)
            {
                centerOffsetX = x - halfWidth;
                centerOffsetY = y - halfHeight;
                if (Mathf.Abs(centerOffsetX) <= halfWidthOfIcon && Mathf.Abs(centerOffsetY) <= halfHeightOfIcon)
                {
                    texture.SetPixel(x, y, centerIcon.GetPixel(centerOffsetX + halfWidthOfIcon, centerOffsetY + halfHeightOfIcon));
                }
            }
        }
        texture.Apply();
        return(texture);
    }
Beispiel #14
0
        /// <summary>
        /// 原生支付 模式一
        /// </summary>
        /// <returns></returns>
        public ActionResult Native()
        {
            try
            {
                RequestHandler nativeHandler = new RequestHandler(null);
                string         timeStamp     = TenPayV3Util.GetTimestamp();
                string         nonceStr      = TenPayV3Util.GetNoncestr();

                //商品Id,用户自行定义
                string productId = SystemTime.Now.ToString("yyyyMMddHHmmss");

                nativeHandler.SetParameter("appid", TenPayV3Info.AppId);
                nativeHandler.SetParameter("mch_id", TenPayV3Info.MchId);
                nativeHandler.SetParameter("time_stamp", timeStamp);
                nativeHandler.SetParameter("nonce_str", nonceStr);
                nativeHandler.SetParameter("product_id", productId);
                string sign = nativeHandler.CreateMd5Sign("key", TenPayV3Info.Key);

                var url = TenPayOldV3.NativePay(TenPayV3Info.AppId, timeStamp, TenPayV3Info.MchId, nonceStr, productId, sign);

                BitMatrix bitMatrix;
                bitMatrix = new MultiFormatWriter().encode(url, BarcodeFormat.QR_CODE, 600, 600);
                var bw = new ZXing.BarcodeWriterPixelData();

                var pixelData = bw.Write(bitMatrix);
                var bitmap    = new System.Drawing.Bitmap(pixelData.Width, pixelData.Height, System.Drawing.Imaging.PixelFormat.Format32bppRgb);

                var fileStream = new MemoryStream();

                var bitmapData = bitmap.LockBits(new System.Drawing.Rectangle(0, 0, pixelData.Width, pixelData.Height), System.Drawing.Imaging.ImageLockMode.WriteOnly, System.Drawing.Imaging.PixelFormat.Format32bppRgb);
                try
                {
                    // we assume that the row stride of the bitmap is aligned to 4 byte multiplied by the width of the image
                    System.Runtime.InteropServices.Marshal.Copy(pixelData.Pixels, 0, bitmapData.Scan0, pixelData.Pixels.Length);
                }
                finally
                {
                    bitmap.UnlockBits(bitmapData);
                }
                bitmap.Save(_fileStream, System.Drawing.Imaging.ImageFormat.Png);
                _fileStream.Seek(0, SeekOrigin.Begin);

                return(File(_fileStream, "image/png"));
            }
            catch (Exception ex)
            {
                SenparcTrace.SendCustomLog("TenPayV3.Native 执行出错", ex.Message);
                SenparcTrace.BaseExceptionLog(ex);

                throw;
            }
        }
Beispiel #15
0
        private void CreateQRCodeByZXingAPI()
        {
            int        intWidth = 300;
            ByteMatrix byteMatrix;

            if (rdbManualSize.Checked)
            {
                intWidth = (int)nudManualSize.Value;
            }
            else if (rdb80.Checked)
            {
                intWidth = 80;
            }
            else if (rdb100.Checked)
            {
                intWidth = 100;
            }
            else if (rdb125.Checked)
            {
                intWidth = 125;
            }
            else if (rdb200.Checked)
            {
                intWidth = 200;
            }
            else if (rdb250.Checked)
            {
                intWidth = 250;
            }
            else if (rdb300.Checked)
            {
                intWidth = 300;
            }
            else if (rdb400.Checked)
            {
                intWidth = 400;
            }
            else if (rdb500.Checked)
            {
                intWidth = 500;
            }

            try
            {
                byteMatrix    = new MultiFormatWriter().encode(txtText.Text, BarcodeFormat.QR_CODE, intWidth, intWidth);
                picCode.Image = byteMatrix.ToBitmap();
            }
            catch (Exception)
            {
                picCode.Image = picCode.ErrorImage;
            }
        }
Beispiel #16
0
        private void button1_Click(object sender, EventArgs e)
        {
            MultiFormatWriter mutiWriter = new MultiFormatWriter();
            BitMatrix         bm         = mutiWriter.encode("http://www.vgo2013.com/WebService/QR.aspx?ID=" + "111111", BarcodeFormat.QR_CODE, 300, 300);

            ZXing.Rendering.BitmapRenderer br = new ZXing.Rendering.BitmapRenderer();
            Bitmap img = br.Render(bm, BarcodeFormat.QR_CODE, "http://www.vgo2013.com/WebService/QR.aspx?ID=" + "111111");

            img = KiResizeImage(img, 90, 90, 0);
            string filename = System.Environment.CurrentDirectory + "\\QR" + DateTime.Now.Ticks.ToString() + ".jpg";

            img.Save(filename, System.Drawing.Imaging.ImageFormat.Jpeg);
        }
Beispiel #17
0
        /// <summary>
        /// 生成带Logo的二维码
        /// </summary>
        /// <param name="_text">文本内容</param>
        /// <param name="_logoPath">Logo路径</param>
        /// <param name="_codeSize">二维码大小</param>
        /// <param name="_codeMargin">边框大小</param>
        /// <returns></returns>
        public static Bitmap GenWithLogo(string _text, string _logoPath, int _codeSize, int _codeMargin, Color _colorBack, Color _colorFront)
        {
            //Logo 图片
            Bitmap logo = new Bitmap(_logoPath);
            //构造二维码写码器
            MultiFormatWriter writer = new MultiFormatWriter();
            Dictionary <EncodeHintType, object> hint = new Dictionary <EncodeHintType, object>();

            hint.Add(EncodeHintType.CHARACTER_SET, "UTF-8");
            hint.Add(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);


            //生成二维码
            BitMatrix     bm            = writer.encode(_text, BarcodeFormat.QR_CODE, _codeSize, _codeSize, hint);
            BarcodeWriter barcodeWriter = new BarcodeWriter();

            barcodeWriter.Options.Margin = _codeMargin;
            barcodeWriter.Renderer       = new ZXing.Rendering.BitmapRenderer {
                Background = _colorBack, Foreground = _colorFront
            };
            Bitmap map = barcodeWriter.Write(bm);


            //获取二维码实际尺寸(去掉二维码两边空白后的实际尺寸)
            int[] rectangle = bm.getEnclosingRectangle();

            //计算插入图片的大小和位置
            int middleW = Math.Min((int)(rectangle[2] / 3.5), logo.Width);
            int middleH = Math.Min((int)(rectangle[3] / 3.5), logo.Height);
            int middleL = (map.Width - middleW) / 2;
            int middleT = (map.Height - middleH) / 2;

            //将img转换成bmp格式,否则后面无法创建Graphics对象
            Bitmap bmpimg = new Bitmap(map.Width, map.Height, PixelFormat.Format32bppArgb);

            using (Graphics g = Graphics.FromImage(bmpimg))
            {
                g.InterpolationMode  = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                g.SmoothingMode      = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
                g.DrawImage(map, 0, 0);
            }
            //将二维码插入图片
            Graphics myGraphic = Graphics.FromImage(bmpimg);

            //白底
            myGraphic.FillRectangle(Brushes.White, middleL, middleT, middleW, middleH);
            myGraphic.DrawImage(logo, middleL, middleT, middleW, middleH);

            return(bmpimg);
        }
Beispiel #18
0
        private void OnCameraAwaitSessionName()
        {
            _cameraConnect.Text = ViewModel.CameraAwaitSessionName;

            if (string.IsNullOrWhiteSpace(ViewModel.CameraAwaitSessionName))
            {
                _initialLayout.Visibility     = ViewStates.Visible;
                _cameraAwaitLayout.Visibility = ViewStates.Gone;
            }
            else
            {
                _initialLayout.Visibility     = ViewStates.Gone;
                _cameraAwaitLayout.Visibility = ViewStates.Visible;
                Title = "Connect RC to a session";

                try
                {
                    BitMatrix bitmapMatrix = null;
                    var       message      = _cameraConnect.Text;
                    bitmapMatrix = new MultiFormatWriter().encode(message, BarcodeFormat.QR_CODE, 660, 660);

                    var   width       = bitmapMatrix.Width;
                    var   height      = bitmapMatrix.Height;
                    int[] pixelsImage = new int[width * height];

                    for (int i = 0; i < height; i++)
                    {
                        for (int j = 0; j < width; j++)
                        {
                            if (bitmapMatrix[j, i])
                            {
                                pixelsImage[i * width + j] = (int)Convert.ToInt64(0xff000000);
                            }
                            else
                            {
                                pixelsImage[i * width + j] = (int)Convert.ToInt64(0xffffffff);
                            }
                        }
                    }

                    Bitmap bitmap = Bitmap.CreateBitmap(width, height, Bitmap.Config.Argb8888);
                    bitmap.SetPixels(pixelsImage, 0, width, 0, 0, width, height);

                    _barcodeImage.SetImageBitmap(bitmap);
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"Exception {ex} ");
                }
            }
        }
        /// <summary>
        /// 创建带图片的二维码
        /// </summary>
        /// <param name="message">信息</param>
        /// <param name="middleImg">图片</param>
        /// <param name="pixel">大小</param>
        /// <returns></returns>
        private Bitmap CreateQrCode(string message, string imagePath, int pixel)
        {
            using (Image middleImg = new Bitmap(imagePath))
            {
                //构造二维码写码器
                MultiFormatWriter mutiWriter = new MultiFormatWriter();
                Dictionary <EncodeHintType, object> encodeHint = new Dictionary <EncodeHintType, object>();
                encodeHint.Add(EncodeHintType.CHARACTER_SET, "UTF-8");
                encodeHint.Add(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);

                //生成二维码
                BitMatrix bitMatrix = mutiWriter.encode(message, BarcodeFormat.QR_CODE, pixel, pixel, encodeHint);
                ZKWebNet.BarcodeWriter barcodeWriter = new ZKWebNet.BarcodeWriter();

                Bitmap bitmap = barcodeWriter.Write(bitMatrix);

                //获取二维码实际尺寸(去掉二维码两边空白后的实际尺寸)
                int[] rectangle = bitMatrix.getEnclosingRectangle();

                //计算插入图片的大小和位置
                int middleImgW = Math.Min((int)(rectangle[2] / 3.5), middleImg.Width);
                int middleImgH = Math.Min((int)(rectangle[3] / 3.5), middleImg.Height);
                int middleImgL = (bitmap.Width - middleImgW) / 2;
                int middleImgT = (bitmap.Height - middleImgH) / 2;

                //将img转换成bmp格式,否则后面无法创建 Graphics对象
                Bitmap bmpimg = new Bitmap(bitmap.Width, bitmap.Height, PixelFormat.Format32bppArgb);

                using (Graphics graphics = Graphics.FromImage(bmpimg))
                {
                    graphics.InterpolationMode  = InterpolationMode.HighQualityBicubic;
                    graphics.SmoothingMode      = SmoothingMode.HighQuality;
                    graphics.CompositingQuality = CompositingQuality.HighQuality;
                    graphics.DrawImage(bitmap, 0, 0);
                }

                //在二维码中插入图片
                using (Graphics myGraphic = Graphics.FromImage(bmpimg))
                {
                    //白底
                    myGraphic.FillRectangle(Brushes.White, middleImgL, middleImgT, middleImgW, middleImgH);

                    myGraphic.DrawImage(middleImg, middleImgL, middleImgT, middleImgW, middleImgH);
                }

                bitmap.Dispose();

                return(bmpimg);
            }
        }
Beispiel #20
0
        /// <summary>
        /// 创建二维码
        /// </summary>
        /// <param name="msg">二维码中保存的信息</param>
        /// <returns></returns>
        public static Bitmap Create(string msg)
        {
            var writer = new MultiFormatWriter();
            var hint   = new Dictionary <EncodeHintType, object>();

            //设置二维码为utf-8编码
            hint.Add(EncodeHintType.CHARACTER_SET, "utf-8");
            //设置纠错等级, 高
            hint.Add(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
            var bm            = writer.encode(msg, BarcodeFormat.QR_CODE, 200, 200, hint);
            var barcodeWriter = new BarcodeWriter();

            return(barcodeWriter.Write(bm));
        }
Beispiel #21
0
        /// <summary>
        /// 生成二维码,返回位图
        /// </summary>
        /// <param name="input">输入的需要编码的信息字符串</param>
        /// <param name="fromat">二维码格式</param>
        /// <param name="CanvasWidth">画布宽度</param>
        /// <param name="CanvasHeight">画布高度</param>
        /// <param name="imageFormat">图像格式</param>
        /// <param name="logoImageFileName">中间嵌入的 Logo 图片</param>
        /// <returns></returns>
        public static Bitmap CreateCode(string input, BarcodeFormat fromat, int CanvasWidth, int CanvasHeight, System.Drawing.Imaging.ImageFormat imageFormat, string logoImageFileName)
        {
            System.Collections.Hashtable hints = new System.Collections.Hashtable();
            hints.Add(EncodeHintType.CHARACTER_SET, "utf-8");

            ByteMatrix byteMatrix = new MultiFormatWriter().encode(input, fromat, CanvasWidth, CanvasHeight, hints);

            int x, y;
            int width  = byteMatrix.Width;
            int height = byteMatrix.Height;

            Bitmap bmap = new Bitmap(width, height, System.Drawing.Imaging.PixelFormat.Format32bppArgb);

            for (x = 0; x < width; x++)
            {
                for (y = 0; y < height; y++)
                {
                    bmap.SetPixel(x, y, byteMatrix.get_Renamed(x, y) != -1 ? ColorTranslator.FromHtml("0xFF000000") : ColorTranslator.FromHtml("0xFFFFFFFF"));
                }
            }

            if (String.IsNullOrEmpty(logoImageFileName.Trim()) || (!System.IO.File.Exists(logoImageFileName)))
            {
                return(bmap);
            }

            // 加图片水印
            System.Drawing.Image    logo = System.Drawing.Image.FromFile(logoImageFileName);
            System.Drawing.Graphics g    = System.Drawing.Graphics.FromImage(bmap);

            // 设置高质量插值法
            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
            // 设置高质量,低速度呈现平滑程度
            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;

            // 清空画布并以透明背景色填充
            //g.Clear(System.Drawing.Color.Transparent);

            // 计算 Logo 的范围
            x = (width - logo.Width) / 2;
            y = (height - logo.Height) / 2;

            //在指定位置并且按指定大小绘制原图片的指定部分
            g.DrawImage(logo, new System.Drawing.Rectangle(x, y, logo.Width, logo.Height), 0, 0, logo.Width, logo.Height, System.Drawing.GraphicsUnit.Pixel);

            logo.Dispose();
            g.Dispose();

            return(bmap);
        }
        /// <summary>
        /// 生成二维码并添加Logo
        /// 注:自定义边长以及颜色
        /// </summary>
        /// <param name="content">二维码内容</param>
        /// <param name="imgSize">二维码边长px</param>
        /// <param name="background">二维码底色</param>
        /// <param name="foreground">二维码前景色</param>
        /// <param name="logo">logo图片</param>
        /// <returns></returns>
        public static Image BuildQRCode_Logo(string content, int imgSize, Color background, Color foreground, Image logo)
        {
            //构造二维码写码器
            MultiFormatWriter writer = new MultiFormatWriter();
            Dictionary <EncodeHintType, object> hint = new Dictionary <EncodeHintType, object>
            {
                { EncodeHintType.CHARACTER_SET, "UTF-8" },
                { EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H }
            };

            //生成二维码
            BitMatrix     bm            = writer.encode(content, BarcodeFormat.QR_CODE, imgSize, imgSize, hint);
            BarcodeWriter barcodeWriter = new BarcodeWriter()
            {
                Renderer = new BitmapRenderer {
                    Background = background, Foreground = foreground
                },
                Format = BarcodeFormat.QR_CODE
            };
            Bitmap map = barcodeWriter.Write(bm);

            //获取二维码实际尺寸(去掉二维码两边空白后的实际尺寸)
            int[] rectangle = bm.getEnclosingRectangle();

            //计算插入图片的大小和位置
            int middleW = Math.Min((int)(rectangle[2] / 3.5), logo.Width);
            int middleH = Math.Min((int)(rectangle[3] / 3.5), logo.Height);
            int middleL = (map.Width - middleW) / 2;
            int middleT = (map.Height - middleH) / 2;

            //将img转换成bmp格式,否则后面无法创建Graphics对象
            Bitmap bmpimg = new Bitmap(map.Width, map.Height, PixelFormat.Format32bppArgb);

            using (Graphics g = Graphics.FromImage(bmpimg))
            {
                g.InterpolationMode  = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                g.SmoothingMode      = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
                g.DrawImage(map, 0, 0);
            }
            //将二维码插入图片
            Graphics myGraphic = Graphics.FromImage(bmpimg);

            //白底
            myGraphic.FillRectangle(Brushes.White, middleL, middleT, middleW, middleH);
            myGraphic.DrawImage(logo, middleL, middleT, middleW, middleH);

            return(bmpimg);
        }
Beispiel #23
0
        public static Bitmap Encode(string content, int width = 350, int height = 350)
        {
            com.google.zxing.common.ByteMatrix byteMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height);
            int    matrixWidth  = byteMatrix.Width;
            int    matrixHeight = byteMatrix.Height;
            Bitmap bmap         = new Bitmap(width, height, System.Drawing.Imaging.PixelFormat.Format32bppArgb);

            for (int x = 0; x < width; x++)
            {
                for (int y = 0; y < height; y++)
                {
                    bmap.SetPixel(x, y, byteMatrix.get_Renamed(x, y) != -1 ? ColorTranslator.FromHtml("0xFF000000") : ColorTranslator.FromHtml("0xFFFFFFFF"));
                }
            }
            return(bmap);
        }
Beispiel #24
0
        public static MemoryStream GetMa(string content)
        {
            ByteMatrix byteMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, 350, 350);

            //writeToFile(byteMatrix, System.Drawing.Imaging.ImageFormat.Png, "wjg2");
            System.Drawing.Bitmap  Img = toBitmap(byteMatrix);
            System.IO.MemoryStream ms  = new System.IO.MemoryStream();
            Img.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
            Img.Dispose();
            return(ms);
            //Response.ClearContent();   //需要输出图象信息   要修改HTTP头
            //Response.ContentType = "image/Png ";
            //Response.BinaryWrite(ms.ToArray());

            //Response.End();
        }
Beispiel #25
0
        /// <summary>
        /// 创建二维码
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string Generate2Code(string path, string str)
        {
            Dictionary <EncodeHintType, Object> hints = new Dictionary <EncodeHintType, Object>();

            hints.Add(EncodeHintType.CHARACTER_SET, "utf-8");
            hints.Add(EncodeHintType.MARGIN, 0);
            string    codeUrl = str;
            BitMatrix bitMatrix;

            bitMatrix = new MultiFormatWriter().encode(codeUrl, BarcodeFormat.QR_CODE, 150, 150, hints);
            BarcodeWriter bw     = new BarcodeWriter();
            var           bitmap = bw.Write(bitMatrix);

            bitmap.Save(path, ImageFormat.Png);
            return(path);
        }
Beispiel #26
0
        public ActionResult getPageqr(string pageurl)
        {
            BitMatrix bitMatrix;

            bitMatrix = new MultiFormatWriter().encode(pageurl, BarcodeFormat.QR_CODE, 600, 600);
            BarcodeWriter bw = new BarcodeWriter();

            var ms     = new MemoryStream();
            var bitmap = bw.Write(bitMatrix);

            bitmap.Save(ms, ImageFormat.Png);
            //return File(ms, "image/png");
            ms.WriteTo(Response.OutputStream);
            Response.ContentType = "image/png";
            return(null);
        }
Beispiel #27
0
    void Start()
    {
        //设置二维码大小
        encoded = new Texture2D(512, 512);
        //二维码边框
        BitMatrix BIT;
        //设置二维码扫描结果
        string name = "毛为名—www-B747";

        Dictionary <EncodeHintType, object> hints = new Dictionary <EncodeHintType, object>();

        //设置编码方式
        hints.Add(EncodeHintType.CHARACTER_SET, "UTF-8");


        BIT = new MultiFormatWriter().encode(name, BarcodeFormat.QR_CODE, 512, 512, hints);
        int width  = BIT.Width;
        int height = BIT.Width;

        if (name != null)
        {
            for (int x = 0; x < height; x++)
            {
                for (int y = 0; y < width; y++)
                {
                    if (BIT[x, y])
                    {
                        encoded.SetPixel(y, x, Color.black);
                    }
                    else
                    {
                        encoded.SetPixel(y, x, Color.white);
                    }
                }
            }


            encoded.Apply();
            byte[] bytes = encoded.EncodeToPNG();
            if (!Directory.Exists(Application.dataPath + "/AdamBieber")) //创建生成目录,如果不存在则创建目录
            {
                Directory.CreateDirectory(Application.dataPath + "/AdamBieber");
            }
            string fileName = Application.dataPath + "/AdamBieber/" + name + ".png";
            System.IO.File.WriteAllBytes(fileName, bytes);
        }
    }
Beispiel #28
0
        /// <summary>
        /// 生成二维码的bitmap
        /// </summary>
        /// <param name="content"></param>
        /// <param name="size"></param>
        /// <param name="img_path"></param>
        /// <returns></returns>
        private Bitmap GetBitmap(string content, int size = 230, string img_path = null)
        {
            content = ConvertHelper.GetString(content);

            var writer = new MultiFormatWriter();
            //参数(如果不把容错能力设置高一些,添加logo后就无法识别)
            var hints = new Hashtable();

            hints.Add(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H); //容错能力
            hints.Add(EncodeHintType.CHARACTER_SET, "UTF-8");                   //字符集
            var byteMatrix = writer.encode(content, BarcodeFormat.QR_CODE, size, size, hints);
            //生成bitmap
            var bm = byteMatrix.ToBitmap();

            /*
             * var bm = new Bitmap(size, size, PixelFormat.Format32bppArgb);
             * for (int x = 0; x < size; ++x)
             * {
             *  for (int y = 0; y < size; ++y)
             *  {
             *      bm.SetPixel(x, y, byteMatrix.get_Renamed(x, y) != -1 ? Color.Black : Color.White);
             *  }
             * }
             */
            //如果有小图片就绘制
            if (ValidateHelper.IsPlumpString(img_path))
            {
                if (!File.Exists(img_path))
                {
                    throw new Exception("二维码水印图片不存在");
                }
                //如果图片已经有被索引的像素,就删除原来的bm,重新生成
                bm = ImageHelper.RemovePixelIndexed(bm);
                using (var g = Graphics.FromImage(bm))
                {
                    using (var logo = Image.FromFile(img_path))
                    {
                        using (var smallLogo = logo.GetThumbnailImage(bm.Width / 5, bm.Height / 5, null, IntPtr.Zero))
                        {
                            //把压缩后的图片绘制到二维码上
                            g.DrawImage(smallLogo, (bm.Width - smallLogo.Width) / 2, (bm.Height - smallLogo.Height) / 2);
                        }
                    }
                }
            }
            return(bm);
        }
Beispiel #29
0
        /// <summary>
        /// 构建 二维码图片
        /// </summary>
        /// <param name="content">内容</param>
        /// <param name="width">宽</param>
        /// <param name="height">高</param>
        /// <param name="midImg">中心图</param>
        /// <returns></returns>
        public static Bitmap Encode(string content, int width = 430, int height = 430, Image midImg = null)
        {
            //构造二维码写码器
            var mutiWriter = new MultiFormatWriter();
            var hint       = new Hashtable
            {
                { EncodeHintType.CHARACTER_SET, "UTF-8" },
                { EncodeHintType.ERROR_CORRECTION, com.google.zxing.qrcode.decoder.ErrorCorrectionLevel.H }
            };
            //生成二维码
            var bm  = mutiWriter.encode(content, BarcodeFormat.QR_CODE, width, height, hint);
            var img = bm.ToBitmap();

            if (midImg == null)
            {
                return(img);
            }

            var middlImg = midImg;
            //获取二维码实际尺寸(去掉二维码两边空白后的实际尺寸)
            var realSize = mutiWriter.GetEncodeSize(content, BarcodeFormat.QR_CODE, width, height);
            //计算插入图片的大小和位置
            var middleImgW = Math.Min((int)(realSize.Width / 3.5), middlImg.Width);
            var middleImgH = Math.Min((int)(realSize.Height / 3.5), middlImg.Height);
            var middleImgL = (img.Width - middleImgW) / 2;
            var middleImgT = (img.Height - middleImgH) / 2;

            //将img转换成bmp格式,否则后面无法创建 Graphics对象
            var bmpimg = new Bitmap(img.Width, img.Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb);

            using (var g = Graphics.FromImage(bmpimg))
            {
                g.InterpolationMode  = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                g.SmoothingMode      = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
                g.DrawImage(img, 0, 0);
            };

            //在二维码中插入图片
            var MyGraphic = Graphics.FromImage(bmpimg);

            //白底
            MyGraphic.FillRectangle(Brushes.White, middleImgL, middleImgT, middleImgW, middleImgH);
            MyGraphic.DrawImage(middlImg, middleImgL, middleImgT, middleImgW, middleImgH);

            return(bmpimg);
        }
Beispiel #30
0
        /// <summary>
        /// 创建包含logo的二维码
        /// </summary>
        /// <param name="text"></param>
        public static void MakeWithLogo(string text)
        {
            //Logo 图片
            Bitmap logo = new Bitmap(Logo);
            //构造二维码写码器
            MultiFormatWriter writer = new MultiFormatWriter();
            Dictionary <EncodeHintType, object> hint = new Dictionary <EncodeHintType, object>();

            hint.Add(EncodeHintType.CHARACTER_SET, "UTF-8");
            hint.Add(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);

            //生成二维码
            BitMatrix     bm            = writer.encode(text, BarcodeFormat.QR_CODE, 500, 500, hint);
            BarcodeWriter barcodeWriter = new BarcodeWriter();
            Bitmap        map           = barcodeWriter.Write(bm);

            //获取二维码实际尺寸(去掉二维码两边空白后的实际尺寸)
            int[] rectangle = bm.getEnclosingRectangle();

            //计算插入图片的大小和位置
            int middleW = Math.Min((int)(rectangle[2] / 3.5), logo.Width);
            int middleH = Math.Min((int)(rectangle[3] / 3.5), logo.Height);
            int middleL = (map.Width - middleW) / 2;
            int middleT = (map.Height - middleH) / 2;

            //将img转换成bmp格式,否则后面无法创建Graphics对象
            Bitmap bmpimg = new Bitmap(map.Width, map.Height, PixelFormat.Format32bppArgb);

            using (Graphics g = Graphics.FromImage(bmpimg))
            {
                g.InterpolationMode  = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                g.SmoothingMode      = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
                g.DrawImage(map, 0, 0);
            }
            //将二维码插入图片
            Graphics myGraphic = Graphics.FromImage(bmpimg);

            //白底
            myGraphic.FillRectangle(Brushes.White, middleL, middleT, middleW, middleH);
            myGraphic.DrawImage(logo, middleL, middleT, middleW, middleH);

            //保存成图片
            string filename = Path.Combine(SavePath, text + ".png");

            bmpimg.Save(filename, ImageFormat.Png);
        }
 public barcodeCreator()
 {
     barcodeReader = new MultiFormatReader();
     barcodeWriter = new MultiFormatWriter();
 }