导入依赖:
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>3.4.1</version>
</dependency>
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>javase</artifactId>
<version>3.3.3</version>
</dependency>
controller:(根据rgb生成彩色的二维码)
@GetMapping("color-qr/{content}")
public void createQrCode2(@PathVariable("content") String content, HttpServletResponse response) throws WriterException, IOException {
int width = 400, height = 400;
Map<EncodeHintType, Object> hints = new HashMap<>();
hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
BitMatrix matrix = new QRCodeWriter().encode(content, BarcodeFormat.QR_CODE, width, height, hints);
int[] pixels = new int[width * height];
for (int y = 0; y < matrix.getHeight(); y++) {
for (int x = 0; x < matrix.getWidth(); x++) {
// 二维码颜色(RGB)
int num1 = (int) (50 - (50.0 - 13.0) / matrix.getHeight()
* (y + 1));
int num2 = (int) (165 - (165.0 - 72.0) / matrix.getHeight()
* (y + 1));
int num3 = (int) (162 - (162.0 - 107.0)
/ matrix.getHeight() * (y + 1));
Color color = new Color(num1, num2, num3);
int colorInt = color.getRGB();
pixels[y * width + x] = matrix.get(x, y) ? colorInt : 16777215;
}
}
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
image.getRaster().setDataElements(0, 0, width, height, pixels);
ImageIO.write(image, "png", response.getOutputStream());
}
生成黑白二维码:
@GetMapping("/test/{content}")
public void qRode(@PathVariable("content") String content, HttpServletRequest request, HttpServletResponse response) throws IOException, WriterException {
Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>();
// 指定编码格式
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
// 指定纠错级别(L--7%,M--15%,Q--25%,H--30%)
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
// 编码内容,编码类型(这里指定为二维码),生成图片宽度,生成图片高度,设置参数
BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, 500, 500, hints);
// 二维码名称
String fileName = "123.png";
String userAgent = request.getHeader("Goods-Agent");
if (userAgent.contains("MSIE") || userAgent.contains("Trident") || userAgent.contains("Edge")) {//IE
fileName = java.net.URLEncoder.encode(fileName, "UTF-8");
} else {
fileName = new String(fileName.getBytes("UTF-8"), "ISO8859-1");// 谷歌/火狐
}
//设置请求头
response.setHeader("Content-Type", "application/octet-stream");
response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
OutputStream outputStream = response.getOutputStream();
MatrixToImageWriter.writeToStream(bitMatrix, "png", outputStream);
outputStream.flush();
outputStream.close();
}
将代码复制到项目中运行就可以直接访问啦!(侵删)