zxing实现二维码的生成和解析

/**
 * 生成二维码
 * @author Administrator
 *
 */
public class CreatQRCode {
    public static void main(String[] args) {

        // 设置图片的长度和宽度
        int width = 300;
        int height = 300;
        // 图片格式
        String format = "png";
        // 二维码内容
        String contents = "第一个二维码生成" + "\n" + "这是第二行";
        try {
            // 解决了生成或读取二维码中文乱码问题
            contents = new String(contents.getBytes("UTF-8"), "ISO-8859-1");
        } catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
        }

        // 定义二维码的参数
        // HashMap hints = new HashMap();
        // hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
        // hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
        // //边距
        // hints.put(EncodeHintType.MARGIN, 2);

        // 生成二维码。。。。。QR_CODE格式的。
        // MultiFormatWriter()
        try {
            // 生成矩阵
            BitMatrix bitMatrix = new MultiFormatWriter().encode(contents, BarcodeFormat.QR_CODE, width, height);

            // 新建二维码存储路径
            Path filePath = new File("D:/二维码生成/img.png").toPath();
            // 输出图像
            MatrixToImageWriter.writeToPath(bitMatrix, format, filePath);
            System.out.print("二维码已生成");
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}

目前流行的三大国际标准

PDF417:不支持中文

DM:专利未公开,需支付专利费用

QR code:开源,支持中文

QR code比其他二维码相比,具有识读速度快,数据密度大,占用空间小的优势。

纠错能力:

L级:约可纠错7%的数据码字

M级:约可纠错15%的数据码字

Q级:约可纠错25%的数据码字

H级:约可纠错30%的数据码字

纠错能力越高,存储的数据就越少

/**
 * 解析二维码
 * @author Administrator
 *
 */
public class ReadQRCode {

    public static void main(String[] args) {
        try {
            MultiFormatReader multiFormatReader = new MultiFormatReader();
            // 文件路径
            File file = new File("D:/二维码生成/img.png");
            // 读取文件
            BufferedImage image = ImageIO.read(file);

            BinaryBitmap binaryBitmap = new BinaryBitmap(new HybridBinarizer(new BufferedImageLuminanceSource(image)));

            // 定义二维码的参数
//          HashMap hints = new HashMap();
//          hints.put(EncodeHintType.CHARACTER_SET, "utf-8");

//          Result result = multiFormatReader.decode(binaryBitmap, hints);
            Result result = multiFormatReader.decode(binaryBitmap);
            System.out.println("解析结果:"+result.toString());
            System.out.println("二维码格式类型:"+result.getBarcodeFormat());
            System.out.println("二维码文本内容"+result.getText());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

jar包链接:zxing的jar包

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值