java实现生成二维码(包括文字,地址,图片)
环境:SpringBoot+Thymeleaf
需要添加的依赖:
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>javase</artifactId>
<version>3.2.1</version>
</dependency>
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>3.2.1</version>
</dependency>
一、文字:
1.生成图片保存:
public class QrCodeController {
//二维码存放地址
private static final String QR_CODE_IMAGE_PATH="C:/Users/WangJinguo/Desktop/MyQRCode.png";
//生成二维码的方法
private static void generateQRCodeImage(String text,int width,int height,String filepath) throws WriterException, IOException {
//转码,防止乱码
text = new String(text.getBytes("utf-8"),"iso-8859-1");
QRCodeWriter qrCodeWriter = new QRCodeWriter();
BitMatrix bitMatrix = qrCodeWriter.encode(text, QR_CODE,width,height);
Path path = FileSystems.getDefault().getPath(filepath);
MatrixToImageWriter.writeToPath(bitMatrix,"PNG",path);
}
public static void main(String[] args){
try {
generateQRCodeImage("中国共产党万岁",350,350,QR_CODE_IMAGE_PATH);
} catch (WriterException e) {
System.out.println("二维码生成失败");
} catch (IOException e) {
System.out.println("二维码生成失败");
}
}
2.展示在页面:
页面代码:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>二维码测试</title>
</head>
<body>
<div>
<!--/code/qrimage 后台请求地址-->
<img th:src="@{'/code/qrimage'}" alt="二维码加载失败">
</div>
</body>
</html>
后台controller:
@Controller
@RequestMapping("/code")
public class QrCodeController {
@GetMapping("/qr")
public String qrcode(){
return "qrcode";
}
@GetMapping("/qrimage")
public ResponseEntity<byte[]> getQRImage() throws UnsupportedEncodingException {
String info = new String("Qnmd".getBytes("UTF-8"),"ISO-8859-1");
byte[] qrcode = null;
try {
qrcode = QrCodeController.getQRCodeImage(info,360,360);
} catch (IOException e) {
e.printStackTrace();
} catch (WriterException e) {
e.printStackTrace();
}
final HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setContentType(MediaType.IMAGE_PNG);
return new ResponseEntity<byte[]>(qrcode,httpHeaders, HttpStatus.CREATED);
}
//转为二进制文件,传到前台
public static byte[] getQRCodeImage(String text, int width, int height) throws WriterException, IOException {
QRCodeWriter qrCodeWriter = new QRCodeWriter();
BitMatrix bitMatrix = qrCodeWriter.encode(text, BarcodeFormat.QR_CODE,width,height);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
MatrixToImageWriter.writeToStream(bitMatrix,"PNG",baos);
byte[] pngData = baos.toByteArray();
return pngData;
}
}
访问:http://localhost:8080/code/qr
二、.地址
地址生成二维码比较简单,只需把文字改成地址即可(该地址必须可查的,如果只是电脑本地的地址不可行,一般网页地址可行),最好用百度扫码,微信扫了几次发现一般打不开。
只需改一个地方:
String info = "https://www.baidu.com/";
三、图片:
这个找了许多没怎么发现我想要的(扫码出现图片),一开始链接到电脑的文件地址,发现打不开,后来想把图片转成字符串,发现提示文本太大,看见一个想法是把照片上传到服务器,再链接,我就试了这个想法,发现可行。
可将照片(静态资源)放在static目录下:
修改地址:
String info = ("http://192.168.43.132:8080/1.jpg");
注意:地址需要加协议,如百度不能直接写www.baidu.com
。