知识点:
1.使用zxing组件生成二维码
2.向二维码图片添加文本内容
3.设置二维码容错率(避免扫码识别率低)
public String saveQRCode(String id, String name, String content, String fileName, String formatName) { String imageUri = null; File file = null; try { StringBuffer buf = new StringBuffer(fileConfig.getStorageDir()); buf.append(File.separator).append("qrcode").append(fileName); imageUri = buf.toString(); file = new File(imageUri); if (!file.getParentFile().exists()) { file.getParentFile().mkdirs(); } //设置二维码容错级别:H Map<EncodeHintType,Object> hints = new HashMap<EncodeHintType, Object>(); hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H); BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, 640, 640, hints); // 临时文件路径(本地) writeToFile(bitMatrix, formatName, file, name); // // 上传到图片服务器(供外部访问) //// imageUri = FDFSClient.uploadFile(code, fileName, 0); // CommonsMultipartFile multipartFile = new CommonsMultipartFile( // new DiskFileItem(code, "", false, fileName, 0, null)); // imageUri = fileStorageService.uploadFile(multipartFile, "qrcode", dir); if (imageUri == null) { logger.warn("Fail to upload QR picture file to picture server. "); } } catch (Exception e) { e.printStackTrace(); logger.warn("Can not generate QR code picture. {}", e.getMessage()); } finally { // if (file != null) // file.delete(); } return imageUri; } private static void writeToFile(BitMatrix matrix, String format, File file, String text) throws IOException { BufferedImage image = toBufferedImage(matrix); if (text != null) { pressText(text, image); } ImageIO.write(image, format, file); } /** * 生成二维码内容<br> * * @param matrix * @return */ private static BufferedImage toBufferedImage(BitMatrix matrix) { int width = matrix.getWidth(); int height = matrix.getHeight(); BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) { image.setRGB(x, y, matrix.get(x, y) == true ? BLACK : WHITE); } } return image; } /** * 给二维码图片加上文字 */ public static void pressText(String pressText, BufferedImage image) throws IOException { pressText = new String(pressText.getBytes(), "utf-8"); Graphics g = image.createGraphics(); g.setColor(Color.BLACK); Font font = new Font("宋体", Font.PLAIN, 24); FontMetrics metrics = g.getFontMetrics(font); // 文字在图片中的坐标 这里设置在中间 int startX = (WIDTH - metrics.stringWidth(pressText)) / 2; int startY = HEIGHT - 40; g.setFont(font); g.drawString(pressText, startX, startY); g.dispose(); }