Java Code Examples for com.google.zxing.qrcode.QRCodeWriter#encode()

The following examples show how to use com.google.zxing.qrcode.QRCodeWriter#encode() . 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: 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 2
Source File: MainActivity.java    From ExamplesAndroid with Apache License 2.0 6 votes vote down vote up
public static Bitmap encodeToQrCode(String text, int width, int height){
    QRCodeWriter writer = new QRCodeWriter();
    BitMatrix matrix = null;
    try {
        matrix = writer.encode(text, BarcodeFormat.QR_CODE, 100, 100);
    } catch (WriterException ex) {
        ex.printStackTrace();
    }
    Bitmap bmp = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
    for (int x = 0; x < width; x++){
        for (int y = 0; y < height; y++){
            bmp.setPixel(x, y, matrix.get(x,y) ? Color.BLACK : Color.WHITE);
        }
    }
    return bmp;
}
 
Example 3
Source File: QRCodeController.java    From eds-starter6-jpa with Apache License 2.0 6 votes vote down vote up
@RequireAnyAuthority
@RequestMapping(value = "/qr", method = RequestMethod.GET)
public void qrcode(HttpServletResponse response,
		@AuthenticationPrincipal JpaUserDetails jpaUserDetails)
		throws WriterException, IOException {

	User user = jpaUserDetails.getUser(this.jpaQueryFactory);
	if (user != null && StringUtils.hasText(user.getSecret())) {
		response.setContentType("image/png");
		String contents = "otpauth://totp/" + user.getEmail() + "?secret="
				+ user.getSecret() + "&issuer=" + this.appName;

		QRCodeWriter writer = new QRCodeWriter();
		BitMatrix matrix = writer.encode(contents, BarcodeFormat.QR_CODE, 200, 200);
		MatrixToImageWriter.writeToStream(matrix, "PNG", response.getOutputStream());
		response.getOutputStream().flush();
	}
}
 
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: 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 6
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 7
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 8
Source File: ReceivePanel.java    From snowblossom with Apache License 2.0 5 votes vote down vote up
public void runPass()
 {
try
{
     String wallet_name = (String)wallet_select_box.getSelectedItem();
     if (wallet_name == null)
     {
       setMessageBox("no wallet selected");
       setStatusBox("");
       return;
     }
     
     SnowBlossomClient client = ice_leaf.getWalletPanel().getWallet( wallet_name );
     if (client == null)
     {
       setMessageBox("no wallet selected");
       setStatusBox("");
       return;
     }
     
     AddressSpecHash spec = client.getPurse().getUnusedAddress(false,false);
     String address_str = spec.toAddressString(ice_leaf.getParams());

     QRCodeWriter qrCodeWriter = new QRCodeWriter();
     BitMatrix bit_matrix = qrCodeWriter.encode(address_str, BarcodeFormat.QR_CODE, qr_size, qr_size);

     BufferedImage bi = MatrixToImageWriter.toBufferedImage(bit_matrix);

     setQrImage(bi);

     setStatusBox(address_str);
     setMessageBox("");

}
catch(Throwable t)
{
	setMessageBox(ErrorUtil.getThrowInfo(t));
     setStatusBox("");
}
 }
 
Example 9
Source File: BluetoothServer.java    From ShootOFF with GNU General Public License v3.0 5 votes vote down vote up
private Optional<Image> generateQrCode(String address) {
	final QRCodeWriter qrCodeWriter = new QRCodeWriter();
	final int width = 300;
	final int height = 300;

	try {
		final BitMatrix byteMatrix = qrCodeWriter.encode(address, BarcodeFormat.QR_CODE, width, height);
		final BufferedImage qrCodeImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
		qrCodeImage.createGraphics();

		final Graphics2D graphics = (Graphics2D) qrCodeImage.getGraphics();
		graphics.setColor(Color.WHITE);
		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 Optional.of(SwingFXUtils.toFXImage(qrCodeImage, null));
	} catch (WriterException e) {
		logger.error("Failed to encode local bluetooth address as a qr code", e);
		return Optional.empty();
	}
}
 
Example 10
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 11
Source File: ShadowSocksSerivceImpl.java    From ShadowSocks-Share with Apache License 2.0 5 votes vote down vote up
/**
 * 生成二维码
 */
@Override
public byte[] createQRCodeImage(String text, int width, int height) throws WriterException, IOException {
	QRCodeWriter qrCodeWriter = new QRCodeWriter();
	BitMatrix bitMatrix = qrCodeWriter.encode(text, BarcodeFormat.QR_CODE, width, height);

	ByteArrayOutputStream pngOutputStream = new ByteArrayOutputStream();
	MatrixToImageWriter.writeToStream(bitMatrix, "PNG", pngOutputStream);
	byte[] pngData = pngOutputStream.toByteArray();
	return pngData;
}
 
Example 12
Source File: CreateScan.java    From Android with MIT License 5 votes vote down vote up
public Bitmap generateQRCode(String content,int colorBg) {
    try {
        QRCodeWriter writer = new QRCodeWriter();
        Hashtable hints = new Hashtable();
        hints.put(EncodeHintType.CHARACTER_SET, "utf-8"); //coding
        //hints.put(EncodeHintType.ERROR_CORRECTION, level); //Fault tolerance
        hints.put(EncodeHintType.MARGIN, 0);  //Two dimensional code frame width, where the document says 0-4
        BitMatrix matrix = writer.encode(content, BarcodeFormat.QR_CODE, widthDef, heightDef,hints);
        return bitMatrix2Bitmap(matrix,colorBg);
    } catch (WriterException e) {
        e.printStackTrace();
    }
    return null;
}
 
Example 13
Source File: TransferEntriesActivity.java    From Aegis with GNU General Public License v3.0 5 votes vote down vote up
private void generateQR() {
    GoogleAuthInfo selectedEntry = _authInfos.get(_currentEntryCount - 1);
    _issuer.setText(selectedEntry.getIssuer());
    _accountName.setText(selectedEntry.getAccountName());
    _entriesCount.setText(String.format(getString(R.string.entries_count), _currentEntryCount, _authInfos.size()));

    QRCodeWriter writer = new QRCodeWriter();
    BitMatrix bitMatrix = null;
    try {
        bitMatrix = writer.encode(selectedEntry.getUri().toString(), BarcodeFormat.QR_CODE, 512, 512);
    } catch (WriterException e) {
        Dialogs.showErrorDialog(this, R.string.unable_to_generate_qrcode, e);
        return;
    }

    int width = bitMatrix.getWidth();
    int height = bitMatrix.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] = bitMatrix.get(x, y) ? Color.BLACK : Color.WHITE;
        }
    }

    Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
    bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
    _qrImage.setImageBitmap(bitmap);
}
 
Example 14
Source File: GenerateQRCode.java    From journaldev with MIT License 5 votes vote down vote up
private static void createQRImage(File qrFile, String qrCodeText, int size, String fileType)
		throws WriterException, IOException {
	// Create the ByteMatrix for the QR-Code that encodes the given String
	Hashtable<EncodeHintType, ErrorCorrectionLevel> hintMap = new Hashtable<>();
	hintMap.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);
	QRCodeWriter qrCodeWriter = new QRCodeWriter();
	BitMatrix byteMatrix = qrCodeWriter.encode(qrCodeText, BarcodeFormat.QR_CODE, size, size, hintMap);
	// Make the BufferedImage that are to hold the QRCode
	int matrixWidth = byteMatrix.getWidth();
	BufferedImage image = new BufferedImage(matrixWidth, matrixWidth, BufferedImage.TYPE_INT_RGB);
	image.createGraphics();

	Graphics2D graphics = (Graphics2D) image.getGraphics();
	graphics.setColor(Color.WHITE);
	graphics.fillRect(0, 0, matrixWidth, matrixWidth);
	// Paint and save the image using the ByteMatrix
	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, j, 1, 1);
			}
		}
	}
	ImageIO.write(image, fileType, qrFile);
}
 
Example 15
Source File: BookLibraryRestController.java    From personal_book_library_web_project with MIT License 5 votes vote down vote up
@RequestMapping(value = "/otp/qrcode/{userid}.png", method = RequestMethod.GET)
  public void generateQRCode(HttpServletResponse response, @PathVariable("userid") Long userId) throws WriterException, IOException {
      
String otpProtocol = userService.generateOTPProtocol(userId);
      response.setContentType("image/png");
      
      QRCodeWriter writer = new QRCodeWriter();
      BitMatrix matrix = writer.encode(otpProtocol, BarcodeFormat.QR_CODE, 250, 250);
      MatrixToImageWriter.writeToStream(matrix, "PNG", response.getOutputStream());
      response.getOutputStream().flush();
  }
 
Example 16
Source File: QrCodeUtility.java    From ethereum-paper-wallet with Apache License 2.0 5 votes vote down vote up
public static byte[] contentToPngBytes(String content, int size) {
	try {
		Map<EncodeHintType, Object> hintMap = new EnumMap<EncodeHintType, Object>(EncodeHintType.class);
		hintMap.put(EncodeHintType.MARGIN, 0);
		hintMap.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);
		hintMap.put(EncodeHintType.CHARACTER_SET, ENCODING_TYPE);

		QRCodeWriter qrWriter = new QRCodeWriter();
		BitMatrix qrMatrix = qrWriter.encode(content, BarcodeFormat.QR_CODE, size, size, hintMap);
		int width = qrMatrix.getWidth();
		BufferedImage image = new BufferedImage(width, width,
				BufferedImage.TYPE_INT_RGB);
		image.createGraphics();

		Graphics2D graphics = (Graphics2D) image.getGraphics();
		graphics.setColor(Color.WHITE);
		graphics.fillRect(0, 0, width, width);
		graphics.setColor(Color.BLACK);

		for (int i = 0; i < width; i++) {
			for (int j = 0; j < width; j++) {
				if (qrMatrix.get(i, j)) {
					graphics.fillRect(i, j, 1, 1);
				}
			}
		}

		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		ImageIO.write(image, IMAGE_FILE_TYPE, bos);

		return bos.toByteArray();
	}
	catch (Exception e) {
		throw new RuntimeException("Failed to produce image byte array", e);
	}
}
 
Example 17
Source File: GroupDetailActivity.java    From Rumble with GNU General Public License v3.0 5 votes vote down vote up
public void invite() {
    String buffer = group.getGroupBase64ID();
    int size = 200;
    Hashtable<EncodeHintType, ErrorCorrectionLevel> hintMap = new Hashtable<EncodeHintType, ErrorCorrectionLevel>();
    hintMap.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);
    QRCodeWriter qrCodeWriter = new QRCodeWriter();
    try {
        BitMatrix bitMatrix = qrCodeWriter.encode(buffer, BarcodeFormat.QR_CODE, size, size, hintMap);
        Bitmap image = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);

        if(image != null) {
            for (int i = 0; i < size; i++) {
                for (int j = 0; j < size; j++) {
                    image.setPixel(i, j, bitMatrix.get(i, j) ? Color.BLACK : Color.WHITE);
                }
            }
            Intent intent = new Intent(this, DisplayQRCode.class);
            intent.putExtra("EXTRA_GROUP_NAME", groupName);
            intent.putExtra("EXTRA_BUFFER", buffer);
            intent.putExtra("EXTRA_QRCODE", image);
            startActivity(intent);
            overridePendingTransition(R.anim.activity_open_enter, R.anim.activity_open_exit);
        }
    }catch(WriterException ignore) {
    }
    //}
}
 
Example 18
Source File: ZxingBarcodeGenerator.java    From tutorials with MIT License 4 votes vote down vote up
public static BufferedImage generateQRCodeImage(String barcodeText) throws Exception {
    QRCodeWriter barcodeWriter = new QRCodeWriter();
    BitMatrix bitMatrix = barcodeWriter.encode(barcodeText, BarcodeFormat.QR_CODE, 200, 200);

    return MatrixToImageWriter.toBufferedImage(bitMatrix);
}
 
Example 19
Source File: MyQRCodeUtils.java    From spring-boot with Apache License 2.0 3 votes vote down vote up
/**
 * 创建 QRCode 图片文件
 *
 * @param file            图片
 * @param imageFormat     图片编码格式
 * @param encodeContent   QRCode 内容
 * @param imageSize       图片大小
 * @param foreGroundColor 前景色
 * @param backGroundColor 背景色
 * @throws WriterException
 * @throws IOException
 */
public static void createQRCodeImageFile(Path file, ImageFormat imageFormat, String encodeContent, Dimension imageSize, Color foreGroundColor, Color backGroundColor) throws WriterException, IOException {
    Assert.isTrue(FilenameUtils.getExtension(file.toString()).toUpperCase().equals(imageFormat.toString()), "文件扩展名和格式不一致");
    QRCodeWriter qrWrite = new QRCodeWriter();
    BitMatrix matrix = qrWrite.encode(encodeContent, BarcodeFormat.QR_CODE, imageSize.width, imageSize.height);
    MatrixToImageWriter.writeToPath(matrix, imageFormat.toString(), file, new MatrixToImageConfig(foreGroundColor.getRGB(), backGroundColor.getRGB()));
}
 
Example 20
Source File: MyQRCodeUtils.java    From spring-boot with Apache License 2.0 3 votes vote down vote up
/**
 * 创建 QRCode 图片文件输出流,用于在线生成动态图片
 *
 * @param stream
 * @param imageFormat
 * @param encodeContent
 * @param imageSize
 * @param foreGroundColor
 * @param backGroundColor
 * @throws WriterException
 * @throws IOException
 */
public static void createQRCodeImageStream(OutputStream stream, ImageFormat imageFormat, String encodeContent, Dimension imageSize, Color foreGroundColor, Color backGroundColor) throws WriterException, IOException {

    QRCodeWriter qrWrite = new QRCodeWriter();
    BitMatrix matrix = qrWrite.encode(encodeContent, BarcodeFormat.QR_CODE, imageSize.width, imageSize.height);
    MatrixToImageWriter.writeToStream(matrix, imageFormat.toString(), stream, new MatrixToImageConfig(foreGroundColor.getRGB(), backGroundColor.getRGB()));
}