com.google.zxing.common.BitMatrix Java Examples

The following examples show how to use com.google.zxing.common.BitMatrix. 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: Detector.java    From analyzer-of-android-for-Apache-Weex with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a BitMatrix by sampling the provided image.
 * topLeft, topRight, bottomRight, and bottomLeft are the centers of the squares on the
 * diagonal just outside the bull's eye.
 */
private BitMatrix sampleGrid(BitMatrix image,
                             ResultPoint topLeft,
                             ResultPoint topRight,
                             ResultPoint bottomRight,
                             ResultPoint bottomLeft) throws NotFoundException {
    
  GridSampler sampler = GridSampler.getInstance();
  int dimension = getDimension();

  float low = dimension / 2.0f - nbCenterLayers;
  float high = dimension / 2.0f + nbCenterLayers;

  return sampler.sampleGrid(image,
                            dimension,
                            dimension,
                            low, low,   // topleft
                            high, low,  // topright
                            high, high, // bottomright
                            low, high,  // bottomleft
                            topLeft.getX(), topLeft.getY(),
                            topRight.getX(), topRight.getY(),
                            bottomRight.getX(), bottomRight.getY(),
                            bottomLeft.getX(), bottomLeft.getY());
}
 
Example #2
Source File: Detector.java    From barcodescanner-lib-aar with MIT License 6 votes vote down vote up
/**
 * Locate the vertices and the codewords area of a black blob using the Start
 * and Stop patterns as locators.
 *
 * @param matrix the scanned barcode image.
 * @return an array containing the vertices:
 *           vertices[0] x, y top left barcode
 *           vertices[1] x, y bottom left barcode
 *           vertices[2] x, y top right barcode
 *           vertices[3] x, y bottom right barcode
 *           vertices[4] x, y top left codeword area
 *           vertices[5] x, y bottom left codeword area
 *           vertices[6] x, y top right codeword area
 *           vertices[7] x, y bottom right codeword area
 */
private static ResultPoint[] findVertices(BitMatrix matrix, int startRow, int startColumn) {
  int height = matrix.getHeight();
  int width = matrix.getWidth();

  ResultPoint[] result = new ResultPoint[8];
  copyToResult(result, findRowsWithPattern(matrix, height, width, startRow, startColumn, START_PATTERN),
      INDEXES_START_PATTERN);

  if (result[4] != null) {
    startColumn = (int) result[4].getX();
    startRow = (int) result[4].getY();
  }
  copyToResult(result, findRowsWithPattern(matrix, height, width, startRow, startColumn, STOP_PATTERN),
      INDEXES_STOP_PATTERN);
  return result;
}
 
Example #3
Source File: ZXingQRCodeUtils.java    From DevUtils with Apache License 2.0 6 votes vote down vote up
/**
 * 同步创建指定前景色、指定背景色二维码图片
 * <pre>
 *     该方法是耗时操作, 请在子线程中调用
 * </pre>
 * @param content         生成内容
 * @param size            图片宽高大小 ( 正方形 px )
 * @param foregroundColor 二维码图片的前景色
 * @param backgroundColor 二维码图片的背景色
 * @return 二维码图片
 */
public static Bitmap syncEncodeQRCode(final String content, final int size, final int foregroundColor, final int backgroundColor) {
    try {
        BitMatrix matrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, size, size, ENCODE_HINTS);
        int[] pixels = new int[size * size];
        for (int y = 0; y < size; y++) {
            for (int x = 0; x < size; x++) {
                if (matrix.get(x, y)) {
                    pixels[y * size + x] = foregroundColor;
                } else {
                    pixels[y * size + x] = backgroundColor;
                }
            }
        }
        Bitmap bitmap = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
        bitmap.setPixels(pixels, 0, size, 0, 0, size, size);
        return bitmap;
    } catch (Exception e) {
        LogPrintUtils.eTag(TAG, e, "syncEncodeQRCode");
        return null;
    }
}
 
Example #4
Source File: Detector.java    From ZXing-Orient with Apache License 2.0 6 votes vote down vote up
/**
 * Locate the vertices and the codewords area of a black blob using the Start
 * and Stop patterns as locators.
 *
 * @param matrix the scanned barcode image.
 * @return an array containing the vertices:
 *           vertices[0] x, y top left barcode
 *           vertices[1] x, y bottom left barcode
 *           vertices[2] x, y top right barcode
 *           vertices[3] x, y bottom right barcode
 *           vertices[4] x, y top left codeword area
 *           vertices[5] x, y bottom left codeword area
 *           vertices[6] x, y top right codeword area
 *           vertices[7] x, y bottom right codeword area
 */
private static ResultPoint[] findVertices(BitMatrix matrix, int startRow, int startColumn) {
  int height = matrix.getHeight();
  int width = matrix.getWidth();

  ResultPoint[] result = new ResultPoint[8];
  copyToResult(result, findRowsWithPattern(matrix, height, width, startRow, startColumn, START_PATTERN),
      INDEXES_START_PATTERN);

  if (result[4] != null) {
    startColumn = (int) result[4].getX();
    startRow = (int) result[4].getY();
  }
  copyToResult(result, findRowsWithPattern(matrix, height, width, startRow, startColumn, STOP_PATTERN),
      INDEXES_STOP_PATTERN);
  return result;
}
 
Example #5
Source File: WhiteRectangleDetector.java    From MiBandDecompiled with Apache License 2.0 6 votes vote down vote up
public WhiteRectangleDetector(BitMatrix bitmatrix)
{
    c = bitmatrix;
    d = bitmatrix.getHeight();
    e = bitmatrix.getWidth();
    f = -30 + e >> 1;
    g = 30 + e >> 1;
    i = -30 + d >> 1;
    h = 30 + d >> 1;
    if (i < 0 || f < 0 || h >= d || g >= e)
    {
        throw NotFoundException.getNotFoundInstance();
    } else
    {
        return;
    }
}
 
Example #6
Source File: OneDimensionalCodeWriter.java    From QrCodeScanner with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Encode the contents following specified format.
 * {@code width} and {@code height} are required size. This method may return bigger size
 * {@code BitMatrix} when specified size is too small. The user can set both {@code width} and
 * {@code height} to zero to get minimum size barcode. If negative value is set to {@code width}
 * or {@code height}, {@code IllegalArgumentException} is thrown.
 */
@Override
public BitMatrix encode(String contents,
                        BarcodeFormat format,
                        int width,
                        int height,
                        Map<EncodeHintType,?> hints) throws WriterException {
  if (contents.isEmpty()) {
    throw new IllegalArgumentException("Found empty contents");
  }

  if (width < 0 || height < 0) {
    throw new IllegalArgumentException("Negative size is not allowed. Input: "
                                           + width + 'x' + height);
  }

  int sidesMargin = getDefaultMargin();
  if (hints != null && hints.containsKey(EncodeHintType.MARGIN)) {
    sidesMargin = Integer.parseInt(hints.get(EncodeHintType.MARGIN).toString());
  }

  boolean[] code = encode(contents);
  return renderResult(code, width, height, sidesMargin);
}
 
Example #7
Source File: QRCodeUtil.java    From bicycleSharingServer with MIT License 6 votes vote down vote up
private static BufferedImage createImage(String content, String imgPath,
        boolean needCompress) throws Exception {
    Hashtable hints = new Hashtable();
    hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
    hints.put(EncodeHintType.CHARACTER_SET, CHARSET);
    hints.put(EncodeHintType.MARGIN, 1);
    BitMatrix bitMatrix = new MultiFormatWriter().encode(content,
            BarcodeFormat.QR_CODE, QRCODE_SIZE, QRCODE_SIZE, hints);
    int width = bitMatrix.getWidth();
    int height = bitMatrix.getHeight();
    BufferedImage image = new BufferedImage(width, height,
            BufferedImage.TYPE_INT_RGB);
    for (int x = 0; x < width; x++) {
        for (int y = 0; y < height; y++) {
            image.setRGB(x, y, bitMatrix.get(x, y) ? 0xFF000000
                    : 0xFFFFFFFF);
        }
    }
    if (imgPath == null || "".equals(imgPath)) {
        return image;
    }
    // 插入图片
    QRCodeUtil.insertImage(image, imgPath, needCompress);
    return image;
}
 
Example #8
Source File: MyAddressActivity.java    From ETHWallet with GNU General Public License v3.0 6 votes vote down vote up
private Bitmap createQRImage(String address) {
    Point size = new Point();
    getWindowManager().getDefaultDisplay().getSize(size);
    int imageSize = (int) (size.x * QR_IMAGE_WIDTH_RATIO);
    try {
        BitMatrix bitMatrix = new MultiFormatWriter().encode(
                address,
                BarcodeFormat.QR_CODE,
                imageSize,
                imageSize,
                null);
        BarcodeEncoder barcodeEncoder = new BarcodeEncoder();
        return barcodeEncoder.createBitmap(bitMatrix);
    } catch (Exception e) {
        Toast.makeText(this, getString(R.string.error_fail_generate_qr), Toast.LENGTH_SHORT)
                .show();
    }
    return null;
}
 
Example #9
Source File: OneDimensionalCodeWriter.java    From analyzer-of-android-for-Apache-Weex with Apache License 2.0 6 votes vote down vote up
/**
 * Encode the contents following specified format.
 * {@code width} and {@code height} are required size. This method may return bigger size
 * {@code BitMatrix} when specified size is too small. The user can set both {@code width} and
 * {@code height} to zero to get minimum size barcode. If negative value is set to {@code width}
 * or {@code height}, {@code IllegalArgumentException} is thrown.
 */
@Override
public BitMatrix encode(String contents,
                        BarcodeFormat format,
                        int width,
                        int height,
                        Map<EncodeHintType,?> hints) throws WriterException {
  if (contents.isEmpty()) {
    throw new IllegalArgumentException("Found empty contents");
  }

  if (width < 0 || height < 0) {
    throw new IllegalArgumentException("Negative size is not allowed. Input: "
                                           + width + 'x' + height);
  }

  int sidesMargin = getDefaultMargin();
  if (hints != null && hints.containsKey(EncodeHintType.MARGIN)) {
    sidesMargin = Integer.parseInt(hints.get(EncodeHintType.MARGIN).toString());
  }

  boolean[] code = encode(contents);
  return renderResult(code, width, height, sidesMargin);
}
 
Example #10
Source File: Detector.java    From weex with Apache License 2.0 6 votes vote down vote up
/**
 * Locate the vertices and the codewords area of a black blob using the Start
 * and Stop patterns as locators.
 *
 * @param matrix the scanned barcode image.
 * @return an array containing the vertices:
 *           vertices[0] x, y top left barcode
 *           vertices[1] x, y bottom left barcode
 *           vertices[2] x, y top right barcode
 *           vertices[3] x, y bottom right barcode
 *           vertices[4] x, y top left codeword area
 *           vertices[5] x, y bottom left codeword area
 *           vertices[6] x, y top right codeword area
 *           vertices[7] x, y bottom right codeword area
 */
private static ResultPoint[] findVertices(BitMatrix matrix, int startRow, int startColumn) {
  int height = matrix.getHeight();
  int width = matrix.getWidth();

  ResultPoint[] result = new ResultPoint[8];
  copyToResult(result, findRowsWithPattern(matrix, height, width, startRow, startColumn, START_PATTERN),
      INDEXES_START_PATTERN);

  if (result[4] != null) {
    startColumn = (int) result[4].getX();
    startRow = (int) result[4].getY();
  }
  copyToResult(result, findRowsWithPattern(matrix, height, width, startRow, startColumn, STOP_PATTERN),
      INDEXES_STOP_PATTERN);
  return result;
}
 
Example #11
Source File: PMedia.java    From PHONK with GNU General Public License v3.0 6 votes vote down vote up
public Bitmap generateQRCode(String text) {
    Bitmap bmp = null;

    Hashtable<EncodeHintType, ErrorCorrectionLevel> hintMap = new Hashtable<EncodeHintType, ErrorCorrectionLevel>();
    hintMap.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H); // H = 30% damage

    int size = 256;

    BitMatrix bitMatrix = null;
    try {
        bitMatrix = new QRCodeWriter().encode(text, BarcodeFormat.QR_CODE, size, size, hintMap);

        int width = bitMatrix.getWidth();
        bmp = Bitmap.createBitmap(width, width, Bitmap.Config.RGB_565);
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < width; y++) {
                bmp.setPixel(y, x, bitMatrix.get(x, y) == true ? Color.BLACK : Color.WHITE);
            }
        }
    } catch (WriterException e) {
        e.printStackTrace();
    }

    return bmp;
}
 
Example #12
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 #13
Source File: RQCodeUtils.java    From MaxKey with Apache License 2.0 6 votes vote down vote up
public static BitMatrix genRQCode(String rqCodeText,int width, int height ){
	if(width==0){
		width=200;
	}
	if(height==0){
		height=200;
	}
	try {  
		return  new MultiFormatWriter().encode(
        		rqCodeText, 
        		BarcodeFormat.QR_CODE, 
        		width, 
        		height);  
	} catch (Exception e) {  
           e.printStackTrace();  
       }  
	return null;
}
 
Example #14
Source File: ActionCreateCode.java    From o2oa with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
    *二维码实现
    * @param msg /二维码包含的信息
    * @param path /二维码存放路径
    */
public static void getBarCode(String msg,String path){
        try {
            File file=new File(path);
            OutputStream ous=new FileOutputStream(file);
            if(StringUtils.isEmpty(msg) || ous==null)
                return;
            String format = "png";
            MultiFormatWriter multiFormatWriter = new MultiFormatWriter();  
            Map<EncodeHintType,String> map =new HashMap<EncodeHintType, String>();
            //设置编码 EncodeHintType类中可以设置MAX_SIZE, ERROR_CORRECTION,CHARACTER_SET,DATA_MATRIX_SHAPE,AZTEC_LAYERS等参数
            map.put(EncodeHintType.CHARACTER_SET,"UTF-8");
            map.put(EncodeHintType.MARGIN,"1");
            //生成二维码
            BitMatrix bitMatrix = new MultiFormatWriter().encode(msg, BarcodeFormat.QR_CODE,300,300,map);
            MatrixToImageWriter.writeToStream(bitMatrix,format,ous);
        }catch (Exception e) {
            e.printStackTrace();
        }
}
 
Example #15
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 #16
Source File: PDF417ScanningDecoder.java    From weex with Apache License 2.0 6 votes vote down vote up
private static int adjustCodewordStartColumn(BitMatrix image,
                                             int minColumn,
                                             int maxColumn,
                                             boolean leftToRight,
                                             int codewordStartColumn,
                                             int imageRow) {
  int correctedStartColumn = codewordStartColumn;
  int increment = leftToRight ? -1 : 1;
  // there should be no black pixels before the start column. If there are, then we need to start earlier.
  for (int i = 0; i < 2; i++) {
    while (((leftToRight && correctedStartColumn >= minColumn) || (!leftToRight && correctedStartColumn < maxColumn)) &&
        leftToRight == image.get(correctedStartColumn, imageRow)) {
      if (Math.abs(codewordStartColumn - correctedStartColumn) > CODEWORD_SKEW_SIZE) {
        return codewordStartColumn;
      }
      correctedStartColumn += increment;
    }
    increment = -increment;
    leftToRight = !leftToRight;
  }
  return correctedStartColumn;
}
 
Example #17
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 #18
Source File: QrCodeGenerator.java    From QrCodeLib with MIT License 6 votes vote down vote up
public static Bitmap getQrCodeImage(String data, int width, int height) {
    if (data == null || data.length() == 0) {
        return null;
    }
    Map<EncodeHintType, Object> hintsMap = new HashMap<>(3);
    hintsMap.put(EncodeHintType.CHARACTER_SET, "utf-8");
    hintsMap.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
    hintsMap.put(EncodeHintType.MARGIN, 0);
    try {
        BitMatrix bitMatrix = new MultiFormatWriter().encode(data, BarcodeFormat.QR_CODE, width, height, hintsMap);
        Bitmap bitmap = bitMatrix2Bitmap(bitMatrix);
        return bitmap;
    } catch (WriterException e) {
        e.printStackTrace();
    }
    return null;
}
 
Example #19
Source File: Detector.java    From ZXing-Orient with Apache License 2.0 5 votes vote down vote up
private static BitMatrix sampleGrid(BitMatrix image,
                                    PerspectiveTransform transform,
                                    int dimension) throws NotFoundException {

  GridSampler sampler = GridSampler.getInstance();
  return sampler.sampleGrid(image, dimension, dimension, transform);
}
 
Example #20
Source File: EAN13Writer.java    From reacteu-app with MIT License 5 votes vote down vote up
@Override
public BitMatrix encode(String contents,
                        BarcodeFormat format,
                        int width,
                        int height,
                        Map<EncodeHintType,?> hints) throws WriterException {
  if (format != BarcodeFormat.EAN_13) {
    throw new IllegalArgumentException("Can only encode EAN_13, but got " + format);
  }

  return super.encode(contents, format, width, height, hints);
}
 
Example #21
Source File: BitMatrixParser.java    From reacteu-app with MIT License 5 votes vote down vote up
/**
 * <p>Extracts the data region from a {@link BitMatrix} that contains
 * alignment patterns.</p>
 * 
 * @param bitMatrix Original {@link BitMatrix} with alignment patterns
 * @return BitMatrix that has the alignment patterns removed
 */
BitMatrix extractDataRegion(BitMatrix bitMatrix) {
  int symbolSizeRows = version.getSymbolSizeRows();
  int symbolSizeColumns = version.getSymbolSizeColumns();
  
  if (bitMatrix.getHeight() != symbolSizeRows) {
    throw new IllegalArgumentException("Dimension of bitMarix must match the version size");
  }
  
  int dataRegionSizeRows = version.getDataRegionSizeRows();
  int dataRegionSizeColumns = version.getDataRegionSizeColumns();
  
  int numDataRegionsRow = symbolSizeRows / dataRegionSizeRows;
  int numDataRegionsColumn = symbolSizeColumns / dataRegionSizeColumns;
  
  int sizeDataRegionRow = numDataRegionsRow * dataRegionSizeRows;
  int sizeDataRegionColumn = numDataRegionsColumn * dataRegionSizeColumns;
  
  BitMatrix bitMatrixWithoutAlignment = new BitMatrix(sizeDataRegionColumn, sizeDataRegionRow);
  for (int dataRegionRow = 0; dataRegionRow < numDataRegionsRow; ++dataRegionRow) {
    int dataRegionRowOffset = dataRegionRow * dataRegionSizeRows;
    for (int dataRegionColumn = 0; dataRegionColumn < numDataRegionsColumn; ++dataRegionColumn) {
      int dataRegionColumnOffset = dataRegionColumn * dataRegionSizeColumns;
      for (int i = 0; i < dataRegionSizeRows; ++i) {
        int readRowOffset = dataRegionRow * (dataRegionSizeRows + 2) + 1 + i;
        int writeRowOffset = dataRegionRowOffset + i;
        for (int j = 0; j < dataRegionSizeColumns; ++j) {
          int readColumnOffset = dataRegionColumn * (dataRegionSizeColumns + 2) + 1 + j;
          if (bitMatrix.get(readColumnOffset, readRowOffset)) {
            int writeColumnOffset = dataRegionColumnOffset + j;
            bitMatrixWithoutAlignment.set(writeColumnOffset, writeRowOffset);
          }
        }
      }
    }
  }
  return bitMatrixWithoutAlignment;
}
 
Example #22
Source File: PDF417Writer.java    From ZXing-Orient with Apache License 2.0 5 votes vote down vote up
/**
 * Takes encoder, accounts for width/height, and retrieves bit matrix
 */
private static BitMatrix bitMatrixFromEncoder(PDF417 encoder,
                                              String contents,
                                              int width,
                                              int height,
                                              int margin) throws WriterException {
  int errorCorrectionLevel = 2;
  encoder.generateBarcodeLogic(contents, errorCorrectionLevel);

  int lineThickness = 2;
  int aspectRatio = 4;
  byte[][] originalScale = encoder.getBarcodeMatrix().getScaledMatrix(lineThickness, aspectRatio * lineThickness);
  boolean rotated = false;
  if ((height > width) ^ (originalScale[0].length < originalScale.length)) {
    originalScale = rotateArray(originalScale);
    rotated = true;
  }

  int scaleX = width / originalScale[0].length;
  int scaleY = height / originalScale.length;

  int scale;
  if (scaleX < scaleY) {
    scale = scaleX;
  } else {
    scale = scaleY;
  }

  if (scale > 1) {
    byte[][] scaledMatrix =
        encoder.getBarcodeMatrix().getScaledMatrix(scale * lineThickness, scale * aspectRatio * lineThickness);
    if (rotated) {
      scaledMatrix = rotateArray(scaledMatrix);
    }
    return bitMatrixFrombitArray(scaledMatrix, margin);
  }
  return bitMatrixFrombitArray(originalScale, margin);
}
 
Example #23
Source File: PDF417Writer.java    From MiBandDecompiled with Apache License 2.0 5 votes vote down vote up
public BitMatrix encode(String s, BarcodeFormat barcodeformat, boolean flag, int i, int j, int k, int l, 
        int i1, int j1, Compaction compaction)
{
    c c1 = a(barcodeformat, flag);
    c1.a(l, k, j1, i1);
    c1.a(compaction);
    return a(c1, s, i, j);
}
 
Example #24
Source File: EncodingUtils.java    From tysq-android with GNU General Public License v3.0 5 votes vote down vote up
/**
 * 创建二维码
 *
 * @param content   content
 * @param widthPix  widthPix
 * @param heightPix heightPix
 * @param logoBm    logoBm
 * @return 二维码
 */
public static Bitmap createQRCode(String content, int widthPix, int heightPix, Bitmap logoBm) {
    try {
        if (content == null || "".equals(content)) {
            return null;
        }
        // 配置参数
        Map<EncodeHintType, Object> hints = new HashMap<>();
        hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
        // 容错级别 这里选择最高H级别
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
        // 图像数据转换,使用了矩阵转换 参数顺序分别为:编码内容,编码类型,生成图片宽度,生成图片高度,设置参数
        BitMatrix bitMatrix = new QRCodeWriter().encode(content, BarcodeFormat.QR_CODE, widthPix,
                heightPix, hints);
        int[] pixels = new int[widthPix * heightPix];
        // 下面这里按照二维码的算法,逐个生成二维码的图片,
        // 两个for循环是图片横列扫描的结果
        for (int y = 0; y < heightPix; y++) {
            for (int x = 0; x < widthPix; x++) {
                if (bitMatrix.get(x, y)) {
                    pixels[y * widthPix + x] = 0xff000000; // 黑色
                } else {
                    pixels[y * widthPix + x] = 0xffffffff;// 白色
                }
            }
        }
        // 生成二维码图片的格式,使用ARGB_8888
        Bitmap bitmap = Bitmap.createBitmap(widthPix, heightPix, Bitmap.Config.ARGB_8888);
        bitmap.setPixels(pixels, 0, widthPix, 0, 0, widthPix, heightPix);
        if (logoBm != null) {//绘制logo
            bitmap = addLogo(bitmap, logoBm);
        }
        //必须使用compress方法将bitmap保存到文件中再进行读取。直接返回的bitmap是没有任何压缩的,内存消耗巨大!
        return bitmap;
    } catch (WriterException e) {
        e.printStackTrace();
    }
    return null;
}
 
Example #25
Source File: Version.java    From analyzer-of-android-for-Apache-Weex with Apache License 2.0 5 votes vote down vote up
/**
 * See ISO 18004:2006 Annex E
 */
BitMatrix buildFunctionPattern() {
  int dimension = getDimensionForVersion();
  BitMatrix bitMatrix = new BitMatrix(dimension);

  // Top left finder pattern + separator + format
  bitMatrix.setRegion(0, 0, 9, 9);
  // Top right finder pattern + separator + format
  bitMatrix.setRegion(dimension - 8, 0, 8, 9);
  // Bottom left finder pattern + separator + format
  bitMatrix.setRegion(0, dimension - 8, 9, 8);

  // Alignment patterns
  int max = alignmentPatternCenters.length;
  for (int x = 0; x < max; x++) {
    int i = alignmentPatternCenters[x] - 2;
    for (int y = 0; y < max; y++) {
      if ((x == 0 && (y == 0 || y == max - 1)) || (x == max - 1 && y == 0)) {
        // No alignment patterns near the three finder paterns
        continue;
      }
      bitMatrix.setRegion(alignmentPatternCenters[y] - 2, i, 5, 5);
    }
  }

  // Vertical timing pattern
  bitMatrix.setRegion(6, 9, 1, dimension - 17);
  // Horizontal timing pattern
  bitMatrix.setRegion(9, 6, dimension - 17, 1);

  if (versionNumber > 6) {
    // Version info, top right
    bitMatrix.setRegion(dimension - 11, 0, 3, 6);
    // Version info, bottom left
    bitMatrix.setRegion(0, dimension - 11, 6, 3);
  }

  return bitMatrix;
}
 
Example #26
Source File: MainActivity.java    From android-apps with MIT License 5 votes vote down vote up
public void createBarcodeBitmap(){
  	String barcode_content = etString.getText().toString();
  	String fileNames[] = barcode_content.split("\n");
  	String fileName = "QR_" + fileNames[0];
  	QRCodeWriter qrWriter = new QRCodeWriter();

try {
	BitMatrix bitMatrix = qrWriter.encode(barcode_content, BarcodeFormat.QR_CODE, 250, 250);
	Bitmap bitmap = toBitmap(bitMatrix);
	scannedBitmap.setImageBitmap(bitmap);
	
	
	ByteArrayOutputStream bytes = new ByteArrayOutputStream();
	bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bytes);

	//you can create a new file name "test.jpg" in sdcard folder.
	File f = new File(Environment.getExternalStorageDirectory()
	                        + File.separator + "QRCODES" + File.separator + fileName + ".jpg");
	f.createNewFile();
	//write the bytes in file
	FileOutputStream fout = new FileOutputStream(f);
	fout.write(bytes.toByteArray());

	// remember close de FileOutput
	fout.close();
	
} catch (Exception e) {
	e.printStackTrace();
}
  }
 
Example #27
Source File: BitMatrixParser.java    From analyzer-of-android-for-Apache-Weex with Apache License 2.0 5 votes vote down vote up
/**
 * @param bitMatrix {@link BitMatrix} to parse
 * @throws FormatException if dimension is < 8 or > 144 or not 0 mod 2
 */
BitMatrixParser(BitMatrix bitMatrix) throws FormatException {
  int dimension = bitMatrix.getHeight();
  if (dimension < 8 || dimension > 144 || (dimension & 0x01) != 0) {
    throw FormatException.getFormatInstance();
  }
  
  version = readVersion(bitMatrix);
  this.mappingBitMatrix = extractDataRegion(bitMatrix);
  this.readMappingMatrix = new BitMatrix(this.mappingBitMatrix.getWidth(), this.mappingBitMatrix.getHeight());
}
 
Example #28
Source File: BinaryBitmap.java    From ZXing-Orient with Apache License 2.0 5 votes vote down vote up
/**
 * Converts a 2D array of luminance data to 1 bit. As above, assume this method is expensive
 * and do not call it repeatedly. This method is intended for decoding 2D barcodes and may or
 * may not apply sharpening. Therefore, a row from this matrix may not be identical to one
 * fetched using getBlackRow(), so don't mix and match between them.
 *
 * @return The 2D array of bits for the image (true means black).
 * @throws NotFoundException if image can't be binarized to make a matrix
 */
public BitMatrix getBlackMatrix() throws NotFoundException {
  // The matrix is created on demand the first time it is requested, then cached. There are two
  // reasons for this:
  // 1. This work will never be done if the caller only installs 1D Reader objects, or if a
  //    1D Reader finds a barcode before the 2D Readers run.
  // 2. This work will only be done once even if the caller installs multiple 2D Readers.
  if (matrix == null) {
    matrix = binarizer.getBlackMatrix();
  }
  return matrix;
}
 
Example #29
Source File: BitMatrixParser.java    From weex with Apache License 2.0 5 votes vote down vote up
/**
 * <p>Extracts the data region from a {@link BitMatrix} that contains
 * alignment patterns.</p>
 * 
 * @param bitMatrix Original {@link BitMatrix} with alignment patterns
 * @return BitMatrix that has the alignment patterns removed
 */
BitMatrix extractDataRegion(BitMatrix bitMatrix) {
  int symbolSizeRows = version.getSymbolSizeRows();
  int symbolSizeColumns = version.getSymbolSizeColumns();
  
  if (bitMatrix.getHeight() != symbolSizeRows) {
    throw new IllegalArgumentException("Dimension of bitMarix must match the version size");
  }
  
  int dataRegionSizeRows = version.getDataRegionSizeRows();
  int dataRegionSizeColumns = version.getDataRegionSizeColumns();
  
  int numDataRegionsRow = symbolSizeRows / dataRegionSizeRows;
  int numDataRegionsColumn = symbolSizeColumns / dataRegionSizeColumns;
  
  int sizeDataRegionRow = numDataRegionsRow * dataRegionSizeRows;
  int sizeDataRegionColumn = numDataRegionsColumn * dataRegionSizeColumns;
  
  BitMatrix bitMatrixWithoutAlignment = new BitMatrix(sizeDataRegionColumn, sizeDataRegionRow);
  for (int dataRegionRow = 0; dataRegionRow < numDataRegionsRow; ++dataRegionRow) {
    int dataRegionRowOffset = dataRegionRow * dataRegionSizeRows;
    for (int dataRegionColumn = 0; dataRegionColumn < numDataRegionsColumn; ++dataRegionColumn) {
      int dataRegionColumnOffset = dataRegionColumn * dataRegionSizeColumns;
      for (int i = 0; i < dataRegionSizeRows; ++i) {
        int readRowOffset = dataRegionRow * (dataRegionSizeRows + 2) + 1 + i;
        int writeRowOffset = dataRegionRowOffset + i;
        for (int j = 0; j < dataRegionSizeColumns; ++j) {
          int readColumnOffset = dataRegionColumn * (dataRegionSizeColumns + 2) + 1 + j;
          if (bitMatrix.get(readColumnOffset, readRowOffset)) {
            int writeColumnOffset = dataRegionColumnOffset + j;
            bitMatrixWithoutAlignment.set(writeColumnOffset, writeRowOffset);
          }
        }
      }
    }
  }
  return bitMatrixWithoutAlignment;
}
 
Example #30
Source File: BoundingBox.java    From ZXing-Orient with Apache License 2.0 5 votes vote down vote up
BoundingBox(BitMatrix image,
            ResultPoint topLeft,
            ResultPoint bottomLeft,
            ResultPoint topRight,
            ResultPoint bottomRight) throws NotFoundException {
  if ((topLeft == null && topRight == null) ||
      (bottomLeft == null && bottomRight == null) ||
      (topLeft != null && bottomLeft == null) ||
      (topRight != null && bottomRight == null)) {
    throw NotFoundException.getNotFoundInstance();
  }
  init(image, topLeft, bottomLeft, topRight, bottomRight);
}