下面列出了com.google.zxing.client.j2se.MatrixToImageWriter#writeToStream ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
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);
}
}
/**
* 将内容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();
}
}
}
@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();
}
}
@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());
}
}
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);
}
}
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);
}
}
@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);
}
}
/**
* 生成二维码
*/
@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;
}
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();
}
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();
}
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;
}
}
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);
}
}
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);
}
}
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");
}
/**
* 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();
}
}
/**
* 创建 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()));
}
/**
* 将二维码图片输出到一个流中
*
* @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);
}
/**
* 转成字符输出流
* @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;
}
/**
* 将二维码图片输出到一个流中
*
* @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);
}
/**
* 将二维码图片输出到一个流中
*
* @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);
}