@Override
public Response QrcCodeDetail(String baseUrl, Long id, HttpServletResponse response, HttpServletRequest request) {
response.setContentType("image/jpg");
response.setHeader("Pragma", "no-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
OutputStream stream = null;
try {
int onColor = 0xFF006600;
int offColor = 0xFFFFFFFF; ==》设置颜色
stream = response.getOutputStream();
String baseUrls = "http://www.baidu.com ===》这里替换掉需要的访问的地址
BitMatrix bitMatrix = QRCodeUtils.createCode(baseUrls);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
//以流的形式输出到前端
MatrixToImageConfig config = new MatrixToImageConfig(onColor, offColor);
MatrixToImageWriter.writeToStream(bitMatrix, "jpg", stream, config);
} catch (IOException e) {
throw new RuntimeException(e);
}
return Response.buildSuccess();
}
===生成二维码===
public static BitMatrix createCode(String content) throws IOException {
//二维码的宽高
int width = 300;
int height = 300;
//其他参数,如字符集编码
Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>();
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
//容错级别为H
hints.put(EncodeHintType.ERROR_CORRECTION , ErrorCorrectionLevel.H);
//白边的宽度,可取0~4
hints.put(EncodeHintType.MARGIN , 0);
BitMatrix bitMatrix = null;
try {
//生成矩阵,因为我的业务场景传来的是编码之后的URL,所以先解码
bitMatrix = new MultiFormatWriter().encode(content,
BarcodeFormat.QR_CODE, width, height, hints);
//bitMatrix = deleteWhite(bitMatrix);
} catch (WriterException e) {
e.printStackTrace();
}
return bitMatrix;
}
/**
* 删除生成的二维码周围的白边,根据审美决定是否删除
* @param matrix BitMatrix对象
* @return BitMatrix对象
* */
private static BitMatrix deleteWhite(BitMatrix matrix) {
int[] rec = matrix.getEnclosingRectangle();
int resWidth = rec[2] + 1;
int resHeight = rec[3] + 1;
BitMatrix resMatrix = new BitMatrix(resWidth, resHeight);
resMatrix.clear();
for (int i = 0; i < resWidth; i++) {
for (int j = 0; j < resHeight; j++) {
if (matrix.get(i + rec[0], j + rec[1]))
resMatrix.set(i, j);
}
}
return resMatrix;
}