Ejemplo n.º 1
0
        public async Task <Tuple <bool, string> > PagePay(string body, string outTradeNo, int totalFee, string productId)
        {
            try
            {
                var nativePay = new NativePay();
                //生成扫码支付模式二url
                var url2 = await nativePay.GetPayUrl(body, outTradeNo, totalFee, productId);

                //将url生成二维码图片
                var writerSvg = new BarcodeWriterSvg
                {
                    Format  = BarcodeFormat.QR_CODE,
                    Options = new QrCodeEncodingOptions
                    {
                        ErrorCorrection = ErrorCorrectionLevel.H
                    }
                };
                var svgImageData = writerSvg.Write(url2);
                return(svgImageData == null
                    ? new Tuple <bool, string>(false, "返回数据为空!")
                    : new Tuple <bool, string>(true, svgImageData.ToString()));
            }
            catch (Exception e)
            {
                return(new Tuple <bool, string>(false, e.Message));
            }
        }
Ejemplo n.º 2
0
        private void btnEncoderSave_Click(object sender, EventArgs e)
        {
            if (picEncodedBarCode.Image != null)
            {
                var fileName = String.Empty;
                using (var dlg = new SaveFileDialog())
                {
                    dlg.DefaultExt = "png";
                    dlg.Filter     = "PNG Files (*.png)|*.png|SVG Files (*.svg)|*.svg|BMP Files (*.bmp)|*.bmp|TIFF Files (*.tif)|*.tif|JPG Files (*.jpg)|*.jpg|All Files (*.*)|*.*";
                    if (dlg.ShowDialog(this) != DialogResult.OK)
                    {
                        return;
                    }
                    fileName = dlg.FileName;
                }
                var extension = Path.GetExtension(fileName).ToLower();
                var bmp       = (Bitmap)picEncodedBarCode.Image;
                switch (extension)
                {
                case ".bmp":
                    bmp.Save(fileName, ImageFormat.Bmp);
                    break;

                case ".jpeg":
                case ".jpg":
                    bmp.Save(fileName, ImageFormat.Jpeg);
                    break;

                case ".tiff":
                case ".tif":
                    bmp.Save(fileName, ImageFormat.Tiff);
                    break;

                case ".svg":
                {
                    var writer = new BarcodeWriterSvg
                    {
                        Format  = (BarcodeFormat)cmbEncoderType.SelectedItem,
                        Options = EncodingOptions ?? new EncodingOptions
                        {
                            Height = picEncodedBarCode.Height,
                            Width  = picEncodedBarCode.Width
                        }
                    };
                    var svgImage = writer.Write(txtEncoderContent.Text);
                    File.WriteAllText(fileName, svgImage.Content, System.Text.Encoding.UTF8);
                }
                break;

                default:
                    bmp.Save(fileName, ImageFormat.Png);
                    break;
                }
            }
        }
Ejemplo n.º 3
0
        private string GetBarCode(string plateName)
        {
            var writer = new BarcodeWriterSvg
            {
                Format  = BarcodeFormat.CODE_128,
                Options = new ZXing.Common.EncodingOptions
                {
                    Width  = 200,
                    Height = 100
                }
            };

            return(writer.Write(plateName).Content);
        }
Ejemplo n.º 4
0
        public Task OnLoadAsync(Kernel kernel)
        {
            Formatter <Result> .Register((result, writer) =>
            {
                var barcodeWriter = new BarcodeWriterSvg
                {
                    Format  = result.BarcodeFormat,
                    Options = new EncodingOptions
                    {
                        Height = 300,
                        Width  = 600
                    }
                };

                writer.Write(barcodeWriter.Write(result.Text).Content);
            }, HtmlFormatter.MimeType);

            return(Task.CompletedTask);
        }
Ejemplo n.º 5
0
        private void tsmiSaveAs_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(txtQRCode.Text))
            {
                using (SaveFileDialog saveFileDialog = new SaveFileDialog())
                {
                    saveFileDialog.Filter     = @"PNG (*.png)|*.png|JPEG (*.jpg)|*.jpg|Bitmap (*.bmp)|*.bmp|SVG (*.svg)|*.svg";
                    saveFileDialog.FileName   = txtQRCode.Text;
                    saveFileDialog.DefaultExt = "png";

                    if (saveFileDialog.ShowDialog() == DialogResult.OK)
                    {
                        string filePath = saveFileDialog.FileName;

                        if (filePath.EndsWith("svg", StringComparison.InvariantCultureIgnoreCase))
                        {
                            BarcodeWriterSvg writer = new BarcodeWriterSvg
                            {
                                Format  = BarcodeFormat.QR_CODE,
                                Options = new EncodingOptions
                                {
                                    Width  = pbQRCode.Width,
                                    Height = pbQRCode.Height
                                }
                            };
                            SvgRenderer.SvgImage svgImage = writer.Write(txtQRCode.Text);
                            File.WriteAllText(filePath, svgImage.Content, Encoding.UTF8);
                        }
                        else
                        {
                            if (pbQRCode.Image != null)
                            {
                                ImageHelpers.SaveImage(pbQRCode.Image, filePath);
                            }
                        }
                    }
                }
            }
        }
        private string GenerateCode(string content, BarcodeFormat format = BarcodeFormat.QR_CODE, int width = 100, int height = 100)
        {
            if (string.IsNullOrEmpty(content))
            {
                throw new KeyNotFoundException($"Content for barcode not found.");
            }

            BarcodeWriterSvg writer = new BarcodeWriterSvg();

            writer.Format = format;
            switch (format)
            {
            case BarcodeFormat.QR_CODE:
                writer.Options = new ZXing.QrCode.QrCodeEncodingOptions()
                {
                    Height = height,
                    Width  = width
                };

                content = Uri.UnescapeDataString(content);
                break;

            case BarcodeFormat.EAN_13:
            case BarcodeFormat.EAN_8:
                writer.Options = new EncodingOptions()
                {
                    Height = height,
                };
                break;

            default:
                throw new NotImplementedException($"Format [{format}] not implemented.");
            }

            var encodedContent = writer.Write(content);

            return(encodedContent.ToString());
        }
Ejemplo n.º 7
0
        /// <summary>
        /// Convert the specified string value. To an SVG QR code
        /// </summary>
        /// <returns>The convert.</returns>
        /// <param name="value">Value.</param>
        public SvgImage Convert(string value)
        {
            BarcodeWriter <SvgImage> bcw = new BarcodeWriterSvg()
            {
                Renderer = new SvgRenderer(),
                Format   = ZXing.BarcodeFormat.QR_CODE,
            };

            EncodingOptions encOptions = new EncodingOptions
            {
                Width       = 300,
                Height      = 300,
                Margin      = 0,
                PureBarcode = false
            };

            //Define error correction level
            encOptions.Hints.Add(ZXing.EncodeHintType.ERROR_CORRECTION, ZXing.QrCode.Internal.ErrorCorrectionLevel.H);

            bcw.Options = encOptions;

            return(bcw.Write(value));
        }
Ejemplo n.º 8
0
 private void btnEncoderSave_Click(object sender, EventArgs e)
 {
    if (picEncodedBarCode.Image != null)
    {
       var fileName = String.Empty;
       using (var dlg = new SaveFileDialog())
       {
          dlg.DefaultExt = "png";
          dlg.Filter = "PNG Files (*.png)|*.png|SVG Files (*.svg)|*.svg|BMP Files (*.bmp)|*.bmp|TIFF Files (*.tif)|*.tif|JPG Files (*.jpg)|*.jpg|All Files (*.*)|*.*";
          if (dlg.ShowDialog(this) != DialogResult.OK)
             return;
          fileName = dlg.FileName;
       }
       var extension = Path.GetExtension(fileName).ToLower();
       var bmp = (Bitmap)picEncodedBarCode.Image;
       switch (extension)
       {
          case ".bmp":
             bmp.Save(fileName, ImageFormat.Bmp);
             break;
          case ".jpeg":
          case ".jpg":
             bmp.Save(fileName, ImageFormat.Jpeg);
             break;
          case ".tiff":
          case ".tif":
             bmp.Save(fileName, ImageFormat.Tiff);
             break;
          case ".svg":
             {
                var writer = new BarcodeWriterSvg
                                {
                                   Format = (BarcodeFormat) cmbEncoderType.SelectedItem,
                                   Options = EncodingOptions ?? new EncodingOptions
                                                                   {
                                                                      Height = picEncodedBarCode.Height,
                                                                      Width = picEncodedBarCode.Width
                                                                   }
                                };
                var svgImage = writer.Write(txtEncoderContent.Text);
                File.WriteAllText(fileName, svgImage.Content, System.Text.Encoding.UTF8);
             }
             break;
          default:
             bmp.Save(fileName, ImageFormat.Png);
             break;
       }
    }
 }
Ejemplo n.º 9
0
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", Route = null)] HttpRequest req,
            ILogger log)
        {
            // FYI, sizes are a little weird when rending QR codes. Setting to certain values seems to not "take"
            // until the value exceeds some magical boundary.
            // Explained here: https://stackoverflow.com/questions/17527591/zxing-net-qr-code-size
            // "Each Matrix code type has symmetrical representation requirements. It will always jump to an even number that is a multiple of the codeword size."

            // GS1 General Specification define that GS1-128 (the formal application of Code 128 to the supply chain industry) has a limits of 48 characters per symbol.
            // But technically, there's no limit as long as the device can read it.
            // Let's set our limit to a reasonable 100.
            const int    maxValueLength     = 2048;
            const string defaultImageWidth  = "0";
            const string defaultImageHeight = "40";
            const int    minImageWidth      = 0;
            const int    maxImageWidth      = 2048;
            const int    minImageHeight     = 10;
            const int    maxImageHeight     = 2048;
            const string defaultMargin      = "0";
            const int    maxMargin          = 200;

            // Log the querystring.
            log.LogInformation($"querystring: {req.QueryString.Value}");

            // Validate the value, v
            if (!req.Query.ContainsKey("v"))
            {
                return(new BadRequestObjectResult("No value 'v' specified. You must specify the value you wish to encode."));
            }
            string value = req.Query["v"];

            if (value.Length > maxValueLength)
            {
                return(new BadRequestObjectResult($"Invalid length for value 'v'. This API will not render a barcode longer than {maxValueLength} characters."));
            }

            // Validate the output format 'fmt'.
            var outputFormat = req.Query.ContainsKey("fmt") ? req.Query["fmt"].ToString() : "png";

            if (outputFormat != "png" && outputFormat != "svg")
            {
                return(new BadRequestObjectResult(
                           $"Invalid output file format 'fmt'. Value must be 'png' or 'svg'."));
            }

            // Validate the barcode symbology, 'sym'.
            var symbologyStr = req.Query.ContainsKey("sym") ? req.Query["sym"].ToString() : BarcodeFormat.CODE_128.ToString();
            var parsed       = Enum.TryParse <BarcodeFormat>(symbologyStr, true, out var symbology);

            if (!parsed)
            {
                return(new BadRequestObjectResult(
                           $"Invalid barcode symbology 'sym'. Value must be one of {string.Join(",", Enum.GetNames(typeof(BarcodeFormat)))}"));
            }

            // Validate height, width and margin.
            var heightStr = req.Query.ContainsKey("h") ? req.Query["h"].ToString() : defaultImageHeight;
            var widthStr  = req.Query.ContainsKey("w") ? req.Query["w"].ToString() : defaultImageWidth;
            var marginStr = req.Query.ContainsKey("m") ? req.Query["m"].ToString() : defaultMargin;

            int.TryParse(heightStr, out var height);
            if (height < minImageHeight || height > maxImageHeight)
            {
                return(new BadRequestObjectResult($"Height 'h' must be between {minImageHeight} and {maxImageHeight}."));
            }
            int.TryParse(widthStr, out var width);
            if (width < minImageWidth || width > maxImageWidth)
            {
                return(new BadRequestObjectResult($"Width 'w' must be between {minImageWidth} and {maxImageWidth}."));
            }

            int.TryParse(marginStr, out var margin);
            if (margin < 0 || margin > maxMargin)
            {
                return(new BadRequestObjectResult($"Margin 'm' must be between 0 and {maxMargin}."));
            }

            // Configure the EncodingOptions.
            // There are many options for more complicated symbologies which we don't handle here.
            // Our purposes are focused on Code 128 and QR Code.
            var options = new EncodingOptions
            {
                Height = height
            };

            if (width > 0)
            {
                options.Width = width;
            }

            if (margin > 0)
            {
                options.Margin = margin;
            }


            // Branch depending on whether we're outputting a PNG graphics file or an SVG.
            if (outputFormat == "png")
            {
                var bcWriter = new BarcodeWriterPixelData
                {
                    Format  = symbology,
                    Options = options
                };
                var pixelData = bcWriter.Write(value);
                using (var img = Image.LoadPixelData <Rgba32>(pixelData.Pixels, pixelData.Width, pixelData.Height))
                {
                    using (var ms = new MemoryStream())
                    {
                        img.SaveAsPng(ms);
                        return(new FileContentResult(ms.ToArray(), "image/png"));
                    }
                }
            }
            else // svg
            {
                var svgWriter = new BarcodeWriterSvg()
                {
                    Format = symbology,
                };
                var svg   = svgWriter.Write(value);
                var bytes = Encoding.UTF8.GetBytes(svg.ToString());
                return(new FileContentResult(bytes, "image/svg+xml"));
            }
        }