com.google.zxing.qrcode.decoder.ErrorCorrectionLevel Java Examples

The following examples show how to use com.google.zxing.qrcode.decoder.ErrorCorrectionLevel. 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: MatrixUtil.java    From ScreenCapture with MIT License 6 votes vote down vote up
static void makeTypeInfoBits(ErrorCorrectionLevel ecLevel, int maskPattern, BitArray bits)
    throws WriterException {
  if (!QRCode.isValidMaskPattern(maskPattern)) {
    throw new WriterException("Invalid mask pattern");
  }
  int typeInfo = (ecLevel.getBits() << 3) | maskPattern;
  bits.appendBits(typeInfo, 5);

  int bchCode = calculateBCHCode(typeInfo, TYPE_INFO_POLY);
  bits.appendBits(bchCode, 10);

  BitArray maskBits = new BitArray();
  maskBits.appendBits(TYPE_INFO_MASK_PATTERN, 15);
  bits.xor(maskBits);

  if (bits.getSize() != 15) {  // Just in case.
    throw new WriterException("should not happen but we got: " + bits.getSize());
  }
}
 
Example #2
Source File: Utils.java    From privacy-friendly-qr-scanner with GNU General Public License v3.0 6 votes vote down vote up
public static Bitmap generateCode(String data, BarcodeFormat format, Map<EncodeHintType, Object> hints, Map<ResultMetadataType,Object> metadata) {
    if(hints == null) {
        hints = new EnumMap<>(EncodeHintType.class);
    }

    if(!hints.containsKey(ERROR_CORRECTION) && metadata != null && metadata.containsKey(ERROR_CORRECTION_LEVEL)) {
        Object ec = metadata.get(ERROR_CORRECTION_LEVEL);
        if(ec != null) {
            hints.put(ERROR_CORRECTION, ec);
        }
    }
    if(!hints.containsKey(ERROR_CORRECTION)) {
        hints.put(ERROR_CORRECTION, ErrorCorrectionLevel.L.name());
    }

    return generateCode(data, format, hints);
}
 
Example #3
Source File: Encoder.java    From Telegram-FOSS with GNU General Public License v2.0 6 votes vote down vote up
private static int chooseMaskPattern(BitArray bits,
                                     ErrorCorrectionLevel ecLevel,
                                     Version version,
                                     ByteMatrix matrix) throws WriterException {

  int minPenalty = Integer.MAX_VALUE;  // Lower penalty is better.
  int bestMaskPattern = -1;
  // We try all mask patterns to choose the best one.
  for (int maskPattern = 0; maskPattern < QRCode.NUM_MASK_PATTERNS; maskPattern++) {
    MatrixUtil.buildMatrix(bits, ecLevel, version, maskPattern, matrix);
    int penalty = calculateMaskPenalty(matrix);
    if (penalty < minPenalty) {
      minPenalty = penalty;
      bestMaskPattern = maskPattern;
    }
  }
  return bestMaskPattern;
}
 
Example #4
Source File: BarcodeProvider.java    From Conversations 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 #5
Source File: ZxingUtils.java    From MeetingFilm with Apache License 2.0 6 votes vote down vote up
/** 将内容contents生成长为width,宽为width的图片,图片路径由imgPath指定
    */
public static File getQRCodeImge(String contents, int width, int height, String imgPath) {
	try {
           Map<EncodeHintType, Object> hints = new Hashtable<EncodeHintType, Object>();
           hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
           hints.put(EncodeHintType.CHARACTER_SET, "UTF8");

		BitMatrix bitMatrix = new MultiFormatWriter().encode(contents, BarcodeFormat.QR_CODE, width, height, hints);

           File imageFile = new File(imgPath);
		writeToFile(bitMatrix, "png", imageFile);

           return imageFile;

	} catch (Exception e) {
		log.error("create QR code error!", e);
           return null;
	}
}
 
Example #6
Source File: d.java    From MiBandDecompiled with Apache License 2.0 6 votes vote down vote up
static void a(ErrorCorrectionLevel errorcorrectionlevel, int j, ByteMatrix bytematrix)
{
    BitArray bitarray = new BitArray();
    a(errorcorrectionlevel, j, bitarray);
    int k = 0;
    while (k < bitarray.getSize()) 
    {
        boolean flag = bitarray.get((-1 + bitarray.getSize()) - k);
        bytematrix.set(f[k][0], f[k][1], flag);
        if (k < 8)
        {
            bytematrix.set(-1 + (bytematrix.getWidth() - k), 8, flag);
        } else
        {
            bytematrix.set(8, -7 + bytematrix.getHeight() + (k - 8), flag);
        }
        k++;
    }
}
 
Example #7
Source File: MatrixUtil.java    From analyzer-of-android-for-Apache-Weex with Apache License 2.0 6 votes vote down vote up
static void makeTypeInfoBits(ErrorCorrectionLevel ecLevel, int maskPattern, BitArray bits)
    throws WriterException {
  if (!QRCode.isValidMaskPattern(maskPattern)) {
    throw new WriterException("Invalid mask pattern");
  }
  int typeInfo = (ecLevel.getBits() << 3) | maskPattern;
  bits.appendBits(typeInfo, 5);

  int bchCode = calculateBCHCode(typeInfo, TYPE_INFO_POLY);
  bits.appendBits(bchCode, 10);

  BitArray maskBits = new BitArray();
  maskBits.appendBits(TYPE_INFO_MASK_PATTERN, 15);
  bits.xor(maskBits);

  if (bits.getSize() != 15) {  // Just in case.
    throw new WriterException("should not happen but we got: " + bits.getSize());
  }
}
 
Example #8
Source File: ZxingUtils.java    From wish-pay with Apache License 2.0 6 votes vote down vote up
/**
 * 将内容contents生成长为width,宽为width的图片,返回刘文静
 */
public static ServletOutputStream getQRCodeImge(String contents, int width, int height) throws IOException {
    ServletOutputStream stream = null;
    try {
        Map<EncodeHintType, Object> hints = Maps.newHashMap();
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
        hints.put(EncodeHintType.CHARACTER_SET, "UTF8");
        BitMatrix bitMatrix = new MultiFormatWriter().encode(contents, BarcodeFormat.QR_CODE, width, height, hints);
        MatrixToImageWriter.writeToStream(bitMatrix, "png", stream);
        return stream;
    } catch (Exception e) {
        log.error("create QR code error!", e);
        return null;
    } finally {
        if (stream != null) {
            stream.close();
        }
    }
}
 
Example #9
Source File: MatrixUtil.java    From Telegram with GNU General Public License v2.0 6 votes vote down vote up
static void makeTypeInfoBits(ErrorCorrectionLevel ecLevel, int maskPattern, BitArray bits)
    throws WriterException {
  if (!QRCode.isValidMaskPattern(maskPattern)) {
    throw new WriterException("Invalid mask pattern");
  }
  int typeInfo = (ecLevel.getBits() << 3) | maskPattern;
  bits.appendBits(typeInfo, 5);

  int bchCode = calculateBCHCode(typeInfo, TYPE_INFO_POLY);
  bits.appendBits(bchCode, 10);

  BitArray maskBits = new BitArray();
  maskBits.appendBits(TYPE_INFO_MASK_PATTERN, 15);
  bits.xor(maskBits);

  if (bits.getSize() != 15) {  // Just in case.
    throw new WriterException("should not happen but we got: " + bits.getSize());
  }
}
 
Example #10
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 #11
Source File: ZxingUtil.java    From javautils with Apache License 2.0 6 votes vote down vote up
/**
 * 设置二维码的参数
 * @param content
 * @param width
 * @param height
 * @return
 */
private static BitMatrix getBitMatrix(String content, int width, int height){
    /**
     * 设置二维码的参数
     */
    BitMatrix bitMatrix = null;
    try {
        Map<EncodeHintType, Object> hints = new HashMap<>(3);
        // 指定纠错等级
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);
        hints.put(EncodeHintType.CHARACTER_SET, Constants.UTF8);
        //设置白边
        hints.put(EncodeHintType.MARGIN, 1);
        // 生成矩阵
        bitMatrix = new MultiFormatWriter().encode(content,BarcodeFormat.QR_CODE,width,height,hints);
    } catch (Exception e) {
        e.printStackTrace();
    }

    return bitMatrix;
}
 
Example #12
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 #13
Source File: Encoder.java    From RipplePower with Apache License 2.0 6 votes vote down vote up
private static Version chooseVersion(int numInputBits, ErrorCorrectionLevel ecLevel) throws WriterException {
	// In the following comments, we use numbers of Version 7-H.
	for (int versionNum = 1; versionNum <= 40; versionNum++) {
		Version version = Version.getVersionForNumber(versionNum);
		// numBytes = 196
		int numBytes = version.getTotalCodewords();
		// getNumECBytes = 130
		Version.ECBlocks ecBlocks = version.getECBlocksForLevel(ecLevel);
		int numEcBytes = ecBlocks.getTotalECCodewords();
		// getNumDataBytes = 196 - 130 = 66
		int numDataBytes = numBytes - numEcBytes;
		int totalInputBytes = (numInputBits + 7) / 8;
		if (numDataBytes >= totalInputBytes) {
			return version;
		}
	}
	throw new WriterException("Data too big");
}
 
Example #14
Source File: ZXingResult.java    From actframework with Apache License 2.0 6 votes vote down vote up
private void renderCode(H.Response response) {
    response.contentType("image/png");
    Map<EncodeHintType, Object> hints = new HashMap<>();
    hints.put(EncodeHintType.CHARACTER_SET, Act.appConfig().encoding());
    hints.put(EncodeHintType.MARGIN, 0);
    ErrorCorrectionLevel level = errorCorrectionLevel();
    if (null != level) {
        hints.put(EncodeHintType.ERROR_CORRECTION, level);
    }
    MultiFormatWriter writer = new MultiFormatWriter();
    try {
        BitMatrix bitMatrix = writer.encode(getMessage(), barcodeFormat(), width, height, hints);
        MatrixToImageWriter.writeToStream(bitMatrix, "png", response.outputStream());
    } catch (Exception e) {
        throw E.unexpected(e);
    }
}
 
Example #15
Source File: MatrixUtil.java    From RipplePower with Apache License 2.0 6 votes vote down vote up
static void makeTypeInfoBits(ErrorCorrectionLevel ecLevel, int maskPattern, BitArray bits) throws WriterException {
	if (!QRCode.isValidMaskPattern(maskPattern)) {
		throw new WriterException("Invalid mask pattern");
	}
	int typeInfo = (ecLevel.getBits() << 3) | maskPattern;
	bits.appendBits(typeInfo, 5);

	int bchCode = calculateBCHCode(typeInfo, TYPE_INFO_POLY);
	bits.appendBits(bchCode, 10);

	BitArray maskBits = new BitArray();
	maskBits.appendBits(TYPE_INFO_MASK_PATTERN, 15);
	bits.xor(maskBits);

	if (bits.getSize() != 15) { // Just in case.
		throw new WriterException("should not happen but we got: " + bits.getSize());
	}
}
 
Example #16
Source File: ZxingHelper.java    From seezoon-framework-all with Apache License 2.0 6 votes vote down vote up
private BufferedImage createImage(String content, InputStream logo, boolean needCompress) throws Exception {
	Hashtable<EncodeHintType, Object> hints = new Hashtable<EncodeHintType, Object>();
	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, imageSize, imageSize,
			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 (logo == null) {
		return image;
	}
	// 插入logo
	this.insertLogo(image, logo, needCompress);
	return image;
}
 
Example #17
Source File: Encoder.java    From reacteu-app with MIT License 6 votes vote down vote up
private static Version chooseVersion(int numInputBits, ErrorCorrectionLevel ecLevel) throws WriterException {
  // In the following comments, we use numbers of Version 7-H.
  for (int versionNum = 1; versionNum <= 40; versionNum++) {
    Version version = Version.getVersionForNumber(versionNum);
    // numBytes = 196
    int numBytes = version.getTotalCodewords();
    // getNumECBytes = 130
    Version.ECBlocks ecBlocks = version.getECBlocksForLevel(ecLevel);
    int numEcBytes = ecBlocks.getTotalECCodewords();
    // getNumDataBytes = 196 - 130 = 66
    int numDataBytes = numBytes - numEcBytes;
    int totalInputBytes = (numInputBits + 7) / 8;
    if (numDataBytes >= totalInputBytes) {
      return version;
    }
  }
  throw new WriterException("Data too big");
}
 
Example #18
Source File: Qr.java    From bither-android with Apache License 2.0 6 votes vote down vote up
public static void printQrContentSize() {
    for (int versionNum = 1;
         versionNum <= 40;
         versionNum++) {
        Version version = Version.getVersionForNumber(versionNum);
        // numBytes = 196
        int numBytes = version.getTotalCodewords();
        // getNumECBytes = 130
        Version.ECBlocks ecBlocks = version.getECBlocksForLevel(ErrorCorrectionLevel.L);
        int numEcBytes = ecBlocks.getTotalECCodewords();
        // getNumDataBytes = 196 - 130 = 66
        int numDataBytes = numBytes - numEcBytes;
        int numInputBytes = numDataBytes * 8 - 7;
        int length = (numInputBytes - 10) / 11 * 2;
        LogUtil.d("Qr", "Version: " + versionNum + " numData bytes: " + numDataBytes + "  " +
                "input: " + numInputBytes + "  string length: " + length);
    }
}
 
Example #19
Source File: QRCodeWriter.java    From letv with Apache License 2.0 6 votes vote down vote up
public BitMatrix encode(String contents, BarcodeFormat format, int width, int height, Map<EncodeHintType, ?> hints) throws WriterException {
    if (contents.length() == 0) {
        throw new IllegalArgumentException("Found empty contents");
    } else if (format != BarcodeFormat.QR_CODE) {
        throw new IllegalArgumentException("Can only encode QR_CODE, but got " + format);
    } else if (width < 0 || height < 0) {
        throw new IllegalArgumentException("Requested dimensions are too small: " + width + 'x' + height);
    } else {
        ErrorCorrectionLevel errorCorrectionLevel = ErrorCorrectionLevel.L;
        int quietZone = 4;
        if (hints != null) {
            ErrorCorrectionLevel requestedECLevel = (ErrorCorrectionLevel) hints.get(EncodeHintType.ERROR_CORRECTION);
            if (requestedECLevel != null) {
                errorCorrectionLevel = requestedECLevel;
            }
            Integer quietZoneInt = (Integer) hints.get(EncodeHintType.MARGIN);
            if (quietZoneInt != null) {
                quietZone = quietZoneInt.intValue();
            }
        }
        return renderResult(Encoder.encode(contents, errorCorrectionLevel, hints), width, height, quietZone);
    }
}
 
Example #20
Source File: Encoder.java    From QrCodeScanner with GNU General Public License v3.0 6 votes vote down vote up
private static int chooseMaskPattern(BitArray bits,
                                     ErrorCorrectionLevel ecLevel,
                                     Version version,
                                     ByteMatrix matrix) throws WriterException {

  int minPenalty = Integer.MAX_VALUE;  // Lower penalty is better.
  int bestMaskPattern = -1;
  // We try all mask patterns to choose the best one.
  for (int maskPattern = 0; maskPattern < QRCode.NUM_MASK_PATTERNS; maskPattern++) {
    MatrixUtil.buildMatrix(bits, ecLevel, version, maskPattern, matrix);
    int penalty = calculateMaskPenalty(matrix);
    if (penalty < minPenalty) {
      minPenalty = penalty;
      bestMaskPattern = maskPattern;
    }
  }
  return bestMaskPattern;
}
 
Example #21
Source File: ScannerActivity.java    From SecScanQR with GNU General Public License v3.0 6 votes vote down vote up
/**
 * This method creates a picture of the scanned qr code
 */
private void showQrImage() {
    multiFormatWriter = new MultiFormatWriter();
    Map<EncodeHintType, Object> hintMap = new EnumMap<EncodeHintType, Object>(EncodeHintType.class);

    hintMap.put(EncodeHintType.CHARACTER_SET, "UTF-8");
    hintMap.put(EncodeHintType.MARGIN, 1); /* default = 4 */
    hintMap.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);
    try{
        BarcodeFormat format = generalHandler.StringToBarcodeFormat(qrcodeFormat);
        BitMatrix bitMatrix = multiFormatWriter.encode(qrcode, format, 250,250, hintMap);
        BarcodeEncoder barcodeEncoder = new BarcodeEncoder();
        bitmap = barcodeEncoder.createBitmap(bitMatrix);
        codeImage.setImageBitmap(bitmap);
    } catch (Exception e){
        codeImage.setVisibility(View.GONE);
    }
}
 
Example #22
Source File: MatrixUtil.java    From reacteu-app with MIT License 6 votes vote down vote up
static void makeTypeInfoBits(ErrorCorrectionLevel ecLevel, int maskPattern, BitArray bits)
    throws WriterException {
  if (!QRCode.isValidMaskPattern(maskPattern)) {
    throw new WriterException("Invalid mask pattern");
  }
  int typeInfo = (ecLevel.getBits() << 3) | maskPattern;
  bits.appendBits(typeInfo, 5);

  int bchCode = calculateBCHCode(typeInfo, TYPE_INFO_POLY);
  bits.appendBits(bchCode, 10);

  BitArray maskBits = new BitArray();
  maskBits.appendBits(TYPE_INFO_MASK_PATTERN, 15);
  bits.xor(maskBits);

  if (bits.getSize() != 15) {  // Just in case.
    throw new WriterException("should not happen but we got: " + bits.getSize());
  }
}
 
Example #23
Source File: ReceiveFragment.java    From xmrwallet with Apache License 2.0 6 votes vote down vote up
public Bitmap generate(String text, int width, int height) {
    if ((width <= 0) || (height <= 0)) return null;
    Map<EncodeHintType, Object> hints = new HashMap<>();
    hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
    hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
    try {
        BitMatrix bitMatrix = new QRCodeWriter().encode(text, 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 (bitMatrix.get(j, i)) {
                    pixels[i * width + j] = 0x00000000;
                } else {
                    pixels[i * height + j] = 0xffffffff;
                }
            }
        }
        Bitmap bitmap = Bitmap.createBitmap(pixels, 0, width, width, height, Bitmap.Config.RGB_565);
        bitmap = addLogo(bitmap);
        return bitmap;
    } catch (WriterException ex) {
        Timber.e(ex);
    }
    return null;
}
 
Example #24
Source File: MatrixUtil.java    From ZXing-Orient with Apache License 2.0 6 votes vote down vote up
static void makeTypeInfoBits(ErrorCorrectionLevel ecLevel, int maskPattern, BitArray bits)
    throws WriterException {
  if (!QRCode.isValidMaskPattern(maskPattern)) {
    throw new WriterException("Invalid mask pattern");
  }
  int typeInfo = (ecLevel.getBits() << 3) | maskPattern;
  bits.appendBits(typeInfo, 5);

  int bchCode = calculateBCHCode(typeInfo, TYPE_INFO_POLY);
  bits.appendBits(bchCode, 10);

  BitArray maskBits = new BitArray();
  maskBits.appendBits(TYPE_INFO_MASK_PATTERN, 15);
  bits.xor(maskBits);

  if (bits.getSize() != 15) {  // Just in case.
    throw new WriterException("should not happen but we got: " + bits.getSize());
  }
}
 
Example #25
Source File: MatrixUtil.java    From Telegram with GNU General Public License v2.0 5 votes vote down vote up
static void buildMatrix(BitArray dataBits,
                        ErrorCorrectionLevel ecLevel,
                        Version version,
                        int maskPattern,
                        ByteMatrix matrix) throws WriterException {
  clearMatrix(matrix);
  embedBasicPatterns(version, matrix);
  // Type information appear with any version.
  embedTypeInfo(ecLevel, maskPattern, matrix);
  // Version info appear if version >= 7.
  maybeEmbedVersionInfo(version, matrix);
  // Data should be embedded at end.
  embedDataBits(dataBits, maskPattern, matrix);
}
 
Example #26
Source File: Encoder.java    From QrCodeScanner with GNU General Public License v3.0 5 votes vote down vote up
/**
 * @return true if the number of input bits will fit in a code with the specified version and
 * error correction level.
 */
private static boolean willFit(int numInputBits, Version version, ErrorCorrectionLevel ecLevel) {
    // In the following comments, we use numbers of Version 7-H.
    // numBytes = 196
    int numBytes = version.getTotalCodewords();
    // getNumECBytes = 130
    Version.ECBlocks ecBlocks = version.getECBlocksForLevel(ecLevel);
    int numEcBytes = ecBlocks.getTotalECCodewords();
    // getNumDataBytes = 196 - 130 = 66
    int numDataBytes = numBytes - numEcBytes;
    int totalInputBytes = (numInputBits + 7) / 8;
    return numDataBytes >= totalInputBytes;
}
 
Example #27
Source File: Encoder.java    From Tesseract-OCR-Scanner with Apache License 2.0 5 votes vote down vote up
/**
 * @return true if the number of input bits will fit in a code with the specified version and
 * error correction level.
 */
private static boolean willFit(int numInputBits, Version version, ErrorCorrectionLevel ecLevel) {
    // In the following comments, we use numbers of Version 7-H.
    // numBytes = 196
    int numBytes = version.getTotalCodewords();
    // getNumECBytes = 130
    Version.ECBlocks ecBlocks = version.getECBlocksForLevel(ecLevel);
    int numEcBytes = ecBlocks.getTotalECCodewords();
    // getNumDataBytes = 196 - 130 = 66
    int numDataBytes = numBytes - numEcBytes;
    int totalInputBytes = (numInputBits + 7) / 8;
    return numDataBytes >= totalInputBytes;
}
 
Example #28
Source File: EncodingHandler.java    From QrCodeLib with MIT License 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");
        // 容错级别
        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) {
            bitmap = addLogo(bitmap, logoBm);
        }
        //必须使用compress方法将bitmap保存到文件中再进行读取。直接返回的bitmap是没有任何压缩的,内存消耗巨大!
        return bitmap;
    } catch (WriterException e) {
        e.printStackTrace();
    }
    return null;
}
 
Example #29
Source File: Encoder.java    From Tesseract-OCR-Scanner with Apache License 2.0 5 votes vote down vote up
/**
 * Decides the smallest version of QR code that will contain all of the provided data.
 *
 * @throws WriterException if the data cannot fit in any version
 */
private static Version recommendVersion(ErrorCorrectionLevel ecLevel,
                                        Mode mode,
                                        BitArray headerBits,
                                        BitArray dataBits) throws WriterException {
  // 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 = calculateBitsNeeded(mode, headerBits, dataBits, Version.getVersionForNumber(1));
  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 = calculateBitsNeeded(mode, headerBits, dataBits, provisionalVersion);
  return chooseVersion(bitsNeeded, ecLevel);
}
 
Example #30
Source File: Encoder.java    From Telegram with GNU General Public License v2.0 5 votes vote down vote up
private static Version chooseVersion(int numInputBits, ErrorCorrectionLevel ecLevel) throws WriterException {
  for (int versionNum = 1; versionNum <= 40; versionNum++) {
    Version version = Version.getVersionForNumber(versionNum);
    if (willFit(numInputBits, version, ecLevel)) {
      return version;
    }
  }
  throw new WriterException("Data too big");
}