Exemplo n.º 1
0
		private static int DataBits(int version, ErrorCorrectionLevel level)
        {
        	int totalCodewords = VersionTable.GetVersionByNum(version).TotalCodewords;
        	int totalECCodewords = VersionTable.GetVersionByNum(version).GetECBlocksByLevel(level).NumErrorCorrectionCodewards;
        	
        	return (totalCodewords - totalECCodewords) * 8;
        }
Exemplo n.º 2
0
		public static VersionCheckStatus VersionCheck(int versionNum, int numDataBits, Mode mode, ErrorCorrectionLevel level, string encodingName)
		{
			int TotalDataBits = numDataBits;
			ECISet eciSet = new ECISet(ECISet.AppendOption.NameToValue);
        	if(mode == Mode.EightBitByte)
        	{
        		if(encodingName != DEFAULT_ENCODING)
        		{
        			int eciValue = eciSet.GetECIValueByName(encodingName);
        			TotalDataBits += ECISet.NumOfECIHeaderBits(eciValue);
        		}
        	}
        	int bitCharCountIndicator = CharCountIndicatorTable.GetBitCountInCharCountIndicator(mode, versionNum);
        	TotalDataBits += (4 + bitCharCountIndicator);
        	
        	int expectContainer = DataBits(versionNum, level);
        	int lowerContainer = versionNum == 1 ? 0 : DataBits(versionNum - 1, level);
        	
        	if(expectContainer < TotalDataBits)
        	{
        		return VersionCheckStatus.SmallerThanExpect;	
        	}
        	else if(lowerContainer >= TotalDataBits)
        	{
        		return VersionCheckStatus.LargerThanExpect;	
        	}
        	else
        	{
        		return VersionCheckStatus.Efficient;
        	}
		}
Exemplo n.º 3
0
        /// <summary>
        /// Initializes a new instance of the <see cref="QROptions"/> class.
        /// </summary>
        /// <param name="ec">Error correction level.</param>
        /// <param name="margin">The margin (or blank space) around the QR code.</param>
        public QROptions(ErrorCorrectionLevel ec, int margin)
        {
            _errorCorrectionLevel = ec;

            // autocorrect margin if necessary
            _margin = margin > MinimalMargin ? margin : MinimalMargin;
        }
 private FormatInformation(int formatInfo)
 {
     // Bits 3,4
     errorCorrectionLevel = ErrorCorrectionLevel.forBits((formatInfo >> 3) & 0x03);
     // Bottom 3 bits
     dataMask = (sbyte) (formatInfo & 0x07);
 }
Exemplo n.º 5
0
 public void Test_against_CSV_Dataset(int numDataBits,  Mode mode, ErrorCorrectionLevel level, string encodingName, int expectVersionNum)
 {
 	VersionControlStruct vcStruct = VersionControl.InitialSetup(numDataBits, mode, level, encodingName);
 	
 	if(vcStruct.VersionDetail.Version != expectVersionNum)
 		Assert.Fail("Method return version number: {0} Expect value: {1}", vcStruct.VersionDetail.Version, expectVersionNum);
 }
Exemplo n.º 6
0
        private void TestOneCase(string inputString, ErrorCorrectionLevel eclevel, IEnumerable<bool> expected)
        {
        	EncodationStruct encodeStruct = DataEncode.Encode(inputString, eclevel);
			
			IEnumerable<bool> actualResult = ECGenerator.FillECCodewords(encodeStruct.DataCodewords, encodeStruct.VersionDetail);
        	
        	BitVectorTestExtensions.CompareIEnumerable(actualResult, expected, "string");
        }
Exemplo n.º 7
0
		public VersionTestProperties(int numDataBits, Mode mode, ErrorCorrectionLevel level, string encodingName, int versionNum)
			: this()
		{
			this.NumDataBitsForEncodedContent = numDataBits;
			this.Mode = mode;
			this.ECLevel = level;
			this.EncodingName = encodingName;
			this.ExpectVersionNum = versionNum;
		}
		public VersionTableTestProperties(int versionNum, int totalCodewords, ErrorCorrectionLevel level, int numECCodewords, string ecBlockString)
			:this()
		{
			this.VersionNum = versionNum;
			this.TotalNumOfCodewords = totalCodewords;
			this.ErrorCorrectionLevel = level;
			this.NumOfECCodewords = numECCodewords;
			this.ECBlockString = ecBlockString;
		}
        /// <summary>
        /// Given an input string, generates a QR code image.
        /// </summary>
        /// <param name="input">The textual data to turn into a QR code image. The text must contain only
        /// printable US-ASCII characters.</param>
        /// <param name="errorCorrectionLevel">The level of data redundancy to include in the generated
        /// image. The default level is 'M' (approximately 15% redundancy).</param>
        /// <returns>An Image corresponding to the generated QR code.</returns>
        public static Image GetQRCode(string input, ErrorCorrectionLevel errorCorrectionLevel = ErrorCorrectionLevel.M)
        {
            ValidateInputString(input);
            if (errorCorrectionLevel < ErrorCorrectionLevel.L || errorCorrectionLevel > ErrorCorrectionLevel.H)
            {
                throw new ArgumentOutOfRangeException("errorCorrectionLevel");
            }

            return Tester.GetQRCode(input);
        }
Exemplo n.º 10
0
        /// <summary>
        /// 根据文字内容等信息构建相应QRCode格式二维码图片
        /// </summary>
        /// <param name="content">二维码内容信息</param>
        /// <param name="level">纠错级别</param>
        /// <param name="width">图片宽度,如小于0则使用默认尺寸</param>
        /// <param name="height">图片高度,如小于0则使用默认尺寸</param>
        /// <param name="inline">内嵌图片,如为Null则不做内嵌</param>
        /// <returns>二维码图片</returns>
        public static Image BuildQRCode(String content, ErrorCorrectionLevel level, int width, int height, Image inline)
        {
            QrEncoder encoder = new QrEncoder(level);
            QrCode code = null;
            if (!encoder.TryEncode(content, out code))
                return null;

            GraphicsRenderer render = new GraphicsRenderer(new FixedModuleSize(ModuleSizeInPixels, QuietZoneModules.Two), Brushes.Black, Brushes.White);
            DrawingSize cSize = render.SizeCalculator.GetSize(code.Matrix.Width);
            Size oSize = new Size(cSize.CodeWidth, cSize.CodeWidth) + new Size(2 * PaddingSizeInPixels, 2 * PaddingSizeInPixels);

            Image img = new Bitmap(oSize.Width, oSize.Height);

            using (Graphics g = Graphics.FromImage(img))
            {
                g.CompositingQuality = CompositingQuality.HighQuality;
                g.InterpolationMode = InterpolationMode.HighQualityBicubic;

                render.Draw(g, code.Matrix);
                if (inline != null)
                {
                    int iw = (int)(oSize.Width * InlineSizeInProportion);
                    int ih = (int)(oSize.Height * InlineSizeInProportion);
                    int il = (oSize.Width - iw) / 2;
                    int it = (oSize.Height - ih) / 2;
                    g.DrawImage(inline, it, il, iw, ih);
                    Pen pen = new Pen(Color.White, 1);
                    using (GraphicsPath path = CreateRoundedRectanglePath(new Rectangle(it - 1, il - 1, iw + 1, ih + 1), 4))
                    {
                        g.DrawPath(pen, path);
                    }

                }
            }

            if (width > 0 && height > 0)
            {
                int w = width > 0 ? width : code.Matrix.Width;
                int h = height > 0 ? height : code.Matrix.Height;
                Image imgCode = new Bitmap(width, height);
                using (Graphics g = Graphics.FromImage(imgCode))
                {
                    g.CompositingQuality = CompositingQuality.HighQuality;
                    g.InterpolationMode = InterpolationMode.HighQualityBicubic;
                    g.DrawImage(img, 0, 0, width, height);
                }

                img.Dispose();
                img = imgCode;

            }

            return img;
        }
Exemplo n.º 11
0
 public static VersionInfo FindSmallestVersionInfo(ErrorCorrectionLevel errorCorrectionLevel, EncodingMode encodingMode, int dataBits)
 {
     dataBits += 4; // Mode indicator
     foreach (VersionInfo versionInfo in VersionInfos.Where(x => x.ErrorCorrectionLevel == errorCorrectionLevel))
     {
         if ((versionInfo.TotalDataBytes() * 8) >= (dataBits + (int)versionInfo.CharCountBits(encodingMode)))
         {
             return(versionInfo);
         }
     }
     return(null);
 }
Exemplo n.º 12
0
 /// <summary>Build 2D matrix of QR Code from "dataBits" with "ecLevel", "version" and "getMaskPattern".</summary>
 /// <remarks>
 /// Build 2D matrix of QR Code from "dataBits" with "ecLevel", "version" and "getMaskPattern". On
 /// success, store the result in "matrix".
 /// </remarks>
 /// <param name="dataBits">BitVector containing the databits</param>
 /// <param name="ecLevel">Error correction level of the QR code (L,M,Q,H)</param>
 /// <param name="version">Version of the QR code, [1 .. 40]</param>
 /// <param name="maskPattern">masking pattern</param>
 /// <param name="matrix">Bytematrix in which the output will be stored</param>
 public static void BuildMatrix(BitVector dataBits, ErrorCorrectionLevel ecLevel, int version, int maskPattern
                                , ByteMatrix matrix)
 {
     ClearMatrix(matrix);
     EmbedBasicPatterns(version, matrix);
     // Type information appear with any version.
     EmbedTypeInfo(ecLevel, maskPattern, matrix);
     // Version info appear if version >= 7.
     MaybeEmbedVersionInfo(version, matrix);
     // Data should be embedded at end.
     EmbedDataBits(dataBits, maskPattern, matrix);
 }
Exemplo n.º 13
0
        private DecoderResult decode(BitMatrixParser parser, IDictionary <DecodeHintType, object> hints)
        {
            Version version = parser.readVersion();

            if (version == null)
            {
                return(null);
            }
            var formatinfo = parser.readFormatInformation();

            if (formatinfo == null)
            {
                return(null);
            }
            ErrorCorrectionLevel ecLevel = formatinfo.ErrorCorrectionLevel;

            // Read codewords
            byte[] codewords = parser.readCodewords();
            if (codewords == null)
            {
                return(null);
            }
            // Separate into data blocks
            DataBlock[] dataBlocks = DataBlock.getDataBlocks(codewords, version, ecLevel);

            // Count total number of data bytes
            int totalBytes = 0;

            foreach (var dataBlock in dataBlocks)
            {
                totalBytes += dataBlock.NumDataCodewords;
            }
            byte[] resultBytes  = new byte[totalBytes];
            int    resultOffset = 0;

            // Error-correct and copy data blocks together into a stream of bytes
            foreach (var dataBlock in dataBlocks)
            {
                byte[] codewordBytes    = dataBlock.Codewords;
                int    numDataCodewords = dataBlock.NumDataCodewords;
                if (!correctErrors(codewordBytes, numDataCodewords))
                {
                    return(null);
                }
                for (int i = 0; i < numDataCodewords; i++)
                {
                    resultBytes[resultOffset++] = codewordBytes[i];
                }
            }

            // Decode the contents of that stream of bytes
            return(DecodedBitStreamParser.decode(resultBytes, version, ecLevel, hints));
        }
Exemplo n.º 14
0
        /// <summary>
        /// Use number of data bits(header + eci header + data bits from EncoderBase) to search for proper version to use
        /// between min and max boundary.
        /// Boundary define by DynamicSearchIndicator method.
        /// </summary>
        private static int BinarySearch(int numDataBits, ErrorCorrectionLevel level, int lowerVersionNum, int higherVersionNum)
        {
            //int middleVersionNumber;

            //while (lowerVersionNum <= higherVersionNum)
            //{
            //    middleVersionNumber = (lowerVersionNum + higherVersionNum) / 2;
            //    QRCodeVersion version = VersionTable.GetVersionByNum(middleVersionNumber);
            //    int numECCodewords = version.GetECBlocksByLevel(level).NumErrorCorrectionCodewards;
            //    int dataCodewords = version.TotalCodewords - numECCodewords;

            //    if (dataCodewords << 3 == numDataBits)
            //        return middleVersionNumber;

            //    if (dataCodewords << 3 > numDataBits)
            //    {
            //        higherVersionNum = middleVersionNumber - 1;
            //    }
            //    else
            //    {
            //        lowerVersionNum = middleVersionNumber + 1;
            //    }
            //}
            //return 4;



            int middleVersionNumber;

            while (lowerVersionNum <= higherVersionNum)
            {
                middleVersionNumber = (lowerVersionNum + higherVersionNum) / 2;
                QRCodeVersion version        = VersionTable.GetVersionByNum(middleVersionNumber);
                int           numECCodewords = version.GetECBlocksByLevel(level).NumErrorCorrectionCodewards;
                int           dataCodewords  = version.TotalCodewords - numECCodewords;

                if (dataCodewords << 3 == numDataBits)
                {
                    return(middleVersionNumber);
                }

                if (dataCodewords << 3 > numDataBits)
                {
                    higherVersionNum = middleVersionNumber - 1;
                }
                else
                {
                    lowerVersionNum = middleVersionNumber + 1;
                }
            }
            return(lowerVersionNum);
        }
Exemplo n.º 15
0
        private FormatInformation(int formatInfo)
        {
            //ISO/IEC 18004:2006(E)  6.9 Format information
            //Symbol number 0:         000
            //Data mask pattern reference:       11
            //Data bits (symbol number, data mask pattern reference):  00011

            var p = SYMBOL_NUMBERS_INFO[(formatInfo >> 2) & 0x07];

            errorCorrectionLevel = p.Value;
            version  = Version.getVersionForNumber(p.Key);
            dataMask = (sbyte)(formatInfo & 0x03);
        }
Exemplo n.º 16
0
 public ErrorCorrectionInfo GetCorrectionInfo(ErrorCorrectionLevel level)
 {
     switch (level)
     {
         case ErrorCorrectionLevel.L: return L;
         case ErrorCorrectionLevel.M: return M;
         case ErrorCorrectionLevel.Q: return Q;
         case ErrorCorrectionLevel.H: return H;
         default:
             Debug.Fail("Unknown value.");
             throw new ArgumentOutOfRangeException();
     }
 }
Exemplo n.º 17
0
 public QRCode()
 {
     mode          = null;
     ecLevel       = null;
     version       = -1;
     matrixWidth   = -1;
     maskPattern   = -1;
     numTotalBytes = -1;
     numDataBytes  = -1;
     numECBytes    = -1;
     numRSBlocks   = -1;
     matrix        = null;
 }
Exemplo n.º 18
0
        private static BitMatrix ProcessEncodationResult(EncodationStruct encodeStruct, ErrorCorrectionLevel errorLevel)
        {
            BitList codewords = ECGenerator.FillECCodewords(encodeStruct.DataCodewords, encodeStruct.VersionDetail);

            TriStateMatrix triMatrix = new TriStateMatrix(encodeStruct.VersionDetail.MatrixWidth);
            PositioninngPatternBuilder.EmbedBasicPatterns(encodeStruct.VersionDetail.Version, triMatrix);

            triMatrix.EmbedVersionInformation(encodeStruct.VersionDetail.Version);
            triMatrix.EmbedFormatInformation(errorLevel, new Pattern0());
            triMatrix.TryEmbedCodewords(codewords);

            return triMatrix.GetLowestPenaltyMatrix(errorLevel);
        }
Exemplo n.º 19
0
 public FormatInformation(int mask, ErrorCorrectionLevel errorCorrectionLevel)
 {
     if (0 <= mask && mask <= 7)
     {
         Mask                 = mask;
         MaskPattern          = GetMaskPattern(mask);
         ErrorCorrectionLevel = errorCorrectionLevel;
     }
     else
     {
         throw new Exception($"Attempt to create FormatInformation with mask not in the range [{MinMask}:{MaxMask}]. Given mask: {mask}");
     }
 }
Exemplo n.º 20
0
        public QrCreator(ArgsModel args, ErrorCorrectionLevel level = ErrorCorrectionLevel.H, int Width = 500, int Height = 500)
        {
            switch (args.LoadMode)
            {
            case LoadMode.Text:
                CreateFromContent(args.Content, level, Width, Height);
                break;

            case LoadMode.Image:
                CreateFromImageFile(args.Content, level, Width, Height);
                break;
            }
        }
Exemplo n.º 21
0
        /// <summary>
        /// Parse QueryString that define the QR code properties
        /// </summary>
        /// <param name="request">HttpRequest containing HTTP GET data</param>
        /// <returns>A QR code descriptor object</returns>
        public static CodeDescriptor Init(ErrorCorrectionLevel level, string content, QuietZoneModules qzModules, int moduleSize)
        {
            var cp = new CodeDescriptor();

            //// Error correction level
            cp.Ecl = level;
            //// Code content to encode
            cp.Content = content;
            //// Size of the quiet zone
            cp.QuietZones = qzModules;
            //// Module size
            cp.ModuleSize = moduleSize;
            return(cp);
        }
Exemplo n.º 22
0
        /// <summary>
        /// Parse QueryString that define the QR code properties
        /// </summary>
        /// <param name="request">HttpRequest containing HTTP GET data</param>
        /// <returns>A QR code descriptor object</returns>
        public static CodeDescriptor Init(ErrorCorrectionLevel level, string content, QuietZoneModules qzModules, int moduleSize)
        {
            var cp = new CodeDescriptor();

            //// Error correction level
            cp.Ecl = level;
            //// Code content to encode
            cp.Content = content;
            //// Size of the quiet zone
            cp.QuietZones = qzModules;
            //// Module size
            cp.ModuleSize = moduleSize;
            return cp;
        }
Exemplo n.º 23
0
        internal static EncodationStruct Encode(string content, ErrorCorrectionLevel ecLevel)
        {
            RecognitionStruct recognitionResult = InputRecognise.Recognise(content);
            EncoderBase       encoderBase       = CreateEncoder(recognitionResult.EncodingName);

            BitList encodeContent = encoderBase.GetDataBits(content);

            int encodeContentLength = encodeContent.Count;

            VersionControlStruct vcStruct =
                VersionControl.InitialSetup(encodeContentLength, ecLevel, recognitionResult.EncodingName);

            BitList dataCodewords = new BitList();

            // Eci header
            if (vcStruct.IsContainECI && !(vcStruct.ECIHeader is null))
            {
                dataCodewords.Add(vcStruct.ECIHeader);
            }

            // Header
            dataCodewords.Add(encoderBase.GetModeIndicator());
            int numLetter = encodeContentLength >> 3;

            dataCodewords.Add(encoderBase.GetCharCountIndicator(numLetter, vcStruct.VersionDetail.Version));

            // Data
            dataCodewords.Add(encodeContent);

            // Terminator Padding
            dataCodewords.TerminateBites(dataCodewords.Count, vcStruct.VersionDetail.NumDataBytes);

            int dataCodewordsCount = dataCodewords.Count;

            if ((dataCodewordsCount & 0x7) != 0)
            {
                throw new ArgumentException($"{nameof(dataCodewords)} is not byte sized.");
            }
            else if (dataCodewordsCount >> 3 != vcStruct.VersionDetail.NumDataBytes)
            {
                throw new ArgumentException($"{nameof(dataCodewords)} num of bytes not equal to {nameof(vcStruct.VersionDetail.NumDataBytes)} for current version");
            }

            var encStruct = new EncodationStruct(vcStruct)
            {
                DataCodewords = dataCodewords
            };

            return(encStruct);
        }
 //According Table 25 — Error correction level indicators
 //Using these bits as enum values would destroy their order which currently corresponds to error correction strength.
 internal static int GetErrorCorrectionIndicatorBits(ErrorCorrectionLevel errorLevel)
 {
     //L 01
     //M 00
     //Q 11
     //H 10
     return(errorLevel switch
     {
         ErrorCorrectionLevel.H => 0x02,
         ErrorCorrectionLevel.L => 0x01,
         ErrorCorrectionLevel.M => 0x00,
         ErrorCorrectionLevel.Q => 0x03,
         _ => throw new ArgumentException($"Unsupported error correction level [{errorLevel}]", nameof(errorLevel))
     });
Exemplo n.º 25
0
        /// <summary>
        /// Initializes a new instance of the <see cref="QrConfiguration"/> class.
        /// </summary>
        /// <param name="qrMode">Encoding mode for the message.</param>
        /// <param name="ecc">Error correction level.</param>
        /// <param name="version">QR code version. From 1 to 40 inclusive.</param>
        /// <exception cref="ArgumentOutOfRangeException">
        ///     <paramref name="version"/> is less than 1.<br/>
        ///     -or-<br/>
        ///     <paramref name="version"/> is greater than 40.
        /// </exception>
        /// <exception cref="ArgumentException">
        ///     <paramref name="qrMode"/> is invalid.<br/>
        ///     -or-<br/>
        ///     <paramref name="ecc"/> is invalid.
        /// </exception>
        /// <example>
        /// <code>
        /// var qrConfig = new QrConfiguration(QrMode.Numeric, ErrorCorrectionLevel.Medium, 30);
        /// </code>
        /// </example>
        /// <since_tizen> 4 </since_tizen>
        public QrConfiguration(QrMode qrMode, ErrorCorrectionLevel ecc, int version)
        {
            if (version < 1 || version > 40)
            {
                throw new ArgumentOutOfRangeException(nameof(version), version,
                                                      "Valid version range is 1 to 40 inclusive.");
            }
            ValidationUtil.ValidateEnum(typeof(QrMode), qrMode, nameof(qrMode));
            ValidationUtil.ValidateEnum(typeof(ErrorCorrectionLevel), ecc, nameof(ecc));

            Mode = qrMode;
            ErrorCorrectionLevel = ecc;
            Version = version;
        }
Exemplo n.º 26
0
    private static BitMatrix ProcessEncodationResult(EncodationStruct encodeStruct, ErrorCorrectionLevel errorLevel)
    {
        BitList codewords = ECGenerator.FillECCodewords(encodeStruct.DataCodewords, encodeStruct.VersionDetail);

        TriStateMatrix triMatrix = new(encodeStruct.VersionDetail.MatrixWidth);

        PositioningPatternBuilder.EmbedBasicPatterns(encodeStruct.VersionDetail.Version, triMatrix);

        triMatrix.EmbedVersionInformation(encodeStruct.VersionDetail.Version);
        triMatrix.EmbedFormatInformation(errorLevel, new Pattern0());
        triMatrix.TryEmbedCodewords(codewords);

        return(triMatrix.GetLowestPenaltyMatrix(errorLevel));
    }
Exemplo n.º 27
0
        public static IBarcode Encode(string content, ErrorCorrectionLevel errorCorrectionLevel, Encoding encoding)
        {
            InternalEncoderBase encoder = GetEncoder(encoding);

            (BitList bits, VersionInfo versionInfo) = encoder.Encode(content, errorCorrectionLevel);

            var blocks = BlockList.SplitToBlocks(new Queue <byte>(bits.IterateBytes()), versionInfo);

            byte[] data   = blocks.Interleave(versionInfo);
            QrCode result = Render(data, versionInfo);

            result.Content = content;
            return(result);
        }
Exemplo n.º 28
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
//ORIGINAL LINE: public com.google.zxing.common.BitMatrix encode(String contents, com.google.zxing.BarcodeFormat format, int width, int height, java.util.Map<com.google.zxing.EncodeHintType,?> hints) throws com.google.zxing.WriterException
        public BitMatrix encode(string contents, BarcodeFormat format, int width, int height, IDictionary <EncodeHintType, object> hints)
        {
            if (contents.Length == 0)
            {
                throw new System.ArgumentException("Found empty contents");
            }

            if (format != BarcodeFormat.QR_CODE)
            {
                throw new System.ArgumentException("Can only encode QR_CODE, but got " + format);
            }

            if (width < 0 || height < 0)
            {
                throw new System.ArgumentException("Requested dimensions are too small: " + width + 'x' + height);
            }

            ErrorCorrectionLevel errorCorrectionLevel = ErrorCorrectionLevel.L;
            int quietZone = QUIET_ZONE_SIZE;

            if (hints != null)
            {
                //ErrorCorrectionLevel requestedECLevel = (ErrorCorrectionLevel) hints[EncodeHintType.ERROR_CORRECTION];
                ErrorCorrectionLevel requestedECLevel = null;
                if (hints.ContainsKey(EncodeHintType.ERROR_CORRECTION))
                {
                    requestedECLevel = (ErrorCorrectionLevel)hints[EncodeHintType.ERROR_CORRECTION];
                }
                if (requestedECLevel != null)
                {
                    errorCorrectionLevel = requestedECLevel;
                }

                //int? quietZoneInt = (int?) hints[EncodeHintType.MARGIN];
                int?quietZoneInt = null;
                if (hints.ContainsKey(EncodeHintType.MARGIN))
                {
                    quietZoneInt = (int?)hints[EncodeHintType.MARGIN];
                }

                if (quietZoneInt != null)
                {
                    quietZone = (int)quietZoneInt;
                }
            }

            QRCode code = Encoder.encode(contents, errorCorrectionLevel, hints);

            return(renderResult(code, width, height, quietZone));
        }
Exemplo n.º 29
0
        /// <summary>
        /// 将字符串转换二维码图片
        /// </summary>
        /// <param name="self"></param>
        /// <param name="errLevel"></param>
        /// <returns></returns>
        public static QrCode ToQrCode(this string self, ErrorCorrectionLevel errLevel = ErrorCorrectionLevel.M)
        {
            if (self.NullEmpty())
            {
                return(null);
            }
            QrEncoder qrEncoder = new QrEncoder(ErrorCorrectionLevel.M);
            //QrCode qrCode = qrEncoder.Encode(self);
            QrCode qrCode = new QrCode();

            qrEncoder.TryEncode(self, out qrCode);
            return(qrCode);
            //Renderer renderer = new Renderer(5, Brushes.Black, Brushes.White);
            //renderer.CreateImageFile(qrCode.Matrix, @"c:\temp\HelloWorld.png", ImageFormat.Png);
        }
Exemplo n.º 30
0
        /// <summary>
        /// Encodes the specified content.
        /// </summary>
        /// <param name="content">The content.</param>
        /// <param name="errorLevel">The error level.</param>
        /// <returns></returns>
        /// <remarks></remarks>
        internal static BitMatrix Encode(string content, ErrorCorrectionLevel errorLevel)
        {
            EncodationStruct encodeStruct = DataEncode.Encode(content, errorLevel);

            BitList codewords = ECGenerator.FillECCodewords(encodeStruct.DataCodewords, encodeStruct.VersionDetail);

            var triMatrix = new TriStateMatrix(encodeStruct.VersionDetail.MatrixWidth);
            PositioninngPatternBuilder.EmbedBasicPatterns(encodeStruct.VersionDetail.Version, triMatrix);

            triMatrix.EmbedVersionInformation(encodeStruct.VersionDetail.Version);
            triMatrix.EmbedFormatInformation(errorLevel, new Pattern0());
            triMatrix.TryEmbedCodewords(codewords);

            return triMatrix.GetLowestPenaltyMatrix(errorLevel);
        }
Exemplo n.º 31
0
 // Build 2D matrix of QR Code from "dataBits" with "ecLevel", "version" and "getMaskPattern". On
 // success, store the result in "matrix" and return true.
 public static void buildMatrix(BitVector dataBits, ErrorCorrectionLevel ecLevel, int version, int maskPattern, ByteMatrix matrix)
 {
     try{
         clearMatrix(matrix);
         embedBasicPatterns(version, matrix);
         // Type information appear with any version.
         embedTypeInfo(ecLevel, maskPattern, matrix);
         // Version info appear if version >= 7.
         maybeEmbedVersionInfo(version, matrix);
         // Data should be embedded at end.
         embedDataBits(dataBits, maskPattern, matrix);
     }catch (Exception e) {
         throw  new WriterException(e.Message);
     }
 }
        /// <summary>
        /// Initializes a new instance of a <see cref="GoogleQrCodeProvider"/> with the specified
        /// <see cref="ErrorCorrectionLevel"/>, <see cref="MarginRows"/> and
        /// <see cref="RemoteCertificateValidationCallback"/>.
        /// </summary>
        /// <param name="errorCorrectionLevel">The <see cref="ErrorCorrectionLevel"/> to use when generating QR codes.</param>
        /// <param name="marginRows">The width of the white border around the data portion of the code.</param>
        /// <param name="remoteCertificateValidationCallback">
        /// The <see cref="RemoteCertificateValidationCallback"/> to use when generating QR codes.
        /// </param>
        /// <exception cref="ArgumentOutOfRangeException">
        /// Thrown when an invalid <see cref="ErrorCorrectionLevel"/> is specified or marginRows is less than 0.
        /// </exception>
        public GoogleQrCodeProvider(ErrorCorrectionLevel errorCorrectionLevel, int marginRows, RemoteCertificateValidationCallback remoteCertificateValidationCallback)
            : base(baseuri, remoteCertificateValidationCallback)
        {
            if (!Enum.IsDefined(typeof(ErrorCorrectionLevel), errorCorrectionLevel))
            {
                throw new ArgumentOutOfRangeException("errorCorrectionLevel");
            }
            this.ErrorCorrectionLevel = errorCorrectionLevel;

            if (marginRows < 0)
            {
                throw new ArgumentOutOfRangeException("marginRows");
            }
            this.MarginRows = marginRows;
        }
 public void testForBits()
 {
     Assert.AreEqual(ErrorCorrectionLevel.M, ErrorCorrectionLevel.forBits(0));
     Assert.AreEqual(ErrorCorrectionLevel.L, ErrorCorrectionLevel.forBits(1));
     Assert.AreEqual(ErrorCorrectionLevel.H, ErrorCorrectionLevel.forBits(2));
     Assert.AreEqual(ErrorCorrectionLevel.Q, ErrorCorrectionLevel.forBits(3));
     try
     {
         ErrorCorrectionLevel.forBits(4);
         throw new AssertionException("Should have thrown an exception");
     }
     catch (ArgumentException)
     {
         // good
     }
 }
Exemplo n.º 34
0
 /// <summary>
 /// Get Error Correction Blocks by level
 /// </summary>
 /// <param name="ECLevel">The EC level.</param>
 /// <returns></returns>
 /// <remarks></remarks>
 //[method
 internal ErrorCorrectionBlocks GetECBlocksByLevel(ErrorCorrectionLevel ECLevel)
 {
     switch (ECLevel)
     {
         case ErrorCorrectionLevel.L:
             return m_ECBlocks[0];
         case ErrorCorrectionLevel.M:
             return m_ECBlocks[1];
         case ErrorCorrectionLevel.Q:
             return m_ECBlocks[2];
         case ErrorCorrectionLevel.H:
             return m_ECBlocks[3];
         default:
             throw new ArgumentOutOfRangeException("Invalide ErrorCorrectionLevel");
     }
 }
Exemplo n.º 35
0
 /// <summary>
 /// Zpl QrCode
 /// </summary>
 /// <param name="content"></param>
 /// <param name="positionX"></param>
 /// <param name="positionY"></param>
 /// <param name="model">1 (original) and 2 (enhanced – recommended)</param>
 /// <param name="magnificationFactor">Size of the QR code, 1 on 150 dpi printers, 2 on 200 dpi printers, 3 on 300 dpi printers, 6 on 600 dpi printers</param>
 /// <param name="errorCorrectionLevel"></param>
 /// <param name="maskValue">0-7, (default: 7)</param>
 public ZplQrCode(
     string content,
     int positionX,
     int positionY,
     int model = 2,
     int magnificationFactor = 2,
     ErrorCorrectionLevel errorCorrectionLevel = ErrorCorrectionLevel.HighReliability,
     int maskValue = 7)
     : base(positionX, positionY)
 {
     Content              = content;
     Model                = model;
     MagnificationFactor  = magnificationFactor;
     ErrorCorrectionLevel = errorCorrectionLevel;
     MaskValue            = maskValue;
 }
Exemplo n.º 36
0
        /// <summary>
        /// Encodes the specified content.
        /// </summary>
        /// <param name="content">The content.</param>
        /// <param name="errorLevel">The error level.</param>
        /// <returns></returns>
        /// <remarks></remarks>
        internal static BitMatrix Encode(string content, ErrorCorrectionLevel errorLevel)
        {
            EncodationStruct encodeStruct = DataEncode.Encode(content, errorLevel);

            BitList codewords = ECGenerator.FillECCodewords(encodeStruct.DataCodewords, encodeStruct.VersionDetail);

            var triMatrix = new TriStateMatrix(encodeStruct.VersionDetail.MatrixWidth);

            PositioninngPatternBuilder.EmbedBasicPatterns(encodeStruct.VersionDetail.Version, triMatrix);

            triMatrix.EmbedVersionInformation(encodeStruct.VersionDetail.Version);
            triMatrix.EmbedFormatInformation(errorLevel, new Pattern0());
            triMatrix.TryEmbedCodewords(codewords);

            return(triMatrix.GetLowestPenaltyMatrix(errorLevel));
        }
Exemplo n.º 37
0
        public static BarcodeWriterPixelData createBarcodeWriterPixelData(ErrorCorrectionLevel correction, int size = 30, int margin = 0)
        {
            var qrCodeWriter = new BarcodeWriterPixelData
            {
                Format  = BarcodeFormat.QR_CODE,
                Options = new QrCodeEncodingOptions
                {
                    Height          = size,
                    Width           = size,
                    Margin          = margin,
                    ErrorCorrection = correction
                },
            };

            return(qrCodeWriter);
        }
        private static uint GetBinaryIndicatorForErrorCorrectionLevel(ErrorCorrectionLevel level)
        {
            // See ISO/IEC 18004:2006(E), Sec. 6.9.1, Table 12
            switch (level)
            {
            case ErrorCorrectionLevel.L: return(1);

            case ErrorCorrectionLevel.M: return(0);

            case ErrorCorrectionLevel.Q: return(3);

            case ErrorCorrectionLevel.H: return(2);
            }

            throw new InvalidOperationException();
        }
Exemplo n.º 39
0
        internal static EncodationStruct Encode(string content, ErrorCorrectionLevel ecLevel)
        {
            RecognitionStruct recognitionResult = InputRecognise.Recognise(content);
            EncoderBase       encoderBase       = CreateEncoder(recognitionResult.EncodingName);

            BitList encodeContent = encoderBase.GetDataBits(content);

            int encodeContentLength = encodeContent.Count;

            VersionControlStruct vcStruct =
                VersionControl.InitialSetup(encodeContentLength, ecLevel, recognitionResult.EncodingName);

            BitList dataCodewords = new();

            // Eci header
            if (vcStruct.IsContainECI && vcStruct.ECIHeader is { })
Exemplo n.º 40
0
        public ErrorCorrectionInfo GetCorrectionInfo(ErrorCorrectionLevel level)
        {
            switch (level)
            {
            case ErrorCorrectionLevel.L: return(L);

            case ErrorCorrectionLevel.M: return(M);

            case ErrorCorrectionLevel.Q: return(Q);

            case ErrorCorrectionLevel.H: return(H);

            default:
                Debug.Fail("Unknown value.");
                throw new ArgumentOutOfRangeException();
            }
        }
Exemplo n.º 41
0
        /// <summary>
        /// 生成二维码
        /// </summary>
        /// <param name="strContent"></param>
        /// <returns></returns>
        public MemoryStream GetQRCode(string strContent)
        {
            MemoryStream         ms     = new MemoryStream();
            ErrorCorrectionLevel Ecl    = ErrorCorrectionLevel.M; //误差校正水平
            string           Content    = strContent;             //待编码内容
            QuietZoneModules QuietZones = QuietZoneModules.Two;   //空白区域
            int    ModuleSize           = 12;                     //大小
            var    encoder = new QrEncoder(Ecl);
            QrCode qr;

            if (encoder.TryEncode(Content, out qr))//对内容进行编码,并保存生成的矩阵
            {
                var render = new GraphicsRenderer(new FixedModuleSize(ModuleSize, QuietZones));
                render.WriteToStream(qr.Matrix, ImageFormat.Png, ms);
            }
            return(ms);
        }
Exemplo n.º 42
0
        // Encode "bytes" with the error correction level "getECLevel". The encoding mode will be chosen
        // internally by chooseMode(). On success, store the result in "qrCode" and return true.
        // 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.
        public static void encode(String content, ErrorCorrectionLevel ecLevel, QRCode qrCode)
        {
            // Step 1: Choose the mode (encoding).
            Mode mode = chooseMode(content);

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

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

            initQRCode(numInputBytes, ecLevel, mode, qrCode);

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

            appendModeInfo(qrCode.getMode(), headerAndDataBits);
            appendLengthInfo(content.Length, qrCode.getVersion(), qrCode.getMode(), headerAndDataBits);
            headerAndDataBits.appendBitVector(dataBits);

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

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

            interleaveWithECBytes(headerAndDataBits, qrCode.getNumTotalBytes(), qrCode.getNumDataBytes(),
                                  qrCode.getNumRSBlocks(), finalBits);

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

            qrCode.setMaskPattern(chooseMaskPattern(finalBits, qrCode.getECLevel(), qrCode.getVersion(),
                                                    matrix));

            // Step 8.  Build the matrix and set it to "qrCode".
            MatrixUtil.buildMatrix(finalBits, qrCode.getECLevel(), qrCode.getVersion(),
                                   qrCode.getMaskPattern(), matrix);
            qrCode.setMatrix(matrix);
            // Step 9.  Make sure we have a valid QR Code.
            if (!qrCode.isValid())
            {
                throw new WriterException("Invalid QR code: " + qrCode.toString());
            }
        }
Exemplo n.º 43
0
        /// <summary>
        /// RSブロック数を返します。
        /// </summary>
        /// <param name="ecLevel">誤り訂正レベル</param>
        /// <param name="version">型番</param>
        /// <param name="preceding">RSブロック前半部分は true を指定します。</param>
        public static int GetTotalNumber(
            ErrorCorrectionLevel ecLevel, int version, bool preceding)
        {
            int numDataCodewords = DataCodeword.GetTotalNumber(ecLevel, version);
            int numRSBlocks      = _totalNumbers[(int)ecLevel][version];

            int numFolBlocks = numDataCodewords % numRSBlocks;

            if (preceding)
            {
                return(numRSBlocks - numFolBlocks);
            }
            else
            {
                return(numFolBlocks);
            }
        }
Exemplo n.º 44
0
        internal static EncodationStruct Encode(IEnumerable <byte> content, ErrorCorrectionLevel eclevel)
        {
            EncoderBase encoderBase = CreateEncoder(QRCodeConstantVariable.DefaultEncoding);

            BitList encodeContent = new BitList(content);

            int encodeContentLength = encodeContent.Count;

            VersionControlStruct vcStruct =
                VersionControl.InitialSetup(encodeContentLength, eclevel, QRCodeConstantVariable.DefaultEncoding);

            BitList dataCodewords = new BitList();

            //Eci header
            if (vcStruct.IsContainECI && !(vcStruct.ECIHeader is null))
            {
                dataCodewords.Add(vcStruct.ECIHeader);
            }
            //Header
            dataCodewords.Add(encoderBase.GetModeIndicator());
            int numLetter = encodeContentLength >> 3;

            dataCodewords.Add(encoderBase.GetCharCountIndicator(numLetter, vcStruct.VersionDetail.Version));
            //Data
            dataCodewords.Add(encodeContent);
            //Terminator Padding
            dataCodewords.TerminateBites(dataCodewords.Count, vcStruct.VersionDetail.NumDataBytes);

            int dataCodewordsCount = dataCodewords.Count;

            if ((dataCodewordsCount & 0x7) != 0)
            {
                throw new ArgumentException("data codewords is not byte sized.");
            }
            else if (dataCodewordsCount >> 3 != vcStruct.VersionDetail.NumDataBytes)
            {
                throw new ArgumentException("datacodewords num of bytes not equal to NumDataBytes for current version");
            }

            var encStruct = new EncodationStruct(vcStruct)
            {
                DataCodewords = dataCodewords
            };

            return(encStruct);
        }
Exemplo n.º 45
0
 public VersionInfo(
     byte version,
     ErrorCorrectionLevel errorCorrectionLevel,
     byte errorCorrectionCodewordsPerBlock,
     byte numberOfBlocksInGroup1,
     byte dataCodewordsPerBlockInGroup1,
     byte numberOfBlocksInGroup2,
     byte dataCodewordsPerBlockInGroup2)
 {
     Version = version;
     ErrorCorrectionLevel             = errorCorrectionLevel;
     ErrorCorrectionCodewordsPerBlock = errorCorrectionCodewordsPerBlock;
     NumberOfBlocksInGroup1           = numberOfBlocksInGroup1;
     DataCodewordsPerBlockInGroup1    = dataCodewordsPerBlockInGroup1;
     NumberOfBlocksInGroup2           = numberOfBlocksInGroup2;
     DataCodewordsPerBlockInGroup2    = dataCodewordsPerBlockInGroup2;
 }
Exemplo n.º 46
0
  public void Test_against_reference_implementation(int numDataBits,  Mode mode, ErrorCorrectionLevel level, string encodingName)
  {
  	VersionControlStruct vcStruct = VersionControl.InitialSetup(numDataBits, mode, level, encodingName);
  	VersionCheckStatus checkStatus = VersionTest.VersionCheck(vcStruct.VersionDetail.Version, numDataBits, mode, level, encodingName);
  	
  	switch(checkStatus)
  	{
  		case VersionCheckStatus.LargerThanExpect:
  			Assert.Fail("Version {0} size not enough", vcStruct.VersionDetail.Version);
  			break;
  		case VersionCheckStatus.SmallerThanExpect:
  			Assert.Fail("Version{0}'s size too big", vcStruct.VersionDetail.Version);
  			break;
  		default:
  			break;
  	}
 
  }
Exemplo n.º 47
0
        /// <summary>
        /// Determine which version to use
        /// </summary>
        /// <param name="dataBitsLength">Number of bits for encoded content</param>
        /// <param name="mode">The mode.</param>
        /// <param name="level">The level.</param>
        /// <param name="encodingName">Encoding name for EightBitByte</param>
        /// <returns>VersionDetail and ECI</returns>
        /// <remarks></remarks>
        internal static VersionControlStruct InitialSetup(int dataBitsLength, Mode mode, ErrorCorrectionLevel level,
                                                          string encodingName)
        {
            int totalDataBits = dataBitsLength;

            bool containECI = false;

            var eciHeader = new BitList();


            //Check ECI header
            if (mode == Mode.EightBitByte)
            {
                if (encodingName != DEFAULT_ENCODING && encodingName != QRCodeConstantVariable.UTF8Encoding)
                {
                    var eciSet = new ECISet(ECISet.AppendOption.NameToValue);
                    int eciValue = eciSet.GetECIValueByName(encodingName);

                    totalDataBits += ECISet.NumOfECIHeaderBits(eciValue);
                    eciHeader = eciSet.GetECIHeader(encodingName);
                    containECI = true;
                }
            }
            //Determine which version group it belong to
            int searchGroup = DynamicSearchIndicator(totalDataBits, level, mode);

            int[] charCountIndicator = CharCountIndicatorTable.GetCharCountIndicatorSet(mode);

            totalDataBits += (NUM_BITS_MODE_INDICATOR + charCountIndicator[searchGroup]);

            int lowerSearchBoundary = searchGroup == 0 ? 1 : (VERSION_GROUP[searchGroup - 1] + 1);
            int higherSearchBoundary = VERSION_GROUP[searchGroup];

            //Binary search to find proper version
            int versionNum = BinarySearch(totalDataBits, level, lowerSearchBoundary, higherSearchBoundary);

            VersionControlStruct vcStruct = FillVCStruct(versionNum, level, encodingName);

            vcStruct.isContainECI = containECI;

            vcStruct.ECIHeader = eciHeader;

            return vcStruct;
        }
Exemplo n.º 48
0
        public static BitmapImage getQrBitmap(string text, ErrorCorrectionLevel errorCorrection = ErrorCorrectionLevel.M)
        {
            QrCode qrCode;
            QrEncoder qrEncoder = new QrEncoder(errorCorrection);
            qrEncoder.TryEncode(text, out qrCode);

            GraphicsRenderer gRenderer = new GraphicsRenderer(
                new FixedModuleSize(2, QuietZoneModules.Two),
                Brushes.Black, Brushes.White);
            BitmapImage bi = new BitmapImage();
            using (MemoryStream memoryStream = new MemoryStream())
            {
                gRenderer.WriteToStream(qrCode.Matrix, ImageFormat.Png, memoryStream);
                bi.BeginInit();
                bi.CacheOption = BitmapCacheOption.OnLoad;
                bi.StreamSource = memoryStream;
                bi.EndInit();
            }
            return bi;
        }
Exemplo n.º 49
0
 internal static BitMatrix GetLowestPenaltyMatrix(this TriStateMatrix matrix, ErrorCorrectionLevel errorlevel)
 {
     PatternFactory patternFactory = new PatternFactory();
     int score = int.MaxValue;
     int tempScore;
     TriStateMatrix result = new TriStateMatrix(matrix.Width);
     TriStateMatrix triMatrix;
     foreach(Pattern pattern in patternFactory.AllPatterns())
     {
     	triMatrix = matrix.Apply(pattern, errorlevel);
     	tempScore = triMatrix.PenaltyScore();
     	if(tempScore < score)
     	{
     		score = tempScore;
     		result = triMatrix;
     	}
     }
     
     return result;
 }
Exemplo n.º 50
0
        private static BitList GetFormatInfoBits(ErrorCorrectionLevel errorlevel, Pattern pattern)
        {
            int formatInfo = (int)pattern.MaskPatternType;
            //Pattern bits length = 3
            formatInfo |= GetErrorCorrectionIndicatorBits(errorlevel) << 3;

            int bchCode = BCHCalculator.CalculateBCH(formatInfo, s_FormatInfoPoly);
            //bchCode length = 10
            formatInfo = (formatInfo << 10) | bchCode;

            //xor maskPattern
            formatInfo ^= s_FormatInfoMaskPattern;

            BitList resultBits = new BitList();
            resultBits.Add(formatInfo, 15);

            if(resultBits.Count != 15)
                throw new Exception("FormatInfoBits length is not 15");
            else
                return resultBits;
        }
Exemplo n.º 51
0
 	/// <summary>
 	/// Embed format information to tristatematrix. 
 	/// Process combination of create info bits, BCH error correction bits calculation, embed towards matrix. 
 	/// </summary>
 	/// <remarks>ISO/IEC 18004:2000 Chapter 8.9 Page 53</remarks>
 	internal static void EmbedFormatInformation(this TriStateMatrix triMatrix,  ErrorCorrectionLevel errorlevel, Pattern pattern)
 	{
 		BitList formatInfo = GetFormatInfoBits(errorlevel, pattern);
 		int width = triMatrix.Width;
 		for(int index = 0; index < 15; index++)
 		{
 			MatrixPoint point = PointForInfo1(index);
 			bool bit = formatInfo[index];
 			triMatrix[point.X, point.Y, MatrixStatus.NoMask] = bit;
 			
 			if(index < 7)
 			{
 				triMatrix[8, width - 1 - index, MatrixStatus.NoMask] = bit;
 			}
 			else
 			{
 				triMatrix[width - 8 + (index - 7), 8, MatrixStatus.NoMask] = bit;
 			}
 			
 		}
 	}
Exemplo n.º 52
0
        /// <summary>
        /// Encodes the specified content.
        /// </summary>
        /// <param name="content">The content.</param>
        /// <param name="ecLevel">The ec level.</param>
        /// <returns></returns>
        /// <remarks></remarks>
        internal static EncodationStruct Encode(string content, ErrorCorrectionLevel ecLevel)
        {
            RecognitionStruct recognitionResult = InputRecognise.Recognise(content);
            EncoderBase encoderBase = CreateEncoder(recognitionResult.Mode, recognitionResult.EncodingName);

            BitList encodeContent = encoderBase.GetDataBits(content);

            int encodeContentLength = encodeContent.Count;

            VersionControlStruct vcStruct =
                VersionControl.InitialSetup(encodeContentLength, recognitionResult.Mode, ecLevel,
                                            recognitionResult.EncodingName);

            var dataCodewords = new BitList();
            //Eci header
            if (vcStruct.isContainECI && vcStruct.ECIHeader != null)
                dataCodewords.Add(vcStruct.ECIHeader);
            //Header
            dataCodewords.Add(encoderBase.GetModeIndicator());
            int numLetter = recognitionResult.Mode == Mode.EightBitByte ? encodeContentLength >> 3 : content.Length;
            dataCodewords.Add(encoderBase.GetCharCountIndicator(numLetter, vcStruct.VersionDetail.Version));
            //Data
            dataCodewords.Add(encodeContent);
            //Terminator Padding
            dataCodewords.TerminateBites(dataCodewords.Count, vcStruct.VersionDetail.NumDataBytes);

            int dataCodewordsCount = dataCodewords.Count;
            if ((dataCodewordsCount & 0x7) != 0)
                throw new ArgumentException("data codewords is not byte sized.");
            else if (dataCodewordsCount >> 3 != vcStruct.VersionDetail.NumDataBytes)
            {
                throw new ArgumentException("datacodewords num of bytes not equal to NumDataBytes for current version");
            }

            var encStruct = new EncodationStruct(vcStruct);
            encStruct.Mode = recognitionResult.Mode;
            encStruct.DataCodewords = dataCodewords;
            return encStruct;
        }
Exemplo n.º 53
0
        /// <summary>
        /// Méthode retournant un objet d'image Bitmap d'un code QR
        /// </summary>
        /// <param name="text">Le texte à encoder</param>
        /// <param name="errorCorrection">Le niveau de correction d'erreur choisi. Détermine le pourcentage de la structure du codeQR est utilisé pour corriger les erreurs.</param>
        /// <returns>Objet BitmapImage du codeQR</returns>
        public static BitmapImage getQrBitmap(string text, ErrorCorrectionLevel errorCorrection = ErrorCorrectionLevel.M)
        {
            QrCode qrCode;
            QrEncoder qrEncoder = new QrEncoder(errorCorrection);
            //Peut techniquement échouer et le cas n'est pas géré.
            qrEncoder.TryEncode(text, out qrCode);

            //Détermine l'épaisseur des traits, la couleur de fond et la couleur du code QR.
            GraphicsRenderer gRenderer = new GraphicsRenderer(
                new FixedModuleSize(2, QuietZoneModules.Two),
                Brushes.Black, Brushes.White);
            BitmapImage bi = new BitmapImage();
            using (MemoryStream memoryStream = new MemoryStream())
            {
                //Utilise les bytes du codeQR encodé qui se trouve dans l'objet qrCode dans un MemoryStream pour faire une BitmapImage.
                gRenderer.WriteToStream(qrCode.Matrix, ImageFormat.Png, memoryStream);
                bi.BeginInit();
                bi.CacheOption = BitmapCacheOption.OnLoad;
                bi.StreamSource = memoryStream;
                bi.EndInit();
            }
            return bi;
        }
Exemplo n.º 54
0
        //According Table 25 — Error correction level indicators
        //Using this bits as enum values would destroy thir order which currently correspond to error correction strength.
        internal static int GetErrorCorrectionIndicatorBits(ErrorCorrectionLevel errorLevel)
        {
            //L 01
            //M 00
            //Q 11
            //H 10
            switch (errorLevel)
            {
                case ErrorCorrectionLevel.H:
                    return 0x02;

                case ErrorCorrectionLevel.L:
                    return 0x01;

                case ErrorCorrectionLevel.M:
                    return 0x00;

                case ErrorCorrectionLevel.Q:
                    return 0x03;
                   default:
                    throw new ArgumentException(string.Format("Unsupported error correction level [{0}]", errorLevel), "errorLevel");
            }
        }
Exemplo n.º 55
0
        internal static EncodationStruct Encode(IEnumerable<byte> content, ErrorCorrectionLevel eclevel)
        {
            EncoderBase encoderBase = CreateEncoder(Mode.EightBitByte, QRCodeConstantVariable.DefaultEncoding);

            BitList encodeContent = new BitList(content);

            int encodeContentLength = encodeContent.Count;

            VersionControlStruct vcStruct =
                VersionControl.InitialSetup(encodeContentLength, Mode.EightBitByte, eclevel, QRCodeConstantVariable.DefaultEncoding);

            BitList dataCodewords = new BitList();
            //Eci header
            if (vcStruct.isContainECI && vcStruct.ECIHeader != null)
                dataCodewords.Add(vcStruct.ECIHeader);
            //Header
            dataCodewords.Add(encoderBase.GetModeIndicator());
            int numLetter = encodeContentLength >> 3;
            dataCodewords.Add(encoderBase.GetCharCountIndicator(numLetter, vcStruct.VersionDetail.Version));
            //Data
            dataCodewords.Add(encodeContent);
            //Terminator Padding
            dataCodewords.TerminateBites(dataCodewords.Count, vcStruct.VersionDetail.NumDataBytes);

            int dataCodewordsCount = dataCodewords.Count;
            if ((dataCodewordsCount & 0x7) != 0)
                throw new ArgumentException("data codewords is not byte sized.");
            else if (dataCodewordsCount >> 3 != vcStruct.VersionDetail.NumDataBytes)
            {
                throw new ArgumentException("datacodewords num of bytes not equal to NumDataBytes for current version");
            }

            EncodationStruct encStruct = new EncodationStruct(vcStruct);
            encStruct.Mode = Mode.EightBitByte;
            encStruct.DataCodewords = dataCodewords;
            return encStruct;
        }
Exemplo n.º 56
0
		private static VersionControlStruct FillVCStruct(int versionNum, ErrorCorrectionLevel level, string encodingName)
		{
			if(versionNum < 1 || versionNum > 40)
			{
				throw new InvalidOperationException(string.Format("Unexpected version number: {0}", versionNum));
			}
			
			VersionControlStruct vcStruct = new VersionControlStruct();
			
			int version = versionNum;
			
			QRCodeVersion versionData = VersionTable.GetVersionByNum(versionNum);
			
			int numTotalBytes = versionData.TotalCodewords;
			
			ErrorCorrectionBlocks ecBlocks = versionData.GetECBlocksByLevel(level);
			int numDataBytes = numTotalBytes - ecBlocks.NumErrorCorrectionCodewards;
			int numECBlocks = ecBlocks.NumBlocks;
			
			VersionDetail vcDetail = new VersionDetail(version, numTotalBytes, numDataBytes, numECBlocks);
			
			vcStruct.VersionDetail = vcDetail;
			return vcStruct;
		}
Exemplo n.º 57
0
        public static Image GetQRCode(byte[] data, ErrorCorrectionLevel level = ErrorCorrectionLevel.M)
        {
            bool requires16BitLength = false;
            int maxBytesInVersion9Code = QRErrorCorrections.GetQRVersionInfo(9).GetCorrectionInfo(level).TotalDataBytes;
            if (maxBytesInVersion9Code - 2 < data.Length)
            {
                // This data requires a version 10 or higher code; will not fit in version 9 or lower.
                // Version 10 and higher codes require 16-bit data lengths.
                requires16BitLength = true;
            }

            StreamHelper sh = new StreamHelper();
            sh.WriteNibble(0x04); // byte mode
            if (requires16BitLength)
            {
                sh.WriteWord((ushort)data.Length);
            }
            else
            {
                sh.WriteByte((byte)data.Length);
            }
            sh.WriteBytes(new ArraySegment<byte>(data));
            sh.WriteNibble(0x00); // terminator
            byte[] binaryData = sh.ToArray();

            int qrCodeVersion;
            ErrorCorrectionLevel errorCorrectionLevel;
            byte[] finalMessageSequence = QRErrorCorrections.GetMessageSequence(binaryData, level, out qrCodeVersion, out errorCorrectionLevel);

            SymbolTemplate template = SymbolTemplate.CreateTemplate(qrCodeVersion);
            template.ErrorCorrectionLevel = errorCorrectionLevel;
            template.PopulateData(finalMessageSequence);
            template.Complete();

            return template.ToImage();
        }
Exemplo n.º 58
0
 /// <summary>
 /// Initializes a new instance of the <see cref="QRCodes"/> class.
 /// </summary>
 /// <param name="size">The chart size.</param>
 /// <param name="text">The text to encode.</param>
 /// <param name="encodingType">Type of the encoding.</param>
 /// <param name="errorCorrection">Error correction level</param>
 /// <param name="margin">Margin</param>
 public QRCodes(ChartSize size, string text, EncodingType encodingType, ErrorCorrectionLevel errorCorrection, int margin)
     : this(size, text, encodingType)
 {
     if ((errorCorrection != DefaultErrorCorrectionLevel) && (margin != DefaultMargin))
     {
         _options = new QROptions(errorCorrection, margin);
     }
 }
Exemplo n.º 59
0
 /// <summary>
 /// QrEncoder with parameter ErrorCorrectionLevel. 
 /// </summary>
 /// <param name="errorCorrectionLevel"></param>
 public QrEncoder(ErrorCorrectionLevel errorCorrectionLevel)
 {
     ErrorCorrectionLevel = errorCorrectionLevel;
 }
Exemplo n.º 60
0
 public void Test_against_reference_implementation(string inputString, ErrorCorrectionLevel eclevel, IEnumerable<bool> expected)
 {
 	TestOneCase(inputString, eclevel, expected);
 }