A simple, fast array of bits, represented compactly by an array of ints internally.
Exemplo n.º 1
0
 /// <summary>
 ///   <p>Like decodeRow(int, BitArray, java.util.Map), but
 /// allows caller to inform method about where the UPC/EAN start pattern is
 /// found. This allows this to be computed once and reused across many implementations.</p>
 /// </summary>
 /// <param name="rowNumber"></param>
 /// <param name="row"></param>
 /// <param name="startGuardRange"></param>
 /// <param name="hints"></param>
 /// <returns></returns>
 override public Result decodeRow(int rowNumber,
                         BitArray row,
                         int[] startGuardRange,
                         IDictionary<DecodeHintType, object> hints)
 {
    return maybeReturnResult(ean13Reader.decodeRow(rowNumber, row, startGuardRange, hints));
 }
Exemplo n.º 2
0
      /// <summary>
      /// Decodes the middle.
      /// </summary>
      /// <param name="row">The row.</param>
      /// <param name="startRange">The start range.</param>
      /// <param name="result">The result.</param>
      /// <returns></returns>
      override internal protected int decodeMiddle(BitArray row, int[] startRange, StringBuilder result)
      {
         int[] counters = decodeMiddleCounters;
         counters[0] = 0;
         counters[1] = 0;
         counters[2] = 0;
         counters[3] = 0;
         int end = row.Size;
         int rowOffset = startRange[1];

         int lgPatternFound = 0;

         for (int x = 0; x < 6 && rowOffset < end; x++)
         {
            int bestMatch;
            if (!decodeDigit(row, counters, rowOffset, L_AND_G_PATTERNS, out bestMatch))
               return -1;
            result.Append((char)('0' + bestMatch % 10));
            foreach (int counter in counters)
            {
               rowOffset += counter;
            }
            if (bestMatch >= 10)
            {
               lgPatternFound |= 1 << (5 - x);
            }
         }

         if (!determineNumSysAndCheckDigit(result, lgPatternFound))
            return -1;

         return rowOffset;
      }
Exemplo n.º 3
0
      /// <summary>
      /// Constructs a BitArray from a String like the one returned from BitArray.toString()
      /// </summary>
      public static BitArray buildBitArrayFromString(String data)
      {
         String dotsAndXs = Regex.Replace(Regex.Replace(data, ONE, "X"), ZERO, ".");
         BitArray binary = new BitArray(Regex.Replace(dotsAndXs, SPACE, "").Length);
         int counter = 0;

         for (int i = 0; i < dotsAndXs.Length; ++i)
         {
            if (i % 9 == 0)
            { // spaces
               if (dotsAndXs[i] != ' ')
               {
                  throw new InvalidOperationException("space expected");
               }
               continue;
            }

            char currentChar = dotsAndXs[i];
            if (currentChar == 'X' || currentChar == 'x')
            {
               binary[counter] = true;
            }
            counter++;
         }
         return binary;
      }
Exemplo n.º 4
0
 public override void appendTo(BitArray bitArray, byte[] text)
 {
    for (int i = 0; i < binaryShiftByteCount; i++)
    {
       if (i == 0 || (i == 31 && binaryShiftByteCount <= 62))
       {
          // We need a header before the first character, and before
          // character 31 when the total byte code is <= 62
          bitArray.appendBits(31, 5);  // BINARY_SHIFT
          if (binaryShiftByteCount > 62)
          {
             bitArray.appendBits(binaryShiftByteCount - 31, 16);
          }
          else if (i == 0)
          {
             // 1 <= binaryShiftByteCode <= 62
             bitArray.appendBits(Math.Min(binaryShiftByteCount, (short) 31), 5);
          }
          else
          {
             // 32 <= binaryShiftCount <= 62 and i == 31
             bitArray.appendBits(binaryShiftByteCount - 31, 5);
          }
       }
       bitArray.appendBits(text[binaryShiftStart + i], 8);
    }
 }
Exemplo n.º 5
0
 /// <summary>
 ///   <p>Attempts to decode a one-dimensional barcode format given a single row of
 /// an image.</p>
 /// </summary>
 /// <param name="rowNumber">row number from top of the row</param>
 /// <param name="row">the black/white pixel data of the row</param>
 /// <param name="hints">decode hints</param>
 /// <returns>
 ///   <see cref="Result"/>containing encoded string and start/end of barcode or null, if an error occurs or barcode cannot be found
 /// </returns>
 override public Result decodeRow(int rowNumber,
                         BitArray row,
                         IDictionary<DecodeHintType, object> hints)
 {
    Pair leftPair = decodePair(row, false, rowNumber, hints);
    addOrTally(possibleLeftPairs, leftPair);
    row.reverse();
    Pair rightPair = decodePair(row, true, rowNumber, hints);
    addOrTally(possibleRightPairs, rightPair);
    row.reverse();
    int lefSize = possibleLeftPairs.Count;
    for (int i = 0; i < lefSize; i++)
    {
       Pair left = possibleLeftPairs[i];
       if (left.Count > 1)
       {
          int rightSize = possibleRightPairs.Count;
          for (int j = 0; j < rightSize; j++)
          {
             Pair right = possibleRightPairs[j];
             if (right.Count > 1)
             {
                if (checkChecksum(left, right))
                {
                   return constructResult(left, right);
                }
             }
          }
       }
    }
    return null;
 }
      internal Result decodeRow(int rowNumber, BitArray row, int[] extensionStartRange)
      {
         StringBuilder result = decodeRowStringBuffer;
         result.Length = 0;
         int end = decodeMiddle(row, extensionStartRange, result);
         if (end < 0)
            return null;

         String resultString = result.ToString();
         IDictionary<ResultMetadataType, Object> extensionData = parseExtensionString(resultString);

         Result extensionResult =
             new Result(resultString,
                        null,
                        new ResultPoint[] {
                       new ResultPoint((extensionStartRange[0] + extensionStartRange[1]) / 2.0f, (float) rowNumber),
                       new ResultPoint((float) end, (float) rowNumber),
                   },
                        BarcodeFormat.UPC_EAN_EXTENSION);
         if (extensionData != null)
         {
            extensionResult.putAllMetadata(extensionData);
         }
         return extensionResult;
      }
Exemplo n.º 7
0
 /// <summary>
 ///   <p>Attempts to decode a one-dimensional barcode format given a single row of
 /// an image.</p>
 /// </summary>
 /// <param name="rowNumber">row number from top of the row</param>
 /// <param name="row">the black/white pixel data of the row</param>
 /// <param name="hints">decode hints</param>
 /// <returns>
 ///   <see cref="Result"/>containing encoded string and start/end of barcode or null, if an error occurs or barcode cannot be found
 /// </returns>
 override public Result decodeRow(int rowNumber,
                         BitArray row,
                         IDictionary<DecodeHintType, object> hints)
 {
    Pair leftPair = decodePair(row, false, rowNumber, hints);
    addOrTally(possibleLeftPairs, leftPair);
    row.reverse();
    Pair rightPair = decodePair(row, true, rowNumber, hints);
    addOrTally(possibleRightPairs, rightPair);
    row.reverse();
    foreach (Pair left in possibleLeftPairs)
    {
       if (left.Count > 1)
       {
          foreach (Pair right in possibleRightPairs)
          {
             if (right.Count > 1)
             {
                if (checkChecksum(left, right))
                {
                   return constructResult(left, right);
                }
             }
          }
       }
    }
    return null;
 }
 /// <summary>
 /// Copies the bits from the input to the result BitArray in reverse order.
 /// SF: Not sure how this is different than BitArray.Reverse();
 /// </summary>
 /// <param name="input">Input.</param>
 /// <param name="result">Result.</param>
 private static void Mirror(BitArray input, ref BitArray result)
 {
     result.clear();
     int size = input.Size;
     for (int i = 0; i < size; i++)
     {
         result[size - 1 - i] = input[i];
     }
 }
Exemplo n.º 9
0
 internal Result decodeRow(int rowNumber, BitArray row, int rowOffset)
 {
    int[] extensionStartRange = UPCEANReader.findGuardPattern(row, rowOffset, false, EXTENSION_START_PATTERN);
    if (extensionStartRange == null)
       return null;
    var result = fiveSupport.decodeRow(rowNumber, row, extensionStartRange);
    if (result == null)
       result = twoSupport.decodeRow(rowNumber, row, extensionStartRange);
    return result;
 }
Exemplo n.º 10
0
      internal static BitArray buildBitArray(List<ExpandedPair> pairs)
      {
         int charNumber = (pairs.Count << 1) - 1;
         if (pairs[pairs.Count - 1].RightChar == null)
         {
            charNumber -= 1;
         }

         int size = 12 * charNumber;

         BitArray binary = new BitArray(size);
         int accPos = 0;

         ExpandedPair firstPair = pairs[0];
         int firstValue = firstPair.RightChar.Value;
         for (int i = 11; i >= 0; --i)
         {
            if ((firstValue & (1 << i)) != 0)
            {
               binary[accPos] = true;
            }
            accPos++;
         }

         for (int i = 1; i < pairs.Count; ++i)
         {
            ExpandedPair currentPair = pairs[i];

            int leftValue = currentPair.LeftChar.Value;
            for (int j = 11; j >= 0; --j)
            {
               if ((leftValue & (1 << j)) != 0)
               {
                  binary[accPos] = true;
               }
               accPos++;
            }

            if (currentPair.RightChar != null)
            {
               int rightValue = currentPair.RightChar.Value;
               for (int j = 11; j >= 0; --j)
               {
                  if ((rightValue & (1 << j)) != 0)
                  {
                     binary[accPos] = true;
                  }
                  accPos++;
               }
            }
         }
         return binary;
      }
Exemplo n.º 11
0
 private static long getUnsignedInt(BitArray v, int index)
 {
    long result = 0L;
    for (int i = 0, offset = index << 3; i < 32; i++)
    {
       if (v[offset + i])
       {
          result |= 1L << (31 - i);
       }
    }
    return result;
 }
Exemplo n.º 12
0
      /// <summary>
      /// Subclasses override this to decode the portion of a barcode between the start
      /// and end guard patterns.
      /// </summary>
      /// <param name="row">row of black/white values to search</param>
      /// <param name="startRange">start/end offset of start guard pattern</param>
      /// <param name="resultString"><see cref="StringBuilder"/>to append decoded chars to</param>
      /// <returns>
      /// horizontal offset of first pixel after the "middle" that was decoded or -1 if decoding could not complete successfully
      /// </returns>
      override protected internal int decodeMiddle(BitArray row,
                                 int[] startRange,
                                 StringBuilder resultString)
      {
         int[] counters = decodeMiddleCounters;
         counters[0] = 0;
         counters[1] = 0;
         counters[2] = 0;
         counters[3] = 0;
         int end = row.Size;
         int rowOffset = startRange[1];

         int lgPatternFound = 0;

         for (int x = 0; x < 6 && rowOffset < end; x++)
         {
            int bestMatch;
            if (!decodeDigit(row, counters, rowOffset, L_AND_G_PATTERNS, out bestMatch))
               return -1;
            resultString.Append((char) ('0' + bestMatch%10));
            foreach (int counter in counters)
            {
               rowOffset += counter;
            }
            if (bestMatch >= 10)
            {
               lgPatternFound |= 1 << (5 - x);
            }
         }

         if (!determineFirstDigit(resultString, lgPatternFound))
            return -1;

         int[] middleRange = findGuardPattern(row, rowOffset, true, MIDDLE_PATTERN);
         if (middleRange == null)
            return -1;
         rowOffset = middleRange[1];

         for (int x = 0; x < 6 && rowOffset < end; x++)
         {
            int bestMatch;
            if (!decodeDigit(row, counters, rowOffset, L_PATTERNS, out bestMatch))
               return -1;
            resultString.Append((char) ('0' + bestMatch));
            foreach (int counter in counters)
            {
               rowOffset += counter;
            }
         }

         return rowOffset;
      }
Exemplo n.º 13
0
      int decodeMiddle(BitArray row, int[] startRange, StringBuilder resultString)
      {
         int[] counters = decodeMiddleCounters;
         counters[0] = 0;
         counters[1] = 0;
         counters[2] = 0;
         counters[3] = 0;
         int end = row.Size;
         int rowOffset = startRange[1];

         int lgPatternFound = 0;

         for (int x = 0; x < 5 && rowOffset < end; x++)
         {
            int bestMatch;
            if (!UPCEANReader.decodeDigit(row, counters, rowOffset, UPCEANReader.L_AND_G_PATTERNS, out bestMatch))
               return -1;
            resultString.Append((char)('0' + bestMatch % 10));
            foreach (int counter in counters)
            {
               rowOffset += counter;
            }
            if (bestMatch >= 10)
            {
               lgPatternFound |= 1 << (4 - x);
            }
            if (x != 4)
            {
               // Read off separator if not last
               rowOffset = row.getNextSet(rowOffset);
               rowOffset = row.getNextUnset(rowOffset);
            }
         }

         if (resultString.Length != 5)
         {
            return -1;
         }

         int checkDigit;
         if (!determineCheckDigit(lgPatternFound, out checkDigit))
            return -1;

         if (extensionChecksum(resultString.ToString()) != checkDigit)
         {
            return -1;
         }

         return rowOffset;
      }
Exemplo n.º 14
0
      /// <summary>
      ///   <p>Attempts to decode a one-dimensional barcode format given a single row of
      /// an image.</p>
      /// </summary>
      /// <param name="rowNumber">row number from top of the row</param>
      /// <param name="row">the black/white pixel data of the row</param>
      /// <param name="hints">decode hints</param>
      /// <returns>
      ///   <see cref="Result"/>containing encoded string and start/end of barcode or null if an error occurs or barcode cannot be found
      /// </returns>
      override public Result decodeRow(int rowNumber,
                              BitArray row,
                              IDictionary<DecodeHintType, object> hints)
      {
         // Compute this location once and reuse it on multiple implementations
         int[] startGuardPattern = UPCEANReader.findStartGuardPattern(row);
         if (startGuardPattern == null)
            return null;

         foreach (UPCEANReader reader in readers)
         {
            Result result = reader.decodeRow(rowNumber, row, startGuardPattern, hints);
            if (result == null)
               continue;

            // Special case: a 12-digit code encoded in UPC-A is identical to a "0"
            // followed by those 12 digits encoded as EAN-13. Each will recognize such a code,
            // UPC-A as a 12-digit string and EAN-13 as a 13-digit string starting with "0".
            // Individually these are correct and their readers will both read such a code
            // and correctly call it EAN-13, or UPC-A, respectively.
            //
            // In this case, if we've been looking for both types, we'd like to call it
            // a UPC-A code. But for efficiency we only run the EAN-13 decoder to also read
            // UPC-A. So we special case it here, and convert an EAN-13 result to a UPC-A
            // result if appropriate.
            //
            // But, don't return UPC-A if UPC-A was not a requested format!
            bool ean13MayBeUPCA =
                result.BarcodeFormat == BarcodeFormat.EAN_13 &&
                    result.Text[0] == '0';
            var possibleFormats =
                hints == null || !hints.ContainsKey(DecodeHintType.POSSIBLE_FORMATS) ? null : (IList<BarcodeFormat>)hints[DecodeHintType.POSSIBLE_FORMATS];
            bool canReturnUPCA = possibleFormats == null || possibleFormats.Contains(BarcodeFormat.UPC_A) || possibleFormats.Contains(BarcodeFormat.All_1D);

            if (ean13MayBeUPCA && canReturnUPCA)
            {
               // Transfer the metdata across
               var resultUPCA = new Result(result.Text.Substring(1),
                                              result.RawBytes,
                                              result.ResultPoints,
                                              BarcodeFormat.UPC_A);
               resultUPCA.putAllMetadata(result.ResultMetadata);
               return resultUPCA;
            }
            return result;
         }

         return null;
      }
Exemplo n.º 15
0
      int decodeMiddle(BitArray row, int[] startRange, StringBuilder resultString)
      {
         int[] counters = decodeMiddleCounters;
         counters[0] = 0;
         counters[1] = 0;
         counters[2] = 0;
         counters[3] = 0;
         int end = row.Size;
         int rowOffset = startRange[1];

         int checkParity = 0;

         for (int x = 0; x < 2 && rowOffset < end; x++)
         {
            int bestMatch;
            if (!UPCEANReader.decodeDigit(row, counters, rowOffset, UPCEANReader.L_AND_G_PATTERNS, out bestMatch))
               return -1;
            resultString.Append((char)('0' + bestMatch % 10));
            foreach (int counter in counters)
            {
               rowOffset += counter;
            }
            if (bestMatch >= 10)
            {
               checkParity |= 1 << (1 - x);
            }
            if (x != 1)
            {
               // Read off separator if not last
               rowOffset = row.getNextSet(rowOffset);
               rowOffset = row.getNextUnset(rowOffset);
            }
         }

         if (resultString.Length != 2)
         {
            return -1;
         }

         if (int.Parse(resultString.ToString()) % 4 != checkParity)
         {
            return -1;
         }

         return rowOffset;
      }
Exemplo n.º 16
0
 public void testAppendBit()
 {
    BitArray v = new BitArray();
    Assert.AreEqual(0, v.SizeInBytes);
    // 1
    v.appendBit(true);
    Assert.AreEqual(1, v.Size);
    Assert.AreEqual(0x80000000L, getUnsignedInt(v, 0));
    // 10
    v.appendBit(false);
    Assert.AreEqual(2, v.Size);
    Assert.AreEqual(0x80000000L, getUnsignedInt(v, 0));
    // 101
    v.appendBit(true);
    Assert.AreEqual(3, v.Size);
    Assert.AreEqual(0xa0000000L, getUnsignedInt(v, 0));
    // 1010
    v.appendBit(false);
    Assert.AreEqual(4, v.Size);
    Assert.AreEqual(0xa0000000L, getUnsignedInt(v, 0));
    // 10101
    v.appendBit(true);
    Assert.AreEqual(5, v.Size);
    Assert.AreEqual(0xa8000000L, getUnsignedInt(v, 0));
    // 101010
    v.appendBit(false);
    Assert.AreEqual(6, v.Size);
    Assert.AreEqual(0xa8000000L, getUnsignedInt(v, 0));
    // 1010101
    v.appendBit(true);
    Assert.AreEqual(7, v.Size);
    Assert.AreEqual(0xaa000000L, getUnsignedInt(v, 0));
    // 10101010
    v.appendBit(false);
    Assert.AreEqual(8, v.Size);
    Assert.AreEqual(0xaa000000L, getUnsignedInt(v, 0));
    // 10101010 1
    v.appendBit(true);
    Assert.AreEqual(9, v.Size);
    Assert.AreEqual(0xaa800000L, getUnsignedInt(v, 0));
    // 10101010 10
    v.appendBit(false);
    Assert.AreEqual(10, v.Size);
    Assert.AreEqual(0xaa800000L, getUnsignedInt(v, 0));
 }
        /// <summary>
        /// Rotates the Matrix by 180 degrees in-place
        /// </summary>
        /// <param name="bitMatrix">Bit matrix.</param>
        public static void Rotate180(this BitMatrix bitMatrix)
        {
            int width = bitMatrix.Width;
            int height = bitMatrix.Height;
            BitArray firstRowBitArray = new BitArray(width);
            BitArray secondRowBitArray = new BitArray(width);
            BitArray tmpBitArray = new BitArray(width); // re-use this to save on 'new' calls
            for (int y = 0; y < height + 1 >> 1; y++)
            {
                firstRowBitArray = bitMatrix.getRow(y, firstRowBitArray);

                Mirror(bitMatrix.getRow(height - 1 - y, secondRowBitArray), ref tmpBitArray);
                bitMatrix.setRow(y, tmpBitArray);

                Mirror(firstRowBitArray, ref tmpBitArray);
                bitMatrix.setRow(height - 1 - y, tmpBitArray);
            }
        }
Exemplo n.º 18
0
      /// <summary>
      /// Decodes the middle.
      /// </summary>
      /// <param name="row">The row.</param>
      /// <param name="startRange">The start range.</param>
      /// <param name="result">The result.</param>
      /// <returns></returns>
      override protected internal int decodeMiddle(BitArray row,
                                 int[] startRange,
                                 StringBuilder result)
      {
         int[] counters = decodeMiddleCounters;
         counters[0] = 0;
         counters[1] = 0;
         counters[2] = 0;
         counters[3] = 0;
         int end = row.Size;
         int rowOffset = startRange[1];

         for (int x = 0; x < 4 && rowOffset < end; x++)
         {
            int bestMatch;
            if (!decodeDigit(row, counters, rowOffset, L_PATTERNS, out bestMatch))
               return -1;
            result.Append((char)('0' + bestMatch));
            foreach (int counter in counters)
            {
               rowOffset += counter;
            }
         }

         int[] middleRange = findGuardPattern(row, rowOffset, true, MIDDLE_PATTERN);
         if (middleRange == null)
            return -1;
         rowOffset = middleRange[1];

         for (int x = 0; x < 4 && rowOffset < end; x++)
         {
            int bestMatch;
            if (!decodeDigit(row, counters, rowOffset, L_PATTERNS, out bestMatch))
               return -1;
            result.Append((char)('0' + bestMatch));
            foreach (int counter in counters)
            {
               rowOffset += counter;
            }
         }

         return rowOffset;
      }
      /// <summary>
      /// Creates the decoder.
      /// </summary>
      /// <param name="information">The information.</param>
      /// <returns></returns>
      public static AbstractExpandedDecoder createDecoder(BitArray information)
      {
         if (information[1])
         {
            return new AI01AndOtherAIs(information);
         }
         if (!information[2])
         {
            return new AnyAIDecoder(information);
         }

         int fourBitEncodationMethod = GeneralAppIdDecoder.extractNumericValueFromBitArray(information, 1, 4);

         switch (fourBitEncodationMethod)
         {
            case 4: return new AI013103decoder(information);
            case 5: return new AI01320xDecoder(information);
         }

         int fiveBitEncodationMethod = GeneralAppIdDecoder.extractNumericValueFromBitArray(information, 1, 5);
         switch (fiveBitEncodationMethod)
         {
            case 12: return new AI01392xDecoder(information);
            case 13: return new AI01393xDecoder(information);
         }

         int sevenBitEncodationMethod = GeneralAppIdDecoder.extractNumericValueFromBitArray(information, 1, 7);
         switch (sevenBitEncodationMethod)
         {
            case 56: return new AI013x0x1xDecoder(information, "310", "11");
            case 57: return new AI013x0x1xDecoder(information, "320", "11");
            case 58: return new AI013x0x1xDecoder(information, "310", "13");
            case 59: return new AI013x0x1xDecoder(information, "320", "13");
            case 60: return new AI013x0x1xDecoder(information, "310", "15");
            case 61: return new AI013x0x1xDecoder(information, "320", "15");
            case 62: return new AI013x0x1xDecoder(information, "310", "17");
            case 63: return new AI013x0x1xDecoder(information, "320", "17");
         }

         throw new InvalidOperationException("unknown decoder: " + information);
      }
Exemplo n.º 20
0
        public static ByteMatrix CreateRawQR(byte[] rawData, ErrorCorrectionLevel errorCorrectionLevel)
        {
            int versionNumber = GetSmallestVersion(rawData.Length, errorCorrectionLevel);
            ZXing.QrCode.Internal.Version version = ZXing.QrCode.Internal.Version.getVersionForNumber(versionNumber);

            BitArray dataBits = new BitArray();
            foreach (byte b in rawData)
                dataBits.appendBits(b, 8);

            ZXing.QrCode.Internal.Version.ECBlocks ecBlocks = version.getECBlocksForLevel(errorCorrectionLevel);
            int bytesLength = version.TotalCodewords - ecBlocks.TotalECCodewords;
            terminateBits(bytesLength, dataBits);

            BitArray resultBits = interleaveWithECBytes(dataBits, version.TotalCodewords, bytesLength, ecBlocks.NumBlocks);

            ByteMatrix matrix = new ByteMatrix(version.DimensionForVersion, version.DimensionForVersion);
            int maskPattern = chooseMaskPattern(resultBits, errorCorrectionLevel, version, matrix);

            MatrixUtil.buildMatrix(resultBits, errorCorrectionLevel, version, maskPattern, matrix);
            return matrix;
        }
    /// <summary>
    /// Draw qr code on enable.
    /// </summary>
    void OnEnable()
    {
        _using = GameObject.FindObjectOfType <UsingCon>();
        ZXing.QrCode.QRCodeWriter QRWriter = new ZXing.QrCode.QRCodeWriter();
        BitMatrix encoded = QRWriter.encode(_using.profile.passCode, ZXing.BarcodeFormat.QR_CODE, 512, 512);
        Texture2D tex     = new Texture2D(512, 512, TextureFormat.RGBA32, false);

        Color[] pixels = tex.GetPixels();
        int     k      = 0;

        for (int j = 0; j < 512; j++)
        {
            ZXing.Common.BitArray row = new ZXing.Common.BitArray(512);
            row = encoded.getRow(j, null);
            int[] intRow = row.Array;
            for (int i = intRow.Length - 1; i >= 0; i--)
            {
                int thirtyTwoPixels = intRow[i];
                for (int b = 31; b >= 0; b--)
                {
                    int pixel = ((thirtyTwoPixels >> b) & 1);
                    if (pixel == 0)
                    {
                        pixels[k] = Color.white;
                    }
                    else
                    {
                        pixels[k] = Color.black;
                    }
                    k++;
                }
            }
        }

        print("PassCode for draw QR : " + _using.profile.passCode);

        tex.SetPixels(pixels);
        tex.Apply();
        qr_output.material.mainTexture = tex;
    }
Exemplo n.º 22
0
 public void appendBitArray(BitArray other)
 {
    int otherSize = other.size;
    ensureCapacity(size + otherSize);
    for (int i = 0; i < otherSize; i++)
    {
       appendBit(other[i]);
    }
 }
Exemplo n.º 23
0
      /// <summary>
      /// Encodes the specified content.
      /// </summary>
      /// <param name="content">The content.</param>
      /// <param name="ecLevel">The ec level.</param>
      /// <param name="hints">The hints.</param>
      /// <returns></returns>
      public static QRCode encode(String content,
                                ErrorCorrectionLevel ecLevel,
                                IDictionary<EncodeHintType, object> hints)
      {
         // Determine what character encoding has been specified by the caller, if any
#if !SILVERLIGHT || WINDOWS_PHONE
         String encoding = hints == null || !hints.ContainsKey(EncodeHintType.CHARACTER_SET) ? null : (String)hints[EncodeHintType.CHARACTER_SET];
         if (encoding == null)
         {
            encoding = DEFAULT_BYTE_MODE_ENCODING;
         }
         bool generateECI = !DEFAULT_BYTE_MODE_ENCODING.Equals(encoding);
#else
         // Silverlight supports only UTF-8 and UTF-16 out-of-the-box
         const string encoding = "UTF-8";
         // caller of the method can only control if the ECI segment should be written
         // character set is fixed to UTF-8; but some scanners doesn't like the ECI segment
         bool generateECI = (hints != null && hints.ContainsKey(EncodeHintType.CHARACTER_SET));
#endif

         // Pick an encoding mode appropriate for the content. Note that this will not attempt to use
         // multiple modes / segments even if that were more efficient. Twould be nice.
         Mode mode = chooseMode(content, encoding);

         // This will store the header information, like mode and
         // length, as well as "header" segments like an ECI segment.
         BitArray headerBits = new BitArray();

         // Append ECI segment if applicable
         if (mode == Mode.BYTE && generateECI)
         {
            CharacterSetECI eci = CharacterSetECI.getCharacterSetECIByName(encoding);
            if (eci != null)
            {
               var eciIsExplicitDisabled = (hints != null && hints.ContainsKey(EncodeHintType.DISABLE_ECI) ? (bool)hints[EncodeHintType.DISABLE_ECI] : false);
               if (!eciIsExplicitDisabled)
               {
                  appendECI(eci, headerBits);
               }
            }
         }

         // (With ECI in place,) Write the mode marker
         appendModeInfo(mode, headerBits);

         // Collect data within the main segment, separately, to count its size if needed. Don't add it to
         // main payload yet.
         BitArray dataBits = new BitArray();
         appendBytes(content, mode, dataBits, encoding);

         // Hard part: need to know version to know how many bits length takes. But need to know how many
         // bits it takes to know version. First we take a guess at version by assuming version will be
         // the minimum, 1:

         int provisionalBitsNeeded = headerBits.Size
             + mode.getCharacterCountBits(Version.getVersionForNumber(1))
             + dataBits.Size;
         Version provisionalVersion = chooseVersion(provisionalBitsNeeded, ecLevel);

         // Use that guess to calculate the right version. I am still not sure this works in 100% of cases.
         int bitsNeeded = headerBits.Size
             + mode.getCharacterCountBits(provisionalVersion)
             + dataBits.Size;
         Version version = chooseVersion(bitsNeeded, ecLevel);

         BitArray headerAndDataBits = new BitArray();
         headerAndDataBits.appendBitArray(headerBits);
         // Find "length" of main segment and write it
         int numLetters = mode == Mode.BYTE ? dataBits.SizeInBytes : content.Length;
         appendLengthInfo(numLetters, version, mode, headerAndDataBits);
         // Put data together into the overall payload
         headerAndDataBits.appendBitArray(dataBits);

         Version.ECBlocks ecBlocks = version.getECBlocksForLevel(ecLevel);
         int numDataBytes = version.TotalCodewords - ecBlocks.TotalECCodewords;

         // Terminate the bits properly.
         terminateBits(numDataBytes, headerAndDataBits);

         // Interleave data bits with error correction code.
         BitArray finalBits = interleaveWithECBytes(headerAndDataBits,
                                                    version.TotalCodewords,
                                                    numDataBytes,
                                                    ecBlocks.NumBlocks);

         QRCode qrCode = new QRCode
                            {
                               ECLevel = ecLevel, 
                               Mode = mode,
                               Version = version
                            };

         //  Choose the mask pattern and set to "qrCode".
         int dimension = version.DimensionForVersion;
         ByteMatrix matrix = new ByteMatrix(dimension, dimension);
         int maskPattern = chooseMaskPattern(finalBits, ecLevel, version, matrix);
         qrCode.MaskPattern = maskPattern;

         // Build the matrix and set it to "qrCode".
         MatrixUtil.buildMatrix(finalBits, ecLevel, version, maskPattern, matrix);
         qrCode.Matrix = matrix;

         return qrCode;
      }
Exemplo n.º 24
0
      private static void appendECI(CharacterSetECI eci, BitArray bits)
      {
         bits.appendBits(Mode.ECI.Bits, 4);

         // This is correct for values up to 127, which is all we need now.
         bits.appendBits(eci.Value, 8);
      }
Exemplo n.º 25
0
      internal static void appendKanjiBytes(String content, BitArray bits)
      {
         byte[] bytes;
         try
         {
            bytes = Encoding.GetEncoding("Shift_JIS").GetBytes(content);
         }
         catch (Exception uee)
         {
            throw new WriterException(uee.Message, uee);
         }
         int length = bytes.Length;
         for (int i = 0; i < length; i += 2)
         {
            int byte1 = bytes[i] & 0xFF;
            int byte2 = bytes[i + 1] & 0xFF;
            int code = (byte1 << 8) | byte2;
            int subtracted = -1;
            if (code >= 0x8140 && code <= 0x9ffc)
            {

               subtracted = code - 0x8140;
            }
            else if (code >= 0xe040 && code <= 0xebbf)
            {
               subtracted = code - 0xc140;
            }
            if (subtracted == -1)
            {

               throw new WriterException("Invalid byte sequence");
            }
            int encoded = ((subtracted >> 8) * 0xc0) + (subtracted & 0xff);
            bits.appendBits(encoded, 13);
         }
      }
Exemplo n.º 26
0
      internal static void append8BitBytes(String content, BitArray bits, String encoding)
      {
         byte[] bytes;
         try
         {
            bytes = Encoding.GetEncoding(encoding).GetBytes(content);
         }
#if WindowsCE
         catch (PlatformNotSupportedException)
         {
            try
            {
               // WindowsCE doesn't support all encodings. But it is device depended.
               // So we try here the some different ones
               if (encoding == "ISO-8859-1")
               {
                  bytes = Encoding.GetEncoding(1252).GetBytes(content);
               }
               else
               {
                  bytes = Encoding.GetEncoding("UTF-8").GetBytes(content);
               }
            }
            catch (Exception uee)
            {
               throw new WriterException(uee.Message, uee);
            }
         }
#endif
         catch (Exception uee)
         {
            throw new WriterException(uee.Message, uee);
         }
         foreach (byte b in bytes)
         {
            bits.appendBits(b, 8);
         }
      }
Exemplo n.º 27
0
      internal static void appendAlphanumericBytes(String content, BitArray bits)
      {
         int length = content.Length;

         int i = 0;
         while (i < length)
         {
            int code1 = getAlphanumericCode(content[i]);
            if (code1 == -1)
            {
               throw new WriterException();
            }
            if (i + 1 < length)
            {
               int code2 = getAlphanumericCode(content[i + 1]);
               if (code2 == -1)
               {
                  throw new WriterException();
               }
               // Encode two alphanumeric letters in 11 bits.
               bits.appendBits(code1 * 45 + code2, 11);
               i += 2;
            }
            else
            {
               // Encode one alphanumeric letter in six bits.
               bits.appendBits(code1, 6);
               i++;
            }
         }
      }
Exemplo n.º 28
0
      internal static void appendNumericBytes(String content, BitArray bits)
      {
         int length = content.Length;

         int i = 0;
         while (i < length)
         {
            int num1 = content[i] - '0';
            if (i + 2 < length)
            {
               // Encode three numeric letters in ten bits.
               int num2 = content[i + 1] - '0';
               int num3 = content[i + 2] - '0';
               bits.appendBits(num1 * 100 + num2 * 10 + num3, 10);
               i += 3;
            }
            else if (i + 1 < length)
            {
               // Encode two numeric letters in seven bits.
               int num2 = content[i + 1] - '0';
               bits.appendBits(num1 * 10 + num2, 7);
               i += 2;
            }
            else
            {
               // Encode one numeric letter in four bits.
               bits.appendBits(num1, 4);
               i++;
            }
         }
      }
Exemplo n.º 29
0
 public void xor(BitArray other)
 {
    if (bits.Length != other.bits.Length)
    {
       throw new ArgumentException("Sizes don't match");
    }
    for (int i = 0; i < bits.Length; i++)
    {
       // The last byte could be incomplete (i.e. not have 8 bits in
       // it) but there is no problem since 0 XOR 0 == 0.
       bits[i] ^= other.bits[i];
    }
 }
Exemplo n.º 30
0
    // Start is called before the first frame update
    void Start()
    {
        Texture2D texture = new Texture2D(500, 500);

        texture.filterMode = FilterMode.Bilinear;

        BarcodeWriterGeneric writer = new BarcodeWriterGeneric();

        writer.Format         = BarcodeFormat.QR_CODE;
        writer.Options.Width  = texture.width;
        writer.Options.Height = texture.height;
        writer.Options.Margin = 10;

        PsicologoDAO     psicologoDAO = new PsicologoDAO();
        List <Psicologo> psicologos   = psicologoDAO.Lista();


        if (psicologos.Count > 0)
        {
            Psicologo psicologo      = psicologos[0];
            string    representation = string.Format(
                "{0}\n{1}\n{2}\n{3}",
                psicologo.Nombre,
                psicologo.Correo,
                psicologo.Telefono,
                psicologo.Cedula
                );

            BitMatrix matrix = writer.Encode(representation);
            matrix.rotate180();
            ZXing.Common.BitArray row = new ZXing.Common.BitArray(matrix.RowSize);

            // get image data
            int width  = texture.width;
            int height = texture.height;

            for (int y = 0; y < height; y++)
            {
                row = matrix.getRow(y, row);
                row.reverse(); // they are backwards wtf?
                int[] pixels = row.Array;

                int int_i = 0;
                int bit_i = 0;
                for (int x = 0; x < width; x++)
                {
                    int  bit_mask  = 1 << bit_i++;
                    int  int_value = pixels[int_i];
                    bool bit_value = (int_value & bit_mask) == bit_mask;

                    if (bit_i > 31)
                    {
                        bit_i = 0;
                        int_i++;
                    }

                    UnityEngine.Color color;
                    if (bit_value)
                    {
                        color = UnityEngine.Color.black;
                    }
                    else
                    {
                        color = UnityEngine.Color.white;
                    }

                    texture.SetPixel(x, y, color);
                }
            }

            texture.Apply();
            image.texture = texture;
            //imageFitter.aspectRatio = 1.0f;
            //image.material.mainTexture = texture;
        }
    }
Exemplo n.º 31
0
 internal AI01320xDecoder(BitArray information)
    : base(information)
 {
 }
Exemplo n.º 32
0
 /// <summary>
 /// Append "bytes" in "mode" mode (encoding) into "bits". On success, store the result in "bits".
 /// </summary>
 /// <param name="content">The content.</param>
 /// <param name="mode">The mode.</param>
 /// <param name="bits">The bits.</param>
 /// <param name="encoding">The encoding.</param>
 internal static void appendBytes(String content,
                         Mode mode,
                         BitArray bits,
                         String encoding)
 {
    if (mode.Equals(Mode.NUMERIC))
       appendNumericBytes(content, bits);
    else
       if (mode.Equals(Mode.ALPHANUMERIC))
          appendAlphanumericBytes(content, bits);
       else
          if (mode.Equals(Mode.BYTE))
             append8BitBytes(content, bits, encoding);
          else
             if (mode.Equals(Mode.KANJI))
                appendKanjiBytes(content, bits);
             else
                throw new WriterException("Invalid mode: " + mode);
 }