Ejemplo n.º 1
0
 /// <summary>
 /// 生成二维码
 /// </summary>
 /// <param name="content">内容</param>
 /// <param name="qRCodeScale">大小</param>
 /// <param name="qRCodeVersion">版本</param>
 /// <param name="qRCodeErrorCorrect">容错</param>
 /// <param name="logoFile">logo文件</param>
 /// <param name="logoSize">logo大小</param>
 /// <returns></returns>
 public (string error, Bitmap qrcodeBitbmp) CreateQRCode(string content, int qRCodeScale, int qRCodeVersion,
     ZXing.QrCode.Internal.ErrorCorrectionLevel qRCodeErrorCorrect, string logoFile, int logoSize)
 {
     int? ver = null;
     if (qRCodeVersion > 0)
         ver = qRCodeVersion;
     BarcodeWriter writer = new BarcodeWriter();
     writer.Format = BarcodeFormat.QR_CODE;
     writer.Options = new ZXing.QrCode.QrCodeEncodingOptions() {
         DisableECI = true,
         CharacterSet = "UTF-8",
         Width = qRCodeScale,
         Height = qRCodeScale,
         ErrorCorrection = qRCodeErrorCorrect,
         QrVersion = ver,
         Margin = 0
     };
     try
     {
         Bitmap qrcode = writer.Write(content);
         if (!string.IsNullOrEmpty(logoFile))
         {
             Graphics g = Graphics.FromImage(qrcode);
             Bitmap bitmapLogo = new Bitmap(logoFile);
             bitmapLogo = new Bitmap(bitmapLogo, new System.Drawing.Size(logoSize, logoSize));
             PointF point = new PointF(qrcode.Width / 2 - logoSize / 2, qrcode.Height / 2 - logoSize / 2);
             g.DrawImage(bitmapLogo, point);
         }
         return (null, qrcode);
     }
     catch (Exception ex)
     {
         return (ex.Message, null);
     }
 }
Ejemplo n.º 2
0
        private void comboBox_ErrorCorrect_SelectedIndexChanged(object sender, EventArgs e)
        {
            QrCodeEncodingOptions qceo = (QrCodeEncodingOptions)qrCodeWriter.Options;

            qceo.ErrorCorrection = ErrorCorrectionLevel.forBits(comboBox_ErrorCorrect.SelectedIndex);
            refreshQrCode();
        }
Ejemplo n.º 3
0
        private void comboBox_ErrorCorrect_SelectedIndexChanged(object sender, EventArgs e)
        {
            QrCodeEncodingOptions qceo = (QrCodeEncodingOptions)qrCodeWriter.Options;

            qceo.ErrorCorrection             = ErrorCorrectionLevel.forBits(comboBox_ErrorCorrect.SelectedIndex);
            qrCodeEncoder.QRCodeErrorCorrect = (ThoughtWorks.QRCode.Codec.QRCodeEncoder.ERROR_CORRECTION)qceo.ErrorCorrection.Bits;
            refreshQrCode();
        }
Ejemplo n.º 4
0
        //private ByteMatrix matrix;

        public MicroQRCode()
        {
            mode          = null;
            ecLevel       = null;
            version       = -1;
            matrixWidth   = -1;
            maskPattern   = -1;
            numTotalBytes = -1;
            numDataBytes  = -1;
            numECBytes    = -1;
            numRSBlocks   = -1;
            Matrix        = null;
        }
        private static int chooseMaskPattern(BitVector bits, ErrorCorrectionLevel ecLevel, int version, ByteMatrix matrix)
        {
            int maxPenalty      = System.Int32.MinValue; // highest penalty is better.
            int bestMaskPattern = -1;

            // We try all mask patterns to choose the best one.
            for (int maskPattern = 0; maskPattern < MicroQRCode.NUM_MASK_PATTERNS; maskPattern++)
            {
                MatrixUtil.buildMatrix(bits, ecLevel, version, maskPattern, matrix);
                int penalty = calculateMaskPenalty(matrix);
                if (penalty > maxPenalty)
                {
                    maxPenalty      = penalty;
                    bestMaskPattern = maskPattern;
                }
            }
            return(bestMaskPattern);
        }
Ejemplo n.º 6
0
        public static string QrImg(string content, string qrcodeImgPath, string corrLevel, int wh, string color, string bgcolor)
        {
            ZXing.QrCode.Internal.ErrorCorrectionLevel corrLevel2 = ZXing.QrCode.Internal.ErrorCorrectionLevel.L;
            if (corrLevel != null)
            {
                string text = corrLevel.ToLower();
                if (text != null)
                {
                    if (text == "l")
                    {
                        corrLevel2 = ZXing.QrCode.Internal.ErrorCorrectionLevel.L;
                        goto IL_80;
                    }
                    if (text == "m")
                    {
                        corrLevel2 = ZXing.QrCode.Internal.ErrorCorrectionLevel.M;
                        goto IL_80;
                    }
                    if (text == "q")
                    {
                        corrLevel2 = ZXing.QrCode.Internal.ErrorCorrectionLevel.Q;
                        goto IL_80;
                    }
                    if (text == "h")
                    {
                        corrLevel2 = ZXing.QrCode.Internal.ErrorCorrectionLevel.H;
                        goto IL_80;
                    }
                }
                corrLevel2 = ZXing.QrCode.Internal.ErrorCorrectionLevel.L;
                IL_80 :;
            }
            BitMatrix matrix = new QRCodeWriter().encode(content, BarcodeFormat.QR_CODE, wh, wh, null);
            Image     image  = Create.toBitmap(matrix, color, bgcolor);

            image.Save(qrcodeImgPath, ImageFormat.Png);
            image.Dispose();
            return(qrcodeImgPath);
        }
        /// <summary> Initialize "qrCode" according to "numInputBytes", "ecLevel", and "mode". On success,
        /// modify "qrCode".
        /// </summary>
        private static void initQRCode(int numInputBytes, ErrorCorrectionLevel ecLevel, Mode mode, MicroQRCode qrCode, int versionNum)
        {
            qrCode.ECLevel = ecLevel;
            qrCode.Mode    = mode;

            // In the following comments, we use numbers of Version 7-H.

            Version version = Version.getVersionForNumber(versionNum);
            // numBytes = 196
            int numBytes = version.TotalCodewords;

            // getNumECBytes = 130
            Version.ECBlocks ecBlocks = version.getECBlocksForLevel(ecLevel);
            int numEcBytes            = ecBlocks.TotalECCodewords;
            // getNumRSBlocks = 5
            int numRSBlocks = ecBlocks.NumBlocks;
            // getNumDataBytes = 196 - 130 = 66
            int numDataBytes = numBytes - numEcBytes;

            // We want to choose the smallest version which can contain data of "numInputBytes" + some
            // extra bits for the header (mode info and length info). The header can be three bytes
            // (precisely 4 + 16 bits) at most. Hence we do +3 here.
            if (numDataBytes >= numInputBytes)
            {
                // Yay, we found the proper rs block info!
                qrCode.Version       = versionNum;
                qrCode.NumTotalBytes = numBytes;
                qrCode.NumDataBytes  = numDataBytes;
                qrCode.NumRSBlocks   = numRSBlocks;
                // getNumECBytes = 196 - 66 = 130
                qrCode.NumECBytes = numEcBytes;
                // matrix width = 21 + 6 * 4 = 45
                qrCode.MatrixWidth = version.DimensionForVersion;
                return;
            }
            throw new WriterException("Cannot find proper rs block info (input data too big?)");
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="content"></param>
        /// <param name="ecLevel"></param>
        /// <param name="hints"></param>
        /// <param name="qrCode"></param>
        public static void encode(System.String content, ErrorCorrectionLevel ecLevel,
                                  IDictionary <EncodeHintType, object> hints, MicroQRCode qrCode, int versionNum)
        {
            if (versionNum < 1 || versionNum > 4)
            {
                throw new ArgumentOutOfRangeException("versionNum", "versionNum [1, 4]");
            }
            System.String encoding = null;
            if (hints.ContainsKey(EncodeHintType.CHARACTER_SET))
            {
                encoding = hints == null ? null : (System.String)hints[EncodeHintType.CHARACTER_SET];
                if (encoding == null)
                {
                    encoding = DEFAULT_BYTE_MODE_ENCODING;
                }
            }

            // Step 1: Choose the mode (encoding).
            Mode mode = chooseMode(content, encoding);

            // Step 2: Append "bytes" into "dataBits" in appropriate encoding.
            BitVector dataBits = new BitVector();

            appendBytes(content, mode, dataBits, encoding, versionNum);
            // Step 3: Initialize QR code that can contain "dataBits".
            int numInputBytes = dataBits.sizeInBytes();

            initQRCode(numInputBytes, ecLevel, mode, qrCode, versionNum);

            // Step 4: Build another bit vector that contains header and data.
            BitVector headerAndDataBits = new BitVector();

            //INFO ECB+Mode+Length+Data[+terminate]
            // Step 4.5: Append ECI message if applicable
            appendModeInfo(mode, headerAndDataBits, versionNum);
            int numLetters = mode.Equals(Mode.BYTE) ? dataBits.sizeInBytes() : content.Length;

            appendLengthInfo(numLetters, qrCode.Version, mode, headerAndDataBits);
            headerAndDataBits.appendBitVector(dataBits);

            // Step 5: Terminate the bits properly.
            terminateBits(qrCode.NumDataBytes, headerAndDataBits, versionNum);

            // Step 6: Interleave data bits with error correction code.
            BitVector finalBits = new BitVector();

            interleaveWithECBytes(headerAndDataBits, versionNum, qrCode.NumTotalBytes, qrCode.NumDataBytes, qrCode.NumRSBlocks, finalBits);

            // Step 7: Choose the mask pattern and set to "qrCode".
            ByteMatrix matrix = new ByteMatrix(qrCode.MatrixWidth, qrCode.MatrixWidth);

            qrCode.MaskPattern = chooseMaskPattern(finalBits, qrCode.ECLevel, qrCode.Version, matrix);

            // Step 8.  Build the matrix and set it to "qrCode".
            MatrixUtil.buildMatrix(finalBits, qrCode.ECLevel, qrCode.Version, qrCode.MaskPattern, matrix);
            qrCode.Matrix = matrix;

            //var decoder = new com.google.zxing.microqrcode.decoder.Decoder();
            //var res = decoder.decode(com.google.zxing.common.BitMatrix.FromByteMatrix(matrix));
            //Console.WriteLine(res.Text);

            // Step 9.  Make sure we have a valid QR Code.
            if (!qrCode.Valid)
            {
                throw new WriterException("Invalid QR code: " + qrCode.ToString());
            }
        }
 /// <summary>  Encode "bytes" with the error correction level "ecLevel". The encoding mode will be chosen
 /// internally by chooseMode(). On success, store the result in "qrCode".
 ///
 /// We recommend you to use QRCode.EC_LEVEL_L (the lowest level) for
 /// "getECLevel" since our primary use is to show QR code on desktop screens. We don't need very
 /// strong error correction for this purpose.
 ///
 /// Note that there is no way to encode bytes in MODE_KANJI. We might want to add EncodeWithMode()
 /// with which clients can specify the encoding mode. For now, we don't need the functionality.
 /// </summary>
 public static void encode(System.String content, ErrorCorrectionLevel ecLevel, MicroQRCode qrCode, int versionNum)
 {
     encode(content, ecLevel, null, qrCode, versionNum);
 }
Ejemplo n.º 10
0
        private Tuple <ZXing.QrCode.Internal.ErrorCorrectionLevel, string> getSelectedOptions()
        {
            ZXing.QrCode.Internal.ErrorCorrectionLevel ecl = ZXing.QrCode.Internal.ErrorCorrectionLevel.L;

            if (cbErrorCorrectionLevel.SelectedValue is ComboBoxItem cbi1)
            {
                switch (cbi1.Tag.ToString())
                {
                case "L":
                    ecl = ZXing.QrCode.Internal.ErrorCorrectionLevel.L; break;

                case "M":
                    ecl = ZXing.QrCode.Internal.ErrorCorrectionLevel.M; break;

                case "Q":
                    ecl = ZXing.QrCode.Internal.ErrorCorrectionLevel.Q; break;

                case "H":
                    ecl = ZXing.QrCode.Internal.ErrorCorrectionLevel.H; break;
                }
            }

            string characterSet = "UTF-8";

            if (cbCharacterSet.SelectedValue is ComboBoxItem cbi2)
            {
                string tempEncoding = cbi2.Content.ToString();
                try
                {
                    characterSet = ZXing.Common.CharacterSetECI.getCharacterSetECIByName(tempEncoding).EncodingName;

                    #region 知识点 ZXing.Common.CharacterSetECI

                    // ZXing.Common.CharacterSetECI.getCharacterSetECIByName()
                    // 从网页 https://zxing.github.io/zxing/apidocs/com/google/zxing/common/CharacterSetECI.html#UnicodeBigUnmarked
                    // 了解到 zxing 只支持

                    //ASCII
                    //Big5
                    //Cp1250
                    //Cp1251
                    //Cp1252
                    //Cp1256
                    //Cp437
                    //EUC_KR
                    //GB18030
                    //ISO8859_1
                    //ISO8859_10
                    //ISO8859_11
                    //ISO8859_13
                    //ISO8859_14
                    //ISO8859_15
                    //ISO8859_16
                    //ISO8859_2
                    //ISO8859_3
                    //ISO8859_4
                    //ISO8859_5
                    //ISO8859_6
                    //ISO8859_7
                    //ISO8859_8
                    //ISO8859_9
                    //SJIS
                    //UnicodeBigUnmarked
                    //UTF8

                    #endregion
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"{ex.Message}\r\n编码{tempEncoding}不存在", "捕获异常");
                }
            }

            return(new Tuple <ZXing.QrCode.Internal.ErrorCorrectionLevel, string>(ecl, characterSet));
        }