java 生成二维码
maven例子
<!--导入Zxing的依赖-->
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>3.3.0</version>
</dependency>
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>javase</artifactId>
<version>3.3.0</version>
</dependency>
代码如下:
private static final String SAVE_ROAD_STRENGTH = "图片存放地址";
/**
* 将二维码进行保存
* @param text 存放内容
* @param width 图片宽度
* @param height 图片高度
* @param filePath 图片存放路径
*
* @throws WriterException
* @throws IOException
*/
private static void generateQRCodeImage(String text, int width, int height, String filePath) throws WriterException, IOException {
QRCodeWriter qrCodeWriter = new QRCodeWriter();
BitMatrix bitMatrix = qrCodeWriter.encode(text, BarcodeFormat.QR_CODE, width, height);
//图片保存
Path path = FileSystems.getDefault().getPath(filePath);
MatrixToImageWriter.writeToPath(bitMatrix, "PNG", path);
}
/**
*
* @param text 存放内容
* @param width 图片宽度
* @param height 图片高度
* @return base64
* @throws WriterException
* @throws IOException
*/
private static String generateBase64(String text, int width, int height) throws WriterException, IOException {
QRCodeWriter qrCodeWriter = new QRCodeWriter();
BitMatrix bitMatrix = qrCodeWriter.encode(text, BarcodeFormat.QR_CODE, width, height);
//将图片转为base64
BufferedImage image = toBufferedImage(bitMatrix);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
//输出二维码图片流
ImageIO.write(image, "png",outputStream);
String encode = Base64.encode(outputStream.toByteArray());
encode = "data:image/gif;base64," + encode;
log.debug(encode);
return encode;
}
public static void main(String[] args) throws WriterException, IOException {
//扫描图片进入百度(内容也可存放文本)
String s = generateBase64("https://www.baidu.com", 350, 350);
System.out.println(s);
}
结果展示
data:image/gif;base64,iVBORw0KGgoAAAANSUhEUgAAAV4AAAFeAQAAAADlUEq3AAABXUlEQVR42u3ayQ2EMAxAUUsUQEm0PiWlACQPxEsQYpajI/0cRiyPk8fBcRD9f+wCBoPBYDAYXBC/xIe+VlWRdT+P9ri6gsvjcdokrz3cBZfFZ2jt7hlpWVQ2O/K/AHge3PN30XgMPBtuGekVPBMep56wf83P4DL4Uvbsl5+fNRK4CB6jk60tGeRv6xRwGdzrHJ9yj/CeU+71HbqCq2Pt8e3Fjh2JxdzydVNweZzzbo+0uXvqggtjq08lIu0NHD1K2Pb8hgUXw9qcRKS/NXDABXEPt60bm6/8j+G5ep9ywSXxYjH3Nri9NEUif8HlsU2v+arMYnZrzw0ccEUskbWRsDkNK7g6vi3/c7b1bgC4PB4tOG+DR9njT4DL48d9jcxk8AQ4em6XFWRUPOC5cO7q513wVPi+m/G49AAXxHF6Dbd/4gaeAY/tYKt9oqeqH9rg4GKY75/BYDAYDAZPiN+hP4o7H6LMIgAAAABJRU5ErkJggg==