Java Code Examples for com.google.zxing.common.BitMatrix#get()

The following examples show how to use com.google.zxing.common.BitMatrix#get() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: BarcodeProvider.java    From Pix-Art-Messenger with GNU General Public License v3.0 6 votes vote down vote up
public static Bitmap create2dBarcodeBitmap(String input, int size) {
    try {
        final QRCodeWriter barcodeWriter = new QRCodeWriter();
        final Hashtable<EncodeHintType, Object> hints = new Hashtable<>();
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
        final BitMatrix result = barcodeWriter.encode(input, BarcodeFormat.QR_CODE, size, size, hints);
        final int width = result.getWidth();
        final int height = result.getHeight();
        final int[] pixels = new int[width * height];
        for (int y = 0; y < height; y++) {
            final int offset = y * width;
            for (int x = 0; x < width; x++) {
                pixels[offset + x] = result.get(x, y) ? Color.BLACK : Color.WHITE;
            }
        }
        final Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
        return bitmap;
    } catch (final Exception e) {
        e.printStackTrace();
        return null;
    }
}
 
Example 2
Source File: QRCodeGen.java    From TVRemoteIME with GNU General Public License v2.0 6 votes vote down vote up
public static Bitmap generateBitmap(String content, int width, int height) {
    QRCodeWriter qrCodeWriter = new QRCodeWriter();
    Map<EncodeHintType, String> hints = new HashMap<>();
    hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
    try {
        BitMatrix encode = qrCodeWriter.encode(content, BarcodeFormat.QR_CODE, width, height, hints);
        int[] pixels = new int[width * height];
        for (int i = 0; i < height; i++) {
            for (int j = 0; j < width; j++) {
                if (encode.get(j, i)) {
                    pixels[i * width + j] = 0x00000000;
                } else {
                    pixels[i * width + j] = 0xffffffff;
                }
            }
        }
        return Bitmap.createBitmap(pixels, 0, width, width, height, Bitmap.Config.RGB_565);
    } catch (WriterException e) {
        e.printStackTrace();
    }
    return null;
}
 
Example 3
Source File: QRCodeReader.java    From Telegram with GNU General Public License v2.0 6 votes vote down vote up
private static float moduleSize(int[] leftTopBlack, BitMatrix image) throws NotFoundException {
  int height = image.getHeight();
  int width = image.getWidth();
  int x = leftTopBlack[0];
  int y = leftTopBlack[1];
  boolean inBlack = true;
  int transitions = 0;
  while (x < width && y < height) {
    if (inBlack != image.get(x, y)) {
      if (++transitions == 5) {
        break;
      }
      inBlack = !inBlack;
    }
    x++;
    y++;
  }
  if (x == width || y == height) {
    throw NotFoundException.getNotFoundInstance();
  }
  return (x - leftTopBlack[0]) / 7.0f;
}
 
Example 4
Source File: QRCodeHelper.java    From AndroidWallet with GNU General Public License v3.0 6 votes vote down vote up
public static Bitmap generateBitmap(String content, int width, int height) {
    int margin = 5;  //自定义白边边框宽度
    QRCodeWriter qrCodeWriter = new QRCodeWriter();
    Hashtable hints = new Hashtable<>();
    hints.put(EncodeHintType.MARGIN, 0);
    hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
    try {
        BitMatrix encode = qrCodeWriter.encode(content, BarcodeFormat.QR_CODE, width, height, hints);
      //  encode = updateBit(encode, margin);  //生成新的bitMatrix
        int[] pixels = new int[width * height];
        for (int i = 0; i < height; i++) {
            for (int j = 0; j < width; j++) {
                if (encode.get(j, i)) {
                    pixels[i * width + j] = 0x00000000;
                } else {
                    pixels[i * width + j] = 0xffffffff;
                }
            }
        }
        return Bitmap.createBitmap(pixels, 0, width, width, height, Bitmap.Config.RGB_565);
    } catch (WriterException e) {
        e.printStackTrace();
    }
    return null;
}
 
Example 5
Source File: QREncoder.java    From Lunary-Ethereum-Wallet with GNU General Public License v3.0 6 votes vote down vote up
public Bitmap encodeAsBitmap() throws WriterException {
    if (!encoded) return null;

    Map<EncodeHintType, Object> hints = null;
    String encoding = guessAppropriateEncoding(contents);
    if (encoding != null) {
        hints = new EnumMap<EncodeHintType, Object>(EncodeHintType.class);
        hints.put(EncodeHintType.CHARACTER_SET, encoding);
    }
    MultiFormatWriter writer = new MultiFormatWriter();
    BitMatrix result = writer.encode(contents, format, dimension, dimension, hints);
    int width = result.getWidth();
    int height = result.getHeight();
    int[] pixels = new int[width * height];
    // All are 0, or black, by default
    for (int y = 0; y < height; y++) {
        int offset = y * width;
        for (int x = 0; x < width; x++) {
            pixels[offset + x] = result.get(x, y) ? BLACK : WHITE;
        }
    }

    Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
    bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
    return bitmap;
}
 
Example 6
Source File: QRCodeEncoder.java    From Study_Android_Demo with Apache License 2.0 5 votes vote down vote up
Bitmap encodeAsBitmap() throws WriterException {
  String contentsToEncode = contents;
  if (contentsToEncode == null) {
    return null;
  }
  Map<EncodeHintType,Object> hints = null;
  String encoding = guessAppropriateEncoding(contentsToEncode);
  if (encoding != null) {
    hints = new EnumMap<>(EncodeHintType.class);
    hints.put(EncodeHintType.CHARACTER_SET, encoding);
  }
  BitMatrix result;
  try {
    result = new MultiFormatWriter().encode(contentsToEncode, format, dimension, dimension, hints);
  } catch (IllegalArgumentException iae) {
    // Unsupported format
    return null;
  }
  int width = result.getWidth();
  int height = result.getHeight();
  int[] pixels = new int[width * height];
  for (int y = 0; y < height; y++) {
    int offset = y * width;
    for (int x = 0; x < width; x++) {
      pixels[offset + x] = result.get(x, y) ? BLACK : WHITE;
    }
  }

  Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
  bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
  return bitmap;
}
 
Example 7
Source File: PDF417ScanningDecoder.java    From weex with Apache License 2.0 5 votes vote down vote up
private static int[] getModuleBitCount(BitMatrix image,
                                       int minColumn,
                                       int maxColumn,
                                       boolean leftToRight,
                                       int startColumn,
                                       int imageRow) {
  int imageColumn = startColumn;
  int[] moduleBitCount = new int[8];
  int moduleNumber = 0;
  int increment = leftToRight ? 1 : -1;
  boolean previousPixelValue = leftToRight;
  while (((leftToRight && imageColumn < maxColumn) || (!leftToRight && imageColumn >= minColumn)) &&
      moduleNumber < moduleBitCount.length) {
    if (image.get(imageColumn, imageRow) == previousPixelValue) {
      moduleBitCount[moduleNumber]++;
      imageColumn += increment;
    } else {
      moduleNumber++;
      previousPixelValue = !previousPixelValue;
    }
  }
  if (moduleNumber == moduleBitCount.length ||
      (((leftToRight && imageColumn == maxColumn) || (!leftToRight && imageColumn == minColumn)) && moduleNumber == moduleBitCount.length - 1)) {
    return moduleBitCount;
  }
  return null;
}
 
Example 8
Source File: Decoder.java    From MiBandDecompiled with Apache License 2.0 5 votes vote down vote up
private static BitMatrix b(BitMatrix bitmatrix)
{
    int i1 = 1 + 2 * ((-1 + bitmatrix.getWidth()) / 2 / 16);
    BitMatrix bitmatrix1 = new BitMatrix(bitmatrix.getWidth() - i1, bitmatrix.getHeight() - i1);
    int j1 = 0;
    int k1 = 0;
    while (j1 < bitmatrix.getWidth()) 
    {
        if ((bitmatrix.getWidth() / 2 - j1) % 16 != 0)
        {
            int l1 = 0;
            int i2 = 0;
            while (l1 < bitmatrix.getHeight()) 
            {
                if ((bitmatrix.getWidth() / 2 - l1) % 16 != 0)
                {
                    if (bitmatrix.get(j1, l1))
                    {
                        bitmatrix1.set(k1, i2);
                    }
                    i2++;
                }
                l1++;
            }
            k1++;
        }
        j1++;
    }
    return bitmatrix1;
}
 
Example 9
Source File: FinderPatternFinder.java    From Tesseract-OCR-Scanner with Apache License 2.0 4 votes vote down vote up
/**
 * <p>After a horizontal scan finds a potential finder pattern, this method
 * "cross-checks" by scanning down vertically through the center of the possible
 * finder pattern to see if the same proportion is detected.</p>
 *
 * @param startI row where a finder pattern was detected
 * @param centerJ center of the section that appears to cross a finder pattern
 * @param maxCount maximum reasonable number of modules that should be
 * observed in any reading state, based on the results of the horizontal scan
 * @return vertical center of finder pattern, or {@link Float#NaN} if not found
 */
private float crossCheckVertical(int startI, int centerJ, int maxCount,
    int originalStateCountTotal) {
  BitMatrix image = this.image;

  int maxI = image.getHeight();
  int[] stateCount = getCrossCheckStateCount();

  // Start counting up from center
  int i = startI;
  while (i >= 0 && image.get(centerJ, i)) {
    stateCount[2]++;
    i--;
  }
  if (i < 0) {
    return Float.NaN;
  }
  while (i >= 0 && !image.get(centerJ, i) && stateCount[1] <= maxCount) {
    stateCount[1]++;
    i--;
  }
  // If already too many modules in this state or ran off the edge:
  if (i < 0 || stateCount[1] > maxCount) {
    return Float.NaN;
  }
  while (i >= 0 && image.get(centerJ, i) && stateCount[0] <= maxCount) {
    stateCount[0]++;
    i--;
  }
  if (stateCount[0] > maxCount) {
    return Float.NaN;
  }

  // Now also count down from center
  i = startI + 1;
  while (i < maxI && image.get(centerJ, i)) {
    stateCount[2]++;
    i++;
  }
  if (i == maxI) {
    return Float.NaN;
  }
  while (i < maxI && !image.get(centerJ, i) && stateCount[3] < maxCount) {
    stateCount[3]++;
    i++;
  }
  if (i == maxI || stateCount[3] >= maxCount) {
    return Float.NaN;
  }
  while (i < maxI && image.get(centerJ, i) && stateCount[4] < maxCount) {
    stateCount[4]++;
    i++;
  }
  if (stateCount[4] >= maxCount) {
    return Float.NaN;
  }

  // If we found a finder-pattern-like section, but its size is more than 40% different than
  // the original, assume it's a false positive
  int stateCountTotal = stateCount[0] + stateCount[1] + stateCount[2] + stateCount[3] +
      stateCount[4];
  if (5 * Math.abs(stateCountTotal - originalStateCountTotal) >= 2 * originalStateCountTotal) {
    return Float.NaN;
  }

  return foundPatternCross(stateCount) ? centerFromEnd(stateCount, i) : Float.NaN;
}
 
Example 10
Source File: BitMatrixParser.java    From Tesseract-OCR-Scanner with Apache License 2.0 4 votes vote down vote up
/**
 * <p>Reads the bits in the {@link BitMatrix} representing the finder pattern in the
 * correct order in order to reconstruct the codewords bytes contained within the
 * QR Code.</p>
 *
 * @return bytes encoded within the QR Code
 * @throws FormatException if the exact number of bytes expected is not read
 */
byte[] readCodewords() throws FormatException {

  FormatInformation formatInfo = readFormatInformation();
  Version version = readVersion();

  // Get the data mask for the format used in this QR Code. This will exclude
  // some bits from reading as we wind through the bit matrix.
  DataMask dataMask = DataMask.values()[formatInfo.getDataMask()];
  int dimension = bitMatrix.getHeight();
  dataMask.unmaskBitMatrix(bitMatrix, dimension);

  BitMatrix functionPattern = version.buildFunctionPattern();

  boolean readingUp = true;
  byte[] result = new byte[version.getTotalCodewords()];
  int resultOffset = 0;
  int currentByte = 0;
  int bitsRead = 0;
  // Read columns in pairs, from right to left
  for (int j = dimension - 1; j > 0; j -= 2) {
    if (j == 6) {
      // Skip whole column with vertical alignment pattern;
      // saves time and makes the other code proceed more cleanly
      j--;
    }
    // Read alternatingly from bottom to top then top to bottom
    for (int count = 0; count < dimension; count++) {
      int i = readingUp ? dimension - 1 - count : count;
      for (int col = 0; col < 2; col++) {
        // Ignore bits covered by the function pattern
        if (!functionPattern.get(j - col, i)) {
          // Read a bit
          bitsRead++;
          currentByte <<= 1;
          if (bitMatrix.get(j - col, i)) {
            currentByte |= 1;
          }
          // If we've made a whole byte, save it off
          if (bitsRead == 8) {
            result[resultOffset++] = (byte) currentByte;
            bitsRead = 0;
            currentByte = 0;
          }
        }
      }
    }
    readingUp ^= true; // readingUp = !readingUp; // switch directions
  }
  if (resultOffset != version.getTotalCodewords()) {
    throw FormatException.getFormatInstance();
  }
  return result;
}
 
Example 11
Source File: QRCodeUtil.java    From Android-Application-ZJB with Apache License 2.0 4 votes vote down vote up
private static Bitmap createQRCode(String str, int widthAndHeight) throws WriterException {
    Hashtable<EncodeHintType, String> hints = new Hashtable<>();
    hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
    BitMatrix matrix = new MultiFormatWriter().encode(str,
            BarcodeFormat.QR_CODE, widthAndHeight, widthAndHeight, hints);

    int width = matrix.getWidth();
    int height = matrix.getHeight();
    int[] pixels = new int[width * height];

    boolean isFirstBlackPoint = false;
    int startX = 0;
    int startY = 0;

    for (int y = 0; y < height; y++) {
        for (int x = 0; x < width; x++) {
            if (matrix.get(x, y)) {
                if (isFirstBlackPoint == false) {
                    isFirstBlackPoint = true;
                    startX = x;
                    startY = y;
                    Log.d("createQRCode", "x y = " + x + " " + y);
                }
                pixels[y * width + x] = BLACK;
            }
        }
    }

    Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
    bitmap.setPixels(pixels, 0, width, 0, 0, width, height);

    // 剪切中间的二维码区域,减少padding区域
    if (startX <= PADDING_SIZE_MIN) return bitmap;

    int x1 = startX - PADDING_SIZE_MIN;
    int y1 = startY - PADDING_SIZE_MIN;
    if (x1 < 0 || y1 < 0) return bitmap;

    int w1 = width - x1 * 2;
    int h1 = height - y1 * 2;

    Bitmap bitmapQR = Bitmap.createBitmap(bitmap, x1, y1, w1, h1);

    return bitmapQR;
}
 
Example 12
Source File: BitMatrixParser.java    From ScreenCapture with MIT License 4 votes vote down vote up
/**
 * <p>Reads the bits in the {@link BitMatrix} representing the finder pattern in the
 * correct order in order to reconstruct the codewords bytes contained within the
 * QR Code.</p>
 *
 * @return bytes encoded within the QR Code
 * @throws FormatException if the exact number of bytes expected is not read
 */
byte[] readCodewords() throws FormatException {

  FormatInformation formatInfo = readFormatInformation();
  Version version = readVersion();

  // Get the data mask for the format used in this QR Code. This will exclude
  // some bits from reading as we wind through the bit matrix.
  DataMask dataMask = DataMask.values()[formatInfo.getDataMask()];
  int dimension = bitMatrix.getHeight();
  dataMask.unmaskBitMatrix(bitMatrix, dimension);

  BitMatrix functionPattern = version.buildFunctionPattern();

  boolean readingUp = true;
  byte[] result = new byte[version.getTotalCodewords()];
  int resultOffset = 0;
  int currentByte = 0;
  int bitsRead = 0;
  // Read columns in pairs, from right to left
  for (int j = dimension - 1; j > 0; j -= 2) {
    if (j == 6) {
      // Skip whole column with vertical alignment pattern;
      // saves time and makes the other code proceed more cleanly
      j--;
    }
    // Read alternatingly from bottom to top then top to bottom
    for (int count = 0; count < dimension; count++) {
      int i = readingUp ? dimension - 1 - count : count;
      for (int col = 0; col < 2; col++) {
        // Ignore bits covered by the function pattern
        if (!functionPattern.get(j - col, i)) {
          // Read a bit
          bitsRead++;
          currentByte <<= 1;
          if (bitMatrix.get(j - col, i)) {
            currentByte |= 1;
          }
          // If we've made a whole byte, save it off
          if (bitsRead == 8) {
            result[resultOffset++] = (byte) currentByte;
            bitsRead = 0;
            currentByte = 0;
          }
        }
      }
    }
    readingUp ^= true; // readingUp = !readingUp; // switch directions
  }
  if (resultOffset != version.getTotalCodewords()) {
    throw FormatException.getFormatInstance();
  }
  return result;
}
 
Example 13
Source File: MultiFinderPatternFinder.java    From Tesseract-OCR-Scanner with Apache License 2.0 4 votes vote down vote up
public FinderPatternInfo[] findMulti(Map<DecodeHintType,?> hints) throws NotFoundException {
  boolean tryHarder = hints != null && hints.containsKey(DecodeHintType.TRY_HARDER);
  boolean pureBarcode = hints != null && hints.containsKey(DecodeHintType.PURE_BARCODE);
  BitMatrix image = getImage();
  int maxI = image.getHeight();
  int maxJ = image.getWidth();
  // We are looking for black/white/black/white/black modules in
  // 1:1:3:1:1 ratio; this tracks the number of such modules seen so far

  // Let's assume that the maximum version QR Code we support takes up 1/4 the height of the
  // image, and then account for the center being 3 modules in size. This gives the smallest
  // number of pixels the center could be, so skip this often. When trying harder, look for all
  // QR versions regardless of how dense they are.
  int iSkip = (int) (maxI / (MAX_MODULES * 4.0f) * 3);
  if (iSkip < MIN_SKIP || tryHarder) {
    iSkip = MIN_SKIP;
  }

  int[] stateCount = new int[5];
  for (int i = iSkip - 1; i < maxI; i += iSkip) {
    // Get a row of black/white values
    stateCount[0] = 0;
    stateCount[1] = 0;
    stateCount[2] = 0;
    stateCount[3] = 0;
    stateCount[4] = 0;
    int currentState = 0;
    for (int j = 0; j < maxJ; j++) {
      if (image.get(j, i)) {
        // Black pixel
        if ((currentState & 1) == 1) { // Counting white pixels
          currentState++;
        }
        stateCount[currentState]++;
      } else { // White pixel
        if ((currentState & 1) == 0) { // Counting black pixels
          if (currentState == 4) { // A winner?
            if (foundPatternCross(stateCount) && handlePossibleCenter(stateCount, i, j, pureBarcode)) { // Yes
              // Clear state to start looking again
              currentState = 0;
              stateCount[0] = 0;
              stateCount[1] = 0;
              stateCount[2] = 0;
              stateCount[3] = 0;
              stateCount[4] = 0;
            } else { // No, shift counts back by two
              stateCount[0] = stateCount[2];
              stateCount[1] = stateCount[3];
              stateCount[2] = stateCount[4];
              stateCount[3] = 1;
              stateCount[4] = 0;
              currentState = 3;
            }
          } else {
            stateCount[++currentState]++;
          }
        } else { // Counting white pixels
          stateCount[currentState]++;
        }
      }
    } // for j=...

    if (foundPatternCross(stateCount)) {
      handlePossibleCenter(stateCount, i, maxJ, pureBarcode);
    } // end if foundPatternCross
  } // for i=iSkip-1 ...
  FinderPattern[][] patternInfo = selectMutipleBestPatterns();
  List<FinderPatternInfo> result = new ArrayList<>();
  for (FinderPattern[] pattern : patternInfo) {
    ResultPoint.orderBestPatterns(pattern);
    result.add(new FinderPatternInfo(pattern));
  }

  if (result.isEmpty()) {
    return EMPTY_RESULT_ARRAY;
  } else {
    return result.toArray(new FinderPatternInfo[result.size()]);
  }
}
 
Example 14
Source File: BitMatrixParser.java    From RipplePower with Apache License 2.0 4 votes vote down vote up
/**
 * <p>
 * Reads the bits in the {@link BitMatrix} representing the finder pattern
 * in the correct order in order to reconstruct the codewords bytes
 * contained within the QR Code.
 * </p>
 * 
 * @return bytes encoded within the QR Code
 * @throws FormatException
 *             if the exact number of bytes expected is not read
 */
byte[] readCodewords() throws FormatException {

	FormatInformation formatInfo = readFormatInformation();
	Version version = readVersion();

	// Get the data mask for the format used in this QR Code. This will
	// exclude
	// some bits from reading as we wind through the bit matrix.
	DataMask dataMask = DataMask.forReference(formatInfo.getDataMask());
	int dimension = bitMatrix.getHeight();
	dataMask.unmaskBitMatrix(bitMatrix, dimension);

	BitMatrix functionPattern = version.buildFunctionPattern();

	boolean readingUp = true;
	byte[] result = new byte[version.getTotalCodewords()];
	int resultOffset = 0;
	int currentByte = 0;
	int bitsRead = 0;
	// Read columns in pairs, from right to left
	for (int j = dimension - 1; j > 0; j -= 2) {
		if (j == 6) {
			// Skip whole column with vertical alignment pattern;
			// saves time and makes the other code proceed more cleanly
			j--;
		}
		// Read alternatingly from bottom to top then top to bottom
		for (int count = 0; count < dimension; count++) {
			int i = readingUp ? dimension - 1 - count : count;
			for (int col = 0; col < 2; col++) {
				// Ignore bits covered by the function pattern
				if (!functionPattern.get(j - col, i)) {
					// Read a bit
					bitsRead++;
					currentByte <<= 1;
					if (bitMatrix.get(j - col, i)) {
						currentByte |= 1;
					}
					// If we've made a whole byte, save it off
					if (bitsRead == 8) {
						result[resultOffset++] = (byte) currentByte;
						bitsRead = 0;
						currentByte = 0;
					}
				}
			}
		}
		readingUp ^= true; // readingUp = !readingUp; // switch directions
	}
	if (resultOffset != version.getTotalCodewords()) {
		throw FormatException.getFormatInstance();
	}
	return result;
}
 
Example 15
Source File: FinderPatternFinder.java    From ZXing-Orient with Apache License 2.0 4 votes vote down vote up
/**
 * <p>Like {@link #crossCheckVertical(int, int, int, int)}, and in fact is basically identical,
 * except it reads horizontally instead of vertically. This is used to cross-cross
 * check a vertical cross check and locate the real center of the alignment pattern.</p>
 */
private float crossCheckHorizontal(int startJ, int centerI, int maxCount,
    int originalStateCountTotal) {
  BitMatrix image = this.image;

  int maxJ = image.getWidth();
  int[] stateCount = getCrossCheckStateCount();

  int j = startJ;
  while (j >= 0 && image.get(j, centerI)) {
    stateCount[2]++;
    j--;
  }
  if (j < 0) {
    return Float.NaN;
  }
  while (j >= 0 && !image.get(j, centerI) && stateCount[1] <= maxCount) {
    stateCount[1]++;
    j--;
  }
  if (j < 0 || stateCount[1] > maxCount) {
    return Float.NaN;
  }
  while (j >= 0 && image.get(j, centerI) && stateCount[0] <= maxCount) {
    stateCount[0]++;
    j--;
  }
  if (stateCount[0] > maxCount) {
    return Float.NaN;
  }

  j = startJ + 1;
  while (j < maxJ && image.get(j, centerI)) {
    stateCount[2]++;
    j++;
  }
  if (j == maxJ) {
    return Float.NaN;
  }
  while (j < maxJ && !image.get(j, centerI) && stateCount[3] < maxCount) {
    stateCount[3]++;
    j++;
  }
  if (j == maxJ || stateCount[3] >= maxCount) {
    return Float.NaN;
  }
  while (j < maxJ && image.get(j, centerI) && stateCount[4] < maxCount) {
    stateCount[4]++;
    j++;
  }
  if (stateCount[4] >= maxCount) {
    return Float.NaN;
  }

  // If we found a finder-pattern-like section, but its size is significantly different than
  // the original, assume it's a false positive
  int stateCountTotal = stateCount[0] + stateCount[1] + stateCount[2] + stateCount[3] +
      stateCount[4];
  if (5 * Math.abs(stateCountTotal - originalStateCountTotal) >= originalStateCountTotal) {
    return Float.NaN;
  }

  return foundPatternCross(stateCount) ? centerFromEnd(stateCount, j) : Float.NaN;
}
 
Example 16
Source File: ZxingUtil.java    From smart-farmer-android with Apache License 2.0 4 votes vote down vote up
/**
 * 生成二维码图片
 */
public static Bitmap createImage(String text, int w, int h, Bitmap logo) {
    if (TextUtils.isEmpty(text)) {
        return null;
    }
    try {
        Bitmap scaleLogo = getScaleLogo(logo, w, h);

        int offsetX = w / 2;
        int offsetY = h / 2;

        int scaleWidth = 0;
        int scaleHeight = 0;
        if (scaleLogo != null) {
            scaleWidth = scaleLogo.getWidth();
            scaleHeight = scaleLogo.getHeight();
            offsetX = (w - scaleWidth) / 2;
            offsetY = (h - scaleHeight) / 2;
        }
        Hashtable<EncodeHintType, Object> hints = new Hashtable<EncodeHintType, Object>();
        hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
        //容错级别
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
        //设置空白边距的宽度
        hints.put(EncodeHintType.MARGIN, 0);
        BitMatrix bitMatrix = new QRCodeWriter().encode(text, BarcodeFormat.QR_CODE, w, h, hints);
        int[] pixels = new int[w * h];
        for (int y = 0; y < h; y++) {
            for (int x = 0; x < w; x++) {
                if (x >= offsetX && x < offsetX + scaleWidth && y >= offsetY && y < offsetY + scaleHeight) {
                    int pixel = scaleLogo.getPixel(x - offsetX, y - offsetY);
                    if (pixel == 0) {
                        if (bitMatrix.get(x, y)) {
                            pixel = 0xff000000;
                        } else {
                            pixel = 0xffffffff;
                        }
                    }
                    pixels[y * w + x] = pixel;
                } else {
                    if (bitMatrix.get(x, y)) {
                        pixels[y * w + x] = 0xff000000;
                    } else {
                        pixels[y * w + x] = 0xffffffff;
                    }
                }
            }
        }
        Bitmap bitmap = Bitmap.createBitmap(w, h,
                Bitmap.Config.ARGB_8888);
        bitmap.setPixels(pixels, 0, w, 0, 0, w, h);
        return bitmap;
    } catch (WriterException e) {
        e.printStackTrace();
    }
    return null;
}
 
Example 17
Source File: Detector.java    From weex with Apache License 2.0 4 votes vote down vote up
/**
 * @param matrix row of black/white values to search
 * @param column x position to start search
 * @param row y position to start search
 * @param width the number of pixels to search on this row
 * @param pattern pattern of counts of number of black and white pixels that are
 *                 being searched for as a pattern
 * @param counters array of counters, as long as pattern, to re-use 
 * @return start/end horizontal offset of guard pattern, as an array of two ints.
 */
private static int[] findGuardPattern(BitMatrix matrix,
                                      int column,
                                      int row,
                                      int width,
                                      boolean whiteFirst,
                                      int[] pattern,
                                      int[] counters) {
  Arrays.fill(counters, 0, counters.length, 0);
  int patternLength = pattern.length;
  boolean isWhite = whiteFirst;
  int patternStart = column;
  int pixelDrift = 0;

  // if there are black pixels left of the current pixel shift to the left, but only for MAX_PIXEL_DRIFT pixels 
  while (matrix.get(patternStart, row) && patternStart > 0 && pixelDrift++ < MAX_PIXEL_DRIFT) {
    patternStart--;
  }
  int x = patternStart;
  int counterPosition = 0;
  for (; x < width; x++) {
    boolean pixel = matrix.get(x, row);
    if (pixel ^ isWhite) {
      counters[counterPosition]++;
    } else {
      if (counterPosition == patternLength - 1) {
        if (patternMatchVariance(counters, pattern, MAX_INDIVIDUAL_VARIANCE) < MAX_AVG_VARIANCE) {
          return new int[] {patternStart, x};
        }
        patternStart += counters[0] + counters[1];
        System.arraycopy(counters, 2, counters, 0, patternLength - 2);
        counters[patternLength - 2] = 0;
        counters[patternLength - 1] = 0;
        counterPosition--;
      } else {
        counterPosition++;
      }
      counters[counterPosition] = 1;
      isWhite = !isWhite;
    }
  }
  if (counterPosition == patternLength - 1) {
    if (patternMatchVariance(counters, pattern, MAX_INDIVIDUAL_VARIANCE) < MAX_AVG_VARIANCE) {
      return new int[] {patternStart, x - 1};
    }
  }
  return null;
}
 
Example 18
Source File: FinderPatternFinder.java    From Telegram with GNU General Public License v2.0 4 votes vote down vote up
/**
 * <p>Like {@link #crossCheckVertical(int, int, int, int)}, and in fact is basically identical,
 * except it reads horizontally instead of vertically. This is used to cross-cross
 * check a vertical cross check and locate the real center of the alignment pattern.</p>
 */
private float crossCheckHorizontal(int startJ, int centerI, int maxCount,
    int originalStateCountTotal) {
  BitMatrix image = this.image;

  int maxJ = image.getWidth();
  int[] stateCount = getCrossCheckStateCount();

  int j = startJ;
  while (j >= 0 && image.get(j, centerI)) {
    stateCount[2]++;
    j--;
  }
  if (j < 0) {
    return Float.NaN;
  }
  while (j >= 0 && !image.get(j, centerI) && stateCount[1] <= maxCount) {
    stateCount[1]++;
    j--;
  }
  if (j < 0 || stateCount[1] > maxCount) {
    return Float.NaN;
  }
  while (j >= 0 && image.get(j, centerI) && stateCount[0] <= maxCount) {
    stateCount[0]++;
    j--;
  }
  if (stateCount[0] > maxCount) {
    return Float.NaN;
  }

  j = startJ + 1;
  while (j < maxJ && image.get(j, centerI)) {
    stateCount[2]++;
    j++;
  }
  if (j == maxJ) {
    return Float.NaN;
  }
  while (j < maxJ && !image.get(j, centerI) && stateCount[3] < maxCount) {
    stateCount[3]++;
    j++;
  }
  if (j == maxJ || stateCount[3] >= maxCount) {
    return Float.NaN;
  }
  while (j < maxJ && image.get(j, centerI) && stateCount[4] < maxCount) {
    stateCount[4]++;
    j++;
  }
  if (stateCount[4] >= maxCount) {
    return Float.NaN;
  }

  // If we found a finder-pattern-like section, but its size is significantly different than
  // the original, assume it's a false positive
  int stateCountTotal = stateCount[0] + stateCount[1] + stateCount[2] + stateCount[3] +
      stateCount[4];
  if (5 * Math.abs(stateCountTotal - originalStateCountTotal) >= originalStateCountTotal) {
    return Float.NaN;
  }

  return foundPatternCross(stateCount) ? centerFromEnd(stateCount, j) : Float.NaN;
}
 
Example 19
Source File: FinderPatternFinder.java    From MiBandDecompiled with Apache License 2.0 4 votes vote down vote up
private float b(int i, int j, int k, int l)
{
    BitMatrix bitmatrix = c;
    int i1 = bitmatrix.getWidth();
    int ai[] = a();
    int j1;
    for (j1 = i; j1 >= 0 && bitmatrix.get(j1, j); j1--)
    {
        ai[2] = 1 + ai[2];
    }

    if (j1 >= 0)
    {
        for (; j1 >= 0 && !bitmatrix.get(j1, j) && ai[1] <= k; j1--)
        {
            ai[1] = 1 + ai[1];
        }

        if (j1 >= 0 && ai[1] <= k)
        {
            for (; j1 >= 0 && bitmatrix.get(j1, j) && ai[0] <= k; j1--)
            {
                ai[0] = 1 + ai[0];
            }

            if (ai[0] <= k)
            {
                int k1;
                for (k1 = i + 1; k1 < i1 && bitmatrix.get(k1, j); k1++)
                {
                    ai[2] = 1 + ai[2];
                }

                if (k1 != i1)
                {
                    for (; k1 < i1 && !bitmatrix.get(k1, j) && ai[3] < k; k1++)
                    {
                        ai[3] = 1 + ai[3];
                    }

                    if (k1 != i1 && ai[3] < k)
                    {
                        for (; k1 < i1 && bitmatrix.get(k1, j) && ai[4] < k; k1++)
                        {
                            ai[4] = 1 + ai[4];
                        }

                        if (ai[4] < k && 5 * Math.abs((ai[0] + ai[1] + ai[2] + ai[3] + ai[4]) - l) < l && foundPatternCross(ai))
                        {
                            return a(ai, k1);
                        }
                    }
                }
            }
        }
    }
    return (0.0F / 0.0F);
}
 
Example 20
Source File: a.java    From MiBandDecompiled with Apache License 2.0 4 votes vote down vote up
byte[] c()
{
    n n1 = a();
    Version version = b();
    c c1 = com.google.zxing.qrcode.decoder.c.a(n1.b());
    int i = a.getHeight();
    c1.a(a, i);
    BitMatrix bitmatrix = version.a();
    byte abyte0[] = new byte[version.getTotalCodewords()];
    int j = i - 1;
    int k = 0;
    int l = 0;
    int i1 = 0;
    boolean flag1;
    for (boolean flag = true; j > 0; flag = flag1)
    {
        if (j == 6)
        {
            j--;
        }
        int k1;
        for (int j1 = 0; j1 < i; j1++)
        {
            int l1;
            if (flag)
            {
                k1 = i - 1 - j1;
            } else
            {
                k1 = j1;
            }
            for (l1 = 0; l1 < 2; l1++)
            {
                if (bitmatrix.get(j - l1, k1))
                {
                    continue;
                }
                k++;
                l <<= 1;
                if (a.get(j - l1, k1))
                {
                    l |= 1;
                }
                if (k == 8)
                {
                    int i2 = i1 + 1;
                    abyte0[i1] = (byte)l;
                    l = 0;
                    i1 = i2;
                    k = 0;
                }
            }

        }

        flag1 = flag ^ true;
        j -= 2;
    }

    if (i1 != version.getTotalCodewords())
    {
        throw FormatException.getFormatInstance();
    } else
    {
        return abyte0;
    }
}