zxing生成高容錯率二維碼,以及添加文字


知識點:

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();
    }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM