Java Code Examples for com.google.zxing.client.j2se.MatrixToImageWriter#writeToStream()

The following examples show how to use com.google.zxing.client.j2se.MatrixToImageWriter#writeToStream() . 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: 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 3
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 4
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 5
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 6
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 7
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 8
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 9
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 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: QrCodeUtil.java    From util4j with Apache License 2.0 5 votes vote down vote up
public static byte[] encode(int width, int height, String content, String format) throws Exception {
	Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>();
	hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
	BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height, hints);// 生成矩阵
	ByteArrayOutputStream bos = new ByteArrayOutputStream();
	MatrixToImageWriter.writeToStream(bitMatrix, format, bos);
	return bos.toByteArray();
}
 
Example 12
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 13
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 14
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 15
Source File: DeviceRegisterServiceImpl.java    From konker-platform with Apache License 2.0 4 votes vote down vote up
/**
 * Generate an encoded base64 String with qrcode image
 *
 * @param credentials
 * @param width
 * @param height
 * @return String
 * @throws Exception
 */
@Override
public ServiceResponse<String> generateQrCodeAccess(DeviceSecurityCredentials credentials, int width, int height, Locale locale) {
    try {

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        Base64OutputStream encoded = new Base64OutputStream(baos);
        StringBuilder content = new StringBuilder();
        content.append("{\"user\":\"").append(credentials.getDevice().getUsername());
        content.append("\",\"pass\":\"").append(credentials.getPassword());
        
        DeviceDataURLs deviceDataURLs = new DeviceDataURLs(credentials.getDevice(), locale);
       	content.append("\",\"host\":\"").append(deviceDataURLs.getHttpHostName());
        content.append("\",\"ctx\":\"").append(deviceDataURLs.getContext());
        content.append("\",\"host-mqtt\":\"").append(deviceDataURLs.getMqttHostName());
        
        content.append("\",\"http\":\"").append(deviceDataURLs.getHttpPort());
        content.append("\",\"https\":\"").append(deviceDataURLs.getHttpsPort());
        content.append("\",\"mqtt\":\"").append(deviceDataURLs.getMqttPort());
        content.append("\",\"mqtt-tls\":\"").append(deviceDataURLs.getMqttTlsPort());
        content.append("\",\"pub\":\"pub/").append(credentials.getDevice().getUsername());
        content.append("\",\"sub\":\"sub/").append(credentials.getDevice().getUsername()).append("\"}");

        Map<EncodeHintType, Serializable> map = new HashMap<>();
        for (AbstractMap.SimpleEntry<EncodeHintType, ? extends Serializable> item : Arrays.<AbstractMap.SimpleEntry<EncodeHintType, ? extends Serializable>>asList(
                new AbstractMap.SimpleEntry<>(EncodeHintType.MARGIN, 0),
                new AbstractMap.SimpleEntry<>(EncodeHintType.CHARACTER_SET, "UTF-8")
        )) {
            if (map.put(item.getKey(), item.getValue()) != null) {
                throw new IllegalStateException("Duplicate key");
            }
        }
        BitMatrix bitMatrix = new QRCodeWriter().encode(
                content.toString(),
                BarcodeFormat.QR_CODE, width, height,
                Collections.unmodifiableMap(map));
        MatrixToImageWriter.writeToStream(bitMatrix, "png", encoded);
        String result = "data:image/png;base64," + new String(baos.toByteArray(), 0, baos.size(), "UTF-8");
        return ServiceResponseBuilder.<String>ok().withResult(result).build();
    } catch (Exception e) {
        return ServiceResponseBuilder.<String>error()
                .withMessage(Messages.DEVICE_QRCODE_ERROR.getCode())
                .build();
    }
}
 
Example 16
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()));
}
 
Example 17
Source File: QRCodeUtils.java    From google-authenticator-integration with MIT License 2 votes vote down vote up
/**
 * 将二维码图片输出到一个流中
 *
 * @param content 二维码内容
 * @param stream 输出流
 * @param width 宽
 * @param height 高
 */
public static void writeToStream(String content, OutputStream stream, int width, int height)
		throws WriterException, IOException {
	BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height, HINTS);
	MatrixToImageWriter.writeToStream(bitMatrix, FILE_FORMAT, stream);
}
 
Example 18
Source File: QRCodeUtils.java    From google-authenticator-integration with MIT License 2 votes vote down vote up
/**
 * 将二维码图片输出到一个流中
 *
 * @param content 二维码内容
 * @param stream 输出流
 */
public static void writeToStream(String content, OutputStream stream) throws WriterException, IOException {
	BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, WIDTH, HEIGHT, HINTS);
	MatrixToImageWriter.writeToStream(bitMatrix, FILE_FORMAT, stream);
}
 
Example 19
Source File: QRCodeUtils.java    From qrcodecore with GNU General Public License v2.0 2 votes vote down vote up
/**
 * 转成字符输出流
 * @param bitMatrix bitMatrix
 * @param format 图片格式
 * @return
 * @throws IOException
 */
private static ByteArrayOutputStream writeToStream(BitMatrix bitMatrix, String format) throws IOException {
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    MatrixToImageWriter.writeToStream(bitMatrix, format, outputStream);
    return outputStream;
}
 
Example 20
Source File: QRCodeUtil.java    From jframework with Apache License 2.0 2 votes vote down vote up
/**
 * 将二维码图片输出到一个流中
 *
 * @param content 二维码内容
 * @param stream  输出流
 * @param width   宽
 * @param height  高
 */
public static void writeToStream(String content, OutputStream stream, int width, int height) throws WriterException, IOException {
    BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height, hints);
    MatrixToImageWriter.writeToStream(bitMatrix, FORMAT, stream);
}