Java二维码工具类

牧云@^-^@ 提交于 2019-12-14 05:56:46
/**
 * @Description: 二维码工具类
 */
public class Zxing {
    /**
     * @Param: content 二维码内容
     * @Param path
     * @return: void
     * @Description: 生成二维码
     */
       public static BitMatrix orCode(String content,String path) {
        // 图片的宽度和高度
        int width = 300;
        int height = 300;
        // 图片的格式
        String format = "png";

        //其他参数,如字符集编码
        Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>();
        // 定义字符集编码格式
        hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
        // 纠错的等级 L > M > Q > H 纠错的能力越高可存储的越少,一般使用M
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
        // 设置图片边距
        hints.put(EncodeHintType.MARGIN, 2);
        BitMatrix bitMatrix = null;
        try {
            // 最终生成 参数列表 (1.内容 2.格式 3.宽度 4.高度 5.二维码参数)
            bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height, hints);
            // 写入到本地
            Path file = new File(path).toPath();
            MatrixToImageWriter.writeToPath(bitMatrix, format, file);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return bitMatrix;
    }

    /**
     * @Param: file
     * @return: java.lang.String
     * @Description: 解析二维码
     */
    public static String decode(File file) {
        BufferedImage image;
        try {
            image = ImageIO.read(file);

            LuminanceSource source = new BufferedImageLuminanceSource(image);
            Binarizer binarizer = new HybridBinarizer(source);
            BinaryBitmap binaryBitmap = new BinaryBitmap(binarizer);
            Map<DecodeHintType, Object> hints = new HashMap<DecodeHintType, Object>();
            //解码设置编码方式为:UTF-8
            hints.put(DecodeHintType.CHARACTER_SET, "UTF-8");
            //优化精度
            hints.put(DecodeHintType.TRY_HARDER, Boolean.TRUE);
            //复杂模式,开启PURE_BARCODE模式
            hints.put(DecodeHintType.PURE_BARCODE, Boolean.TRUE);
            Result result = new MultiFormatReader().decode(binaryBitmap, hints);// 对图像进行解码
            return result.getText();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * @Param: filePath
     * @return: java.lang.String
     * @Description: 解析二维码读取文件
     */
    public static String decode(String filePath) {
        return decode(new File(filePath));
    }


    public static void main(String[] args) {
        //生成二维码
        Zxing.orCode("http://www.baidu.com","E:/code.jpg");
        //解析二维码
        System.out.println(Zxing.decode("E:/code.jpg"));
    }
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!