com.google.zxing.client.j2se.MatrixToImageWriter Java Examples

The following examples show how to use com.google.zxing.client.j2se.MatrixToImageWriter. 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: TotpUtils.java    From keycloak with Apache License 2.0 8 votes vote down vote up
public static String qrCode(String totpSecret, RealmModel realm, UserModel user) {
    try {
        String keyUri = realm.getOTPPolicy().getKeyURI(realm, user, totpSecret);

        int width = 246;
        int height = 246;

        QRCodeWriter writer = new QRCodeWriter();
        final BitMatrix bitMatrix = writer.encode(keyUri, BarcodeFormat.QR_CODE, width, height);

        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        MatrixToImageWriter.writeToStream(bitMatrix, "png", bos);
        bos.close();

        return Base64.encodeBytes(bos.toByteArray());
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example #2
Source File: QRCodeUtil.java    From hdw-dubbo with Apache License 2.0 7 votes vote down vote up
/**
 * @param dir     生成二维码路径
 * @param content 内容
 * @param width   宽度
 * @param height  高度
 * @return
 */
public static String createQRCodeImage(String dir, String content, int width, int height) {
    try {
        File dirFile = null;
        if (StringUtils.isNotBlank(dir)) {
            dirFile = new File(dir);
            if (!dirFile.exists()) {
                dirFile.mkdirs();
            }
        }
        String qrcodeFormat = "png";
        HashMap<EncodeHintType, String> hints = new HashMap<EncodeHintType, String>();
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
        BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height, hints);

        File file = new File(dir, UUID.randomUUID().toString() + "." + qrcodeFormat);
        MatrixToImageWriter.writeToPath(bitMatrix, qrcodeFormat, file.toPath());
        return file.getAbsolutePath();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return "";
}
 
Example #3
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 #4
Source File: PaymentUtils.java    From java-pay with Apache License 2.0 6 votes vote down vote up
/**
 * 生成二维码并响应到浏览器
 *
 * @param content
 * @param response
 */
public static void createQRCode(String content, HttpServletResponse response) {
    int width = 300, height = 300;
    String format = "png";
    Map<EncodeHintType, Object> hashMap = new HashMap<>();
    hashMap.put(EncodeHintType.CHARACTER_SET, StandardCharsets.UTF_8);
    hashMap.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
    hashMap.put(EncodeHintType.MARGIN, 1);
    try {
        response.setHeader("Cache-control", "no-cache");
        response.setHeader("Pragma", "no-cache");
        response.setHeader("content-type", "image/png");
        response.setCharacterEncoding(StandardCharsets.UTF_8.displayName());
        response.setDateHeader("Expires", 0);
        BitMatrix bitMatrix = new MultiFormatWriter()
                .encode(content, BarcodeFormat.QR_CODE, width, height, hashMap);
        BufferedImage img = MatrixToImageWriter.toBufferedImage(bitMatrix);
        ImageIO.write(img, format, response.getOutputStream());
    } catch (Exception e) {
        log.warn("create QRCode error message:{}", e.getMessage());
    }
}
 
Example #5
Source File: BarcodeTools.java    From MyBox with Apache License 2.0 6 votes vote down vote up
public static BufferedImage PDF417(String code, int pdf417ErrorCorrectionLevel,
        Compaction pdf417Compact,
        int pdf417Width, int pdf417Height, int pdf417Margin) {
    try {
        HashMap hints = new HashMap();
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
        hints.put(EncodeHintType.ERROR_CORRECTION, pdf417ErrorCorrectionLevel);
        hints.put(EncodeHintType.MARGIN, pdf417Margin);
        if (pdf417Compact == null) {
            hints.put(EncodeHintType.PDF417_COMPACT, false);
        } else {
            hints.put(EncodeHintType.PDF417_COMPACT, true);
            hints.put(EncodeHintType.PDF417_COMPACTION, pdf417Compact);
        }

        BitMatrix bitMatrix = new MultiFormatWriter().encode(code,
                BarcodeFormat.PDF_417, pdf417Width, pdf417Height, hints);

        return MatrixToImageWriter.toBufferedImage(bitMatrix);

    } catch (Exception e) {
        logger.error(e.toString());
        return null;
    }
}
 
Example #6
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 #7
Source File: BarcodeTools.java    From MyBox with Apache License 2.0 6 votes vote down vote up
public static BufferedImage DataMatrix(String code,
        int dmWidth, int dmHeigh) {
    try {
        HashMap hints = new HashMap();
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");

        BitMatrix bitMatrix = new MultiFormatWriter().encode(code,
                BarcodeFormat.DATA_MATRIX, dmWidth, dmHeigh, hints);

        return MatrixToImageWriter.toBufferedImage(bitMatrix);

    } catch (Exception e) {
        logger.error(e.toString());
        return null;
    }
}
 
Example #8
Source File: QRCodeUtils.java    From qrcodecore with GNU General Public License v2.0 6 votes vote down vote up
/**
 * 生成带有logo的二维码
 * @param text 生成文本
 * @param logoInputStream logo文件输入流
 * @param qrCodeWidth 二维码宽度
 * @param qrCodeHeight 二维码高度
 * @param logoWidth logo宽度
 * @param logoHeight logo高度
 * @param ENCODE_HINTS 二维码配置
 * @return 输出流
 * @throws WriterException
 * @throws IOException
 */
private static Thumbnails.Builder<BufferedImage> createWidthLogo(String text, InputStream logoInputStream, int qrCodeWidth, int qrCodeHeight, int logoWidth, int logoHeight,
                                            String format, Map<EncodeHintType, Object> ENCODE_HINTS) throws WriterException, IOException {
    BitMatrix bitMatrix = createBitMatrix(text, BarcodeFormat.QR_CODE, qrCodeWidth, qrCodeHeight, ENCODE_HINTS);
    /* 生成二维码的bufferedImage */
    BufferedImage qrcode = MatrixToImageWriter.toBufferedImage(bitMatrix);
    /* 创建图片构件对象 */
    Thumbnails.Builder<BufferedImage> builder = Thumbnails.of(new BufferedImage(qrCodeWidth, qrCodeHeight, BufferedImage.TYPE_INT_RGB));
    BufferedImage logo = ImageIO.read(logoInputStream);
    BufferedImage logoImage = Thumbnails.of(logo).size(logoWidth, logoHeight).asBufferedImage();
    /* 设置logo水印位置居中,不透明  */
    builder.watermark(Positions.CENTER, qrcode, 1F)
            .watermark(Positions.CENTER, logoImage, 1F)
            .scale(1F)
            .outputFormat(format);
    return builder;
}
 
Example #9
Source File: ZxingUtils.java    From wish-pay with Apache License 2.0 6 votes vote down vote up
/**
 * 二维码信息写成JPG BufferedImage
 *
 * @param content
 * @param width
 * @param height
 * @return
 */
public static BufferedImage writeInfoToJpgBuffImg(String content, int width, int height) {
    if (width < 250) {
        width = 250;
    }
    if (height < 250) {
        height = 250;
    }
    BufferedImage re = null;

    MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
    Map hints = new HashMap();
    hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
    try {
        BitMatrix bitMatrix = multiFormatWriter.encode(content,
                BarcodeFormat.QR_CODE, width, height, hints);
        re = MatrixToImageWriter.toBufferedImage(bitMatrix);
    } catch (Exception e) {
        e.printStackTrace();
    }

    return re;
}
 
Example #10
Source File: ZxingHandler.java    From Shop-for-JavaWeb with MIT License 6 votes vote down vote up
/**
 * 条形码编码
 * 
 * @param contents
 * @param width
 * @param height
 * @param imgPath
 */
public static void encode(String contents, int width, int height, String imgPath) {
	int codeWidth = 3 + // start guard
			(7 * 6) + // left bars
			5 + // middle guard
			(7 * 6) + // right bars
			3; // end guard
	codeWidth = Math.max(codeWidth, width);
	try {
		BitMatrix bitMatrix = new MultiFormatWriter().encode(contents,
				BarcodeFormat.EAN_13, codeWidth, height, null);

		MatrixToImageWriter
				.writeToFile(bitMatrix, "png", new File(imgPath));

	} catch (Exception e) {
		e.printStackTrace();
	}
}
 
Example #11
Source File: ZxingHandler.java    From Shop-for-JavaWeb with MIT License 6 votes vote down vote up
/**
 * 二维码编码
 * 
 * @param contents
 * @param width
 * @param height
 * @param imgPath
 */
public static void encode2(String contents, int width, int height, String imgPath) {
	Hashtable<EncodeHintType, Object> hints = new Hashtable<EncodeHintType, Object>();
	// 指定纠错等级
	hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);
	// 指定编码格式
	hints.put(EncodeHintType.CHARACTER_SET, "GBK");
	try {
		BitMatrix bitMatrix = new MultiFormatWriter().encode(contents,
				BarcodeFormat.QR_CODE, width, height, hints);

		MatrixToImageWriter
				.writeToFile(bitMatrix, "png", new File(imgPath));

	} catch (Exception e) {
		e.printStackTrace();
	}
}
 
Example #12
Source File: ProductController.java    From moserp with Apache License 2.0 6 votes vote down vote up
@ResponseBody
@RequestMapping(method = RequestMethod.GET, value = "/{productId}/ean")
public ResponseEntity<?> getProductEAN(@PathVariable String productId) throws WriterException, IOException {
    Product product = repository.findOne(productId);
    if (product == null) {
        return ResponseEntity.notFound().build();
    }
    EAN13Writer ean13Writer = new EAN13Writer();
    BitMatrix matrix = ean13Writer.encode(product.getEan(), BarcodeFormat.EAN_13, 300, 200);
    BufferedImage bufferedImage = MatrixToImageWriter.toBufferedImage(matrix);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ImageIO.write(bufferedImage, "png", baos);
    byte[] imageData = baos.toByteArray();
    ByteArrayResource byteArrayResource = new ByteArrayResource(imageData);
    return ResponseEntity.ok().contentType(MediaType.IMAGE_PNG).body(byteArrayResource);
}
 
Example #13
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 #14
Source File: QRCodeController.java    From micro-service with MIT License 6 votes vote down vote up
@SuppressWarnings({ "rawtypes", "unchecked" })
@RequestMapping(value = "/generate", method = RequestMethod.GET)
   @ApiOperation(value="获取二维码图片")
   @ApiResponses(value = { @ApiResponse(code = 401, message = "请求未通过认证") })
   public void generateQRCode(@RequestParam(value = "content") String content, HttpServletResponse response) {
	
	logger.info("generate QRCode...");
	
	try {
		Map hints = new HashMap();
		hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
		BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, QRCODE_WIDTH_DEFAULT, QRCODE_HEIGHT_DEFAULT, hints);
		
		response.setContentType(CONTENT_TYPE_JPG);
		OutputStream stream = response.getOutputStream();
		MatrixToImageWriter.writeToStream(bitMatrix, QRCODE_FORMATE_DEFAULT, stream);
		
		stream.flush();
		stream.close();
	} catch (Exception e) {
		logger.error("generate QRCode error, {}", e.getMessage());
	}
   }
 
Example #15
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 #16
Source File: QRCodeWriter.java    From oath with MIT License 6 votes vote down vote up
private void doWrite(OutputStream os, Path path) throws IOException {
    try {
        Writer writer = new MultiFormatWriter();
        Map<EncodeHintType, Object> hints = new Hashtable<EncodeHintType, Object>();
        hints.put(EncodeHintType.CHARACTER_SET, StandardCharsets.UTF_8.name());
        hints.put(EncodeHintType.MARGIN, Integer.valueOf(margin));
        hints.put(EncodeHintType.ERROR_CORRECTION, com.google.zxing.qrcode.decoder.ErrorCorrectionLevel.forBits(errorCorrectionLevel.getBits()));
        BitMatrix matrix = writer.encode(uri.toUriString(), BarcodeFormat.QR_CODE, width, height, hints);
        if (os != null) {
            MatrixToImageWriter.writeToStream(matrix, imageFormatName, os);
        }
        else {
            MatrixToImageWriter.writeToPath(matrix, imageFormatName, path);
        }
    } catch (WriterException e) {
        throw new IOException(e);
    }
}
 
Example #17
Source File: PrintItemBarcode.java    From nordpos with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void draw(Graphics2D g, int x, int y, int width) {
    Graphics2D g2d = (Graphics2D) g;
    AffineTransform oldt = g2d.getTransform();
    g2d.translate(x - 10 + (width - (int) (m_iWidth * scale)) / 2, y + 10);
    g2d.scale(scale, scale);

    try {
        if (m_qrMatrix != null) {
            com.google.zxing.Writer writer = new QRCodeWriter();
            m_qrMatrix = writer.encode(m_sCode, com.google.zxing.BarcodeFormat.QR_CODE, m_iWidth, m_iHeight);
            g2d.drawImage(MatrixToImageWriter.toBufferedImage(m_qrMatrix), null, 0, 0);
        } else if (m_barcode != null) {
            m_barcode.generateBarcode(new Java2DCanvasProvider(g2d, 0), m_sCode);
        }
    } catch (IllegalArgumentException | WriterException ex) {
        g2d.drawRect(0, 0, m_iWidth, m_iHeight);
        g2d.drawLine(0, 0, m_iWidth, m_iHeight);
        g2d.drawLine(m_iWidth, 0, 0, m_iHeight);
    }

    g2d.setTransform(oldt);
}
 
Example #18
Source File: ImageUtil.java    From alf.io with GNU General Public License v3.0 6 votes vote down vote up
public static byte[] createQRCodeWithDescription(String text, String description) {
    try (InputStream fi = new ClassPathResource("/alfio/font/DejaVuSansMono.ttf").getInputStream();
         ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
        BitMatrix matrix = drawQRCode(text);
        BufferedImage bufferedImage = MatrixToImageWriter.toBufferedImage(matrix);
        BufferedImage scaled = new BufferedImage(200, 230, BufferedImage.TYPE_INT_ARGB);
        Graphics2D graphics = (Graphics2D)scaled.getGraphics();
        graphics.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
        graphics.drawImage(bufferedImage, 0,0, null);
        graphics.setColor(Color.WHITE);
        graphics.fillRect(0, 200, 200, 30);
        graphics.setColor(Color.BLACK);
        graphics.setFont(Font.createFont(Font.TRUETYPE_FONT, fi).deriveFont(14f));
        graphics.drawString(center(truncate(description, 23), 25), 0, 215);
        ImageIO.write(scaled, "png", baos);
        return baos.toByteArray();
    } catch (WriterException | IOException | FontFormatException e) {
        throw new IllegalStateException(e);
    }
}
 
Example #19
Source File: GoogleAuthenticatorDemo.java    From twofactorauth with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public static void createQRCode(String barCodeData, String filePath, int height, int width)
            throws WriterException, IOException {
    BitMatrix matrix = new MultiFormatWriter().encode(barCodeData, BarcodeFormat.QR_CODE,
            width, height);
    try (FileOutputStream out = new FileOutputStream(filePath)) {
        MatrixToImageWriter.writeToStream(matrix, "png", out);
    }
}
 
Example #20
Source File: ZxingUtils.java    From frpMgr with MIT License 5 votes vote down vote up
/**
 * 二维码编码
 * 
 * @param contents
 * @param width
 * @param height
 * @param imgPath
 */
public static void encode2(String contents, int width, int height, String imgPath) {
	Hashtable<EncodeHintType, Object> hints = new Hashtable<EncodeHintType, Object>();
	// 指定纠错等级
	hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);
	// 指定编码格式
	hints.put(EncodeHintType.CHARACTER_SET, "GBK");
	try {
		BitMatrix bitMatrix = new MultiFormatWriter().encode(contents, BarcodeFormat.QR_CODE, width, height, hints);
		MatrixToImageWriter.writeToPath(bitMatrix, "png", new File(imgPath).toPath());
	} catch (Exception e) {
		e.printStackTrace();
	}
}
 
Example #21
Source File: QrCodeUtil.java    From common_gui_tools with Apache License 2.0 5 votes vote down vote up
public static void genQrCodeFile(String content, String filePath, String format, int width, int height) throws WriterException, IOException {
    MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
    Map hints = new HashMap();
    hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
    hints.put(EncodeHintType.MARGIN, 2);
    BitMatrix bitMatrix = multiFormatWriter.encode(content, BarcodeFormat.QR_CODE, width, height, hints);
    File file = new File(filePath);
    MatrixToImageWriter.writeToFile(bitMatrix, format, file);
}
 
Example #22
Source File: QrCodeUtil.java    From common_gui_tools with Apache License 2.0 5 votes vote down vote up
public static String genQrCodeBase64String(String content, String format, int width, int height) throws WriterException, IOException {
    MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
    Map hints = new HashMap();
    hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
    hints.put(EncodeHintType.MARGIN, 2);
    BitMatrix bitMatrix = multiFormatWriter.encode(content, BarcodeFormat.QR_CODE, width, height, hints);
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    MatrixToImageWriter.writeToStream(bitMatrix, format, bos);
    return new String(Base64.encodeBase64(bos.toByteArray()), "utf-8");
}
 
Example #23
Source File: ImageUtil.java    From alf.io with GNU General Public License v3.0 5 votes vote down vote up
public static byte[] createQRCode(String text) {
    try {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        BitMatrix matrix = drawQRCode(text);
        MatrixToImageWriter.writeToStream(matrix, "png", baos);
        return baos.toByteArray();
    } catch (WriterException | IOException e) {
        throw new IllegalStateException(e);
    }
}
 
Example #24
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 #25
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 #26
Source File: QRCode.java    From graviteeio-access-management with Apache License 2.0 5 votes vote down vote up
public static String generate(String data, int height, int width) throws Exception {
    BitMatrix matrix = new MultiFormatWriter().encode(data, BarcodeFormat.QR_CODE, width, height);
    try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {
        MatrixToImageWriter.writeToStream(matrix, "png", out);
        Base64.Encoder encoder = Base64.getEncoder();
        String base64Image = encoder.encodeToString(out.toByteArray());
        return "data:image/png;base64," + base64Image;
    }
}
 
Example #27
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 #28
Source File: ZxingPngQrGenerator.java    From java-totp with MIT License 5 votes vote down vote up
@Override
public byte[] generate(QrData data) throws QrGenerationException {
    try {
        BitMatrix bitMatrix = writer.encode(data.getUri(), BarcodeFormat.QR_CODE, imageSize, imageSize);
        ByteArrayOutputStream pngOutputStream = new ByteArrayOutputStream();
        MatrixToImageWriter.writeToStream(bitMatrix, "PNG", pngOutputStream);

        return pngOutputStream.toByteArray();
    } catch (Exception e) {
        throw new QrGenerationException("Failed to generate QR code. See nested exception.", e);
    }
}
 
Example #29
Source File: ZxingUtils.java    From frpMgr with MIT License 5 votes vote down vote up
/**
 * 条形码编码
 * 
 * @param contents
 * @param width
 * @param height
 * @param imgPath
 */
public static void encode(String contents, int width, int height, String imgPath) {
	int codeWidth = 3 + // start guard
			(7 * 6) + // left bars
			5 + // middle guard
			(7 * 6) + // right bars
			3; // end guard
	codeWidth = Math.max(codeWidth, width);
	try {
		BitMatrix bitMatrix = new MultiFormatWriter().encode(contents, BarcodeFormat.EAN_13, codeWidth, height, null);
		MatrixToImageWriter.writeToPath(bitMatrix, "png", new File(imgPath).toPath());
	} catch (Exception e) {
		e.printStackTrace();
	}
}
 
Example #30
Source File: ZxingUtil.java    From DWSurvey with GNU Affero General Public License v3.0 5 votes vote down vote up
public static BufferedImage qRCodeCommon(String content, String imgType, int size){
    int imgSize = 67 + 12 * (size - 1);
    Hashtable hints = new Hashtable();
    hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
    hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
    hints.put(EncodeHintType.MARGIN, 2);
    try{
        BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, imgSize, imgSize, hints);
        return MatrixToImageWriter.toBufferedImage(bitMatrix);
    }catch (WriterException e){
        e.printStackTrace();
    }
    return null;
}