com.google.zxing.WriterException Java Examples

The following examples show how to use com.google.zxing.WriterException. 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: QrCode.java    From mollyim-android with GNU General Public License v3.0 7 votes vote down vote up
public static @NonNull Bitmap create(String data) {
  try {
    BitMatrix result = new QRCodeWriter().encode(data, BarcodeFormat.QR_CODE, 512, 512);
    Bitmap    bitmap = Bitmap.createBitmap(result.getWidth(), result.getHeight(), Bitmap.Config.ARGB_8888);

    for (int y = 0; y < result.getHeight(); y++) {
      for (int x = 0; x < result.getWidth(); x++) {
        if (result.get(x, y)) {
          bitmap.setPixel(x, y, Color.BLACK);
        }
      }
    }

    return bitmap;
  } catch (WriterException e) {
    Log.w(TAG, e);
    return Bitmap.createBitmap(512, 512, Bitmap.Config.ARGB_8888);
  }
}
 
Example #2
Source File: EncodingHandler.java    From vmqApk with MIT License 7 votes vote down vote up
public static Bitmap createQRCode(String str, int widthAndHeight) throws WriterException {
	Hashtable<EncodeHintType, String> hints = new Hashtable<EncodeHintType, String>();
       hints.put(EncodeHintType.CHARACTER_SET, "utf-8"); 
	BitMatrix matrix = new MultiFormatWriter().encode(str,
			BarcodeFormat.QR_CODE, widthAndHeight, widthAndHeight);
	int width = matrix.getWidth();
	int height = matrix.getHeight();
	int[] pixels = new int[width * height];
	
	for (int y = 0; y < height; y++) {
		for (int x = 0; x < width; x++) {
			if (matrix.get(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);
	return bitmap;
}
 
Example #3
Source File: QrCodeCreateUtil.java    From java-study with Apache License 2.0 6 votes vote down vote up
/**
 * 生成包含字符串信息的二维码图片
 *
 * @param outputStream 文件输出流路径
 * @param content      二维码携带信息
 * @param qrCodeSize   二维码图片大小
 * @param imageFormat  二维码的格式
 * @throws WriterException
 * @throws IOException
 */
public static boolean createQrCode(OutputStream outputStream, String content, int qrCodeSize, String imageFormat) throws WriterException, IOException {
    //设置二维码纠错级别MAP
    Hashtable<EncodeHintType, ErrorCorrectionLevel> hintMap = new Hashtable<EncodeHintType, ErrorCorrectionLevel>();
    hintMap.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);  // 矫错级别
    QRCodeWriter qrCodeWriter = new QRCodeWriter();
    //创建比特矩阵(位矩阵)的QR码编码的字符串
    BitMatrix byteMatrix = qrCodeWriter.encode(content, BarcodeFormat.QR_CODE, qrCodeSize, qrCodeSize, hintMap);
    // 使BufferedImage勾画QRCode  (matrixWidth 是行二维码像素点)
    int matrixWidth = byteMatrix.getWidth();
    BufferedImage image = new BufferedImage(matrixWidth - 200, matrixWidth - 200, BufferedImage.TYPE_INT_RGB);
    image.createGraphics();
    Graphics2D graphics = (Graphics2D) image.getGraphics();
    graphics.setColor(Color.WHITE);
    graphics.fillRect(0, 0, matrixWidth, matrixWidth);
    // 使用比特矩阵画并保存图像
    graphics.setColor(Color.BLACK);
    for (int i = 0; i < matrixWidth; i++) {
        for (int j = 0; j < matrixWidth; j++) {
            if (byteMatrix.get(i, j)) {
                graphics.fillRect(i - 100, j - 100, 1, 1);
            }
        }
    }
    return ImageIO.write(image, imageFormat, outputStream);
}
 
Example #4
Source File: AttestationActivity.java    From Auditor with MIT License 6 votes vote down vote up
private Bitmap createQrCode(final byte[] contents) {
    final BitMatrix result;
    try {
        final QRCodeWriter writer = new QRCodeWriter();
        final Map<EncodeHintType,Object> hints = new EnumMap<>(EncodeHintType.class);
        hints.put(EncodeHintType.CHARACTER_SET, StandardCharsets.ISO_8859_1);
        final int size = Math.min(imageView.getWidth(), imageView.getHeight());
        result = writer.encode(new String(contents, StandardCharsets.ISO_8859_1), BarcodeFormat.QR_CODE,
                size, size, hints);
    } catch (WriterException e) {
        throw new RuntimeException(e);
    }

    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) ? BLACK : WHITE;
        }
    }

    return Bitmap.createBitmap(pixels, width, height, Bitmap.Config.RGB_565);
}
 
Example #5
Source File: Encoder.java    From ScreenCapture with MIT License 6 votes vote down vote up
static void appendAlphanumericBytes(CharSequence content, BitArray bits) throws WriterException {
  int length = content.length();
  int i = 0;
  while (i < length) {
    int code1 = getAlphanumericCode(content.charAt(i));
    if (code1 == -1) {
      throw new WriterException();
    }
    if (i + 1 < length) {
      int code2 = getAlphanumericCode(content.charAt(i + 1));
      if (code2 == -1) {
        throw new WriterException();
      }
      // Encode two alphanumeric letters in 11 bits.
      bits.appendBits(code1 * 45 + code2, 11);
      i += 2;
    } else {
      // Encode one alphanumeric letter in six bits.
      bits.appendBits(code1, 6);
      i++;
    }
  }
}
 
Example #6
Source File: QRShowActivity.java    From trigger with GNU General Public License v2.0 6 votes vote down vote up
private void generateQR(Setup setup) throws Exception {
    MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
    int data_length = 0;
    try {
        JSONObject obj = Settings.toJsonObject(setup);
        String data = encodeSetup(obj);
        data_length = data.length();

        // data has to be a string
        BitMatrix bitMatrix = multiFormatWriter.encode(data, BarcodeFormat.QR_CODE, 1080, 1080);
        BarcodeEncoder barcodeEncoder = new BarcodeEncoder();
        Bitmap bitmap = barcodeEncoder.createBitmap(bitMatrix);
        ((ImageView) findViewById(R.id.QRView)).setImageBitmap(bitmap);
    } catch (WriterException e) {
        Toast.makeText(this, e.getMessage() + " (" + data_length + " Bytes)", Toast.LENGTH_LONG).show();
        finish();
    }
}
 
Example #7
Source File: Encoder.java    From ScreenCapture with MIT License 6 votes vote down vote up
static void appendKanjiBytes(String content, BitArray bits) throws WriterException {
  byte[] bytes;
  try {
    bytes = content.getBytes("Shift_JIS");
  } catch (UnsupportedEncodingException uee) {
    throw new WriterException(uee);
  }
  int length = bytes.length;
  for (int i = 0; i < length; i += 2) {
    int byte1 = bytes[i] & 0xFF;
    int byte2 = bytes[i + 1] & 0xFF;
    int code = (byte1 << 8) | byte2;
    int subtracted = -1;
    if (code >= 0x8140 && code <= 0x9ffc) {
      subtracted = code - 0x8140;
    } else if (code >= 0xe040 && code <= 0xebbf) {
      subtracted = code - 0xc140;
    }
    if (subtracted == -1) {
      throw new WriterException("Invalid byte sequence");
    }
    int encoded = ((subtracted >> 8) * 0xc0) + (subtracted & 0xff);
    bits.appendBits(encoded, 13);
  }
}
 
Example #8
Source File: PayUtil.java    From springboot-pay-example with Apache License 2.0 6 votes vote down vote up
/**
 * 根据url生成二位图片对象
 *
 * @param codeUrl
 * @return
 * @throws WriterException
 */
public static BufferedImage getQRCodeImge(String codeUrl) throws WriterException {
    Map<EncodeHintType, Object> hints = new Hashtable();
    hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
    hints.put(EncodeHintType.CHARACTER_SET, "UTF8");
    int width = 256;
    BitMatrix bitMatrix = (new MultiFormatWriter()).encode(codeUrl, BarcodeFormat.QR_CODE, width, width, hints);
    BufferedImage image = new BufferedImage(width, width, 1);
    for(int x = 0; x < width; ++x) {
        for(int y = 0; y < width; ++y) {
            image.setRGB(x, y, bitMatrix.get(x, y) ? -16777216 : -1);
        }
    }

    return image;
}
 
Example #9
Source File: MatrixUtil.java    From ScreenCapture with MIT License 6 votes vote down vote up
static void maybeEmbedVersionInfo(Version version, ByteMatrix matrix) throws WriterException {
  if (version.getVersionNumber() < 7) {  // Version info is necessary if version >= 7.
    return;  // Don't need version info.
  }
  BitArray versionInfoBits = new BitArray();
  makeVersionInfoBits(version, versionInfoBits);

  int bitIndex = 6 * 3 - 1;  // It will decrease from 17 to 0.
  for (int i = 0; i < 6; ++i) {
    for (int j = 0; j < 3; ++j) {
      // Place bits in LSB (least significant bit) to MSB order.
      boolean bit = versionInfoBits.get(bitIndex);
      bitIndex--;
      // Left bottom corner.
      matrix.set(i, matrix.getHeight() - 11 + j, bit);
      // Right bottom corner.
      matrix.set(matrix.getHeight() - 11 + j, i, bit);
    }
  }
}
 
Example #10
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 #11
Source File: EncodingHandler.java    From QrCodeDemo4 with MIT License 6 votes vote down vote up
public static Bitmap createQRCode(String str, int widthAndHeight) throws WriterException {
	Hashtable<EncodeHintType, String> hints = new Hashtable<EncodeHintType, String>();
       hints.put(EncodeHintType.CHARACTER_SET, "utf-8"); 
	BitMatrix matrix = new MultiFormatWriter().encode(str,
			BarcodeFormat.QR_CODE, widthAndHeight, widthAndHeight);
	int width = matrix.getWidth();
	int height = matrix.getHeight();
	int[] pixels = new int[width * height];
	
	for (int y = 0; y < height; y++) {
		for (int x = 0; x < width; x++) {
			if (matrix.get(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);
	return bitmap;
}
 
Example #12
Source File: MobileServerPreference.java    From Quelea with GNU General Public License v3.0 6 votes vote down vote up
private Image getQRImage() {
    if (qrImage == null) {
        QRCodeWriter qrCodeWriter = new QRCodeWriter();
        int qrWidth = 500;
        int qrHeight = 500;
        BitMatrix byteMatrix = null;
        try {
            byteMatrix = qrCodeWriter.encode(getMLURL(), BarcodeFormat.QR_CODE, qrWidth, qrHeight);
        } catch (WriterException ex) {
            LOGGER.log(Level.WARNING, "Error writing QR code", ex);
        }
        qrImage = MatrixToImageWriter.toBufferedImage(byteMatrix);
    }
    WritableImage fxImg = new WritableImage(500, 500);
    SwingFXUtils.toFXImage(qrImage, fxImg);
    return fxImg;
}
 
Example #13
Source File: QrCodeUtils.java    From guarda-android-wallets with GNU General Public License v3.0 6 votes vote down vote up
public static Bitmap textToBarCode(String data) {
    MultiFormatWriter writer = new MultiFormatWriter();


    String finaldata = Uri.encode(data, "utf-8");

    BitMatrix bm = null;
    try {
        bm = writer.encode(finaldata, BarcodeFormat.CODE_128, 150, 150);
    } catch (WriterException e) {
        e.printStackTrace();
    }
    Bitmap bitmap = Bitmap.createBitmap(180, 40, Bitmap.Config.ARGB_8888);

    for (int i = 0; i < 180; i++) {//width
        for (int j = 0; j < 40; j++) {//height
            bitmap.setPixel(i, j, bm.get(i, j) ? BLACK : WHITE);
        }
    }

    return bitmap;
}
 
Example #14
Source File: QRCodeEncode.java    From Tok-Android 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 #15
Source File: EncodingHandler.java    From QrCodeLib with MIT License 6 votes vote down vote up
public static Bitmap createQRCode(String str, int widthAndHeight) throws WriterException {
    Hashtable<EncodeHintType, String> hints = new Hashtable<EncodeHintType, String>();
    hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
    BitMatrix matrix = new MultiFormatWriter().encode(str,
            BarcodeFormat.QR_CODE, widthAndHeight, widthAndHeight);
    int width = matrix.getWidth();
    int height = matrix.getHeight();
    int[] pixels = new int[width * height];

    for (int y = 0; y < height; y++) {
        for (int x = 0; x < width; x++) {
            if (matrix.get(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);
    return bitmap;
}
 
Example #16
Source File: OneDimensionalCodeWriter.java    From ScreenCapture with MIT License 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 #17
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 #18
Source File: QRCodeEngine.java    From SlidesRemote with Apache License 2.0 6 votes vote down vote up
public static Image encode(String data, int width, int height) {
    try {
        BitMatrix byteMatrix = new QRCodeWriter().encode(data, BarcodeFormat.QR_CODE, width, height);
        BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        bufferedImage.createGraphics();
        Graphics2D graphics = (Graphics2D) bufferedImage.getGraphics();
        graphics.setColor(Color.decode("#00adb5"));
        graphics.fillRect(0, 0, width, height);
        graphics.setColor(Color.BLACK);
        for (int i = 0; i < height; i++) {
            for (int j = 0; j < width; j++) {
                if (byteMatrix.get(i, j)) {
                    graphics.fillRect(i, j, 1, 1);
                }
            }
        }

        return SwingFXUtils.toFXImage(bufferedImage, null);
    } catch (WriterException ex) {
        ex.printStackTrace();
        return null;
    }
}
 
Example #19
Source File: QRPresenterActivity.java    From Meshenger with GNU General Public License v3.0 5 votes vote down vote up
private void generateQR() throws Exception {
    json = generateJson();

    Log.d(QRPresenterActivity.class.getSimpleName(), json);

    MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
    try {
        BitMatrix bitMatrix = multiFormatWriter.encode(json, BarcodeFormat.QR_CODE,1080,1080);
        BarcodeEncoder barcodeEncoder = new BarcodeEncoder();
        Bitmap bitmap = barcodeEncoder.createBitmap(bitMatrix);
        ((ImageView) findViewById(R.id.QRView)).setImageBitmap(bitmap);
    } catch (WriterException e) {
        e.printStackTrace();
    }
}
 
Example #20
Source File: Utils.java    From evt4j with MIT License 5 votes vote down vote up
public static byte[] getQrImageInBytes(String rawText) throws WriterException, IOException {
    int width = 600;
    int height = 600;

    Hashtable<EncodeHintType, Object> hints = new Hashtable<>();
    hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);

    QRCodeWriter qrCodeWriter = new QRCodeWriter();
    BitMatrix bitMatrix = qrCodeWriter.encode(rawText, BarcodeFormat.QR_CODE, width, height, hints);

    ByteArrayOutputStream pngOutputStream = new ByteArrayOutputStream();
    MatrixToImageWriter.writeToStream(bitMatrix, "PNG", pngOutputStream);

    return pngOutputStream.toByteArray();
}
 
Example #21
Source File: EncodingHandler.java    From QrCodeDemo4 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 #22
Source File: QRCodeWriter.java    From MyBox with Apache License 2.0 5 votes vote down vote up
@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 (format != BarcodeFormat.QR_CODE) {
        throw new IllegalArgumentException("Can only encode QR_CODE, but got " + format);
    }

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

    ErrorCorrectionLevel errorCorrectionLevel = ErrorCorrectionLevel.L;
    int quietZone = QUIET_ZONE_SIZE;
    if (hints != null) {
        if (hints.containsKey(EncodeHintType.ERROR_CORRECTION)) {
            errorCorrectionLevel = ErrorCorrectionLevel.valueOf(hints.get(EncodeHintType.ERROR_CORRECTION).toString());
        }
        if (hints.containsKey(EncodeHintType.MARGIN)) {
            quietZone = Integer.parseInt(hints.get(EncodeHintType.MARGIN).toString());
        }
    }

    code = Encoder.encode(contents, errorCorrectionLevel, hints);
    return renderResult(width, height, quietZone);
}
 
Example #23
Source File: Encoder.java    From ScreenCapture with MIT License 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 #24
Source File: CodeCreator.java    From FoodOrdering with Apache License 2.0 5 votes vote down vote up
/**
 * 生成QRCode(二维码)
 * 
 * @param str
 * @return
 * @throws WriterException
 */
public static Bitmap createQRCode(String url) throws WriterException {

	if (url == null || url.equals("")) {
		return null;
	}

	// 生成二维矩阵,编码时指定大小,不要生成了图片以后再进行缩放,这样会模糊导致识别失败
	BitMatrix matrix = new MultiFormatWriter().encode(url,
			BarcodeFormat.QR_CODE, 300, 300);

	int width = matrix.getWidth();
	int height = matrix.getHeight();

	// 二维矩阵转为一维像素数组,也就是一直横着排了
	int[] pixels = new int[width * height];

	for (int y = 0; y < height; y++) {
		for (int x = 0; x < width; x++) {
			if (matrix.get(x, y)) {
				pixels[y * width + x] = 0xff000000;
			}

		}
	}

	Bitmap bitmap = Bitmap.createBitmap(width, height,
			Bitmap.Config.ARGB_8888);
	bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
	return bitmap;
}
 
Example #25
Source File: Encoder.java    From ScreenCapture with MIT License 5 votes vote down vote up
static void append8BitBytes(String content, BitArray bits, String encoding)
    throws WriterException {
  byte[] bytes;
  try {
    bytes = content.getBytes(encoding);
  } catch (UnsupportedEncodingException uee) {
    throw new WriterException(uee);
  }
  for (byte b : bytes) {
    bits.appendBits(b, 8);
  }
}
 
Example #26
Source File: Encoder.java    From ScreenCapture with MIT License 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");
}
 
Example #27
Source File: MatrixUtil.java    From ScreenCapture with MIT License 5 votes vote down vote up
private static void embedVerticalSeparationPattern(int xStart,
                                                   int yStart,
                                                   ByteMatrix matrix) throws WriterException {
  for (int y = 0; y < 7; ++y) {
    if (!isEmpty(matrix.get(xStart, yStart + y))) {
      throw new WriterException();
    }
    matrix.set(xStart, yStart + y, 0);
  }
}
 
Example #28
Source File: MatrixUtil.java    From ScreenCapture with MIT License 5 votes vote down vote up
private static void embedPositionDetectionPatternsAndSeparators(ByteMatrix matrix) throws WriterException {
  // Embed three big squares at corners.
  int pdpWidth = POSITION_DETECTION_PATTERN[0].length;
  // Left top corner.
  embedPositionDetectionPattern(0, 0, matrix);
  // Right top corner.
  embedPositionDetectionPattern(matrix.getWidth() - pdpWidth, 0, matrix);
  // Left bottom corner.
  embedPositionDetectionPattern(0, matrix.getWidth() - pdpWidth, matrix);

  // Embed horizontal separation patterns around the squares.
  int hspWidth = 8;
  // Left top corner.
  embedHorizontalSeparationPattern(0, hspWidth - 1, matrix);
  // Right top corner.
  embedHorizontalSeparationPattern(matrix.getWidth() - hspWidth,
      hspWidth - 1, matrix);
  // Left bottom corner.
  embedHorizontalSeparationPattern(0, matrix.getWidth() - hspWidth, matrix);

  // Embed vertical separation patterns around the squares.
  int vspSize = 7;
  // Left top corner.
  embedVerticalSeparationPattern(vspSize, 0, matrix);
  // Right top corner.
  embedVerticalSeparationPattern(matrix.getHeight() - vspSize - 1, 0, matrix);
  // Left bottom corner.
  embedVerticalSeparationPattern(vspSize, matrix.getHeight() - vspSize,
      matrix);
}
 
Example #29
Source File: CodeCreator.java    From ScanZxing with Apache License 2.0 5 votes vote down vote up
/**
 * 生成QRCode(二维码)
 * 
 * @param str
 * @return
 * @throws WriterException
 */
public static Bitmap createQRCode(String url) throws WriterException {

	if (url == null || url.equals("")) {
		return null;
	}

	// 生成二维矩阵,编码时指定大小,不要生成了图片以后再进行缩放,这样会模糊导致识别失败
	BitMatrix matrix = new MultiFormatWriter().encode(url,
			BarcodeFormat.QR_CODE, 300, 300);

	int width = matrix.getWidth();
	int height = matrix.getHeight();

	// 二维矩阵转为一维像素数组,也就是一直横着排了
	int[] pixels = new int[width * height];

	for (int y = 0; y < height; y++) {
		for (int x = 0; x < width; x++) {
			if (matrix.get(x, y)) {
				pixels[y * width + x] = 0xff000000;
			}

		}
	}

	Bitmap bitmap = Bitmap.createBitmap(width, height,
			Bitmap.Config.ARGB_8888);
	bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
	return bitmap;
}
 
Example #30
Source File: Utils.java    From tron-wallet-android with Apache License 2.0 5 votes vote down vote up
public static Bitmap strToQR(String str, int width, int height) {
    if(str == null || str.equals("")) {
        return null;
    }
    MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
    try {
        BitMatrix bitMatrix = multiFormatWriter.encode(str, BarcodeFormat.QR_CODE,width,height);
        BarcodeEncoder barcodeEncoder = new BarcodeEncoder();
        return barcodeEncoder.createBitmap(bitMatrix);
    } catch (WriterException e) {
        e.printStackTrace();
    }
    return null;
}