java创建QRCode二维码的三种方式

自己在网上看视频学习了下如何使用java创建二维码,感觉还是挺有趣的,有小心思的还可以把秘密存入二维码中噢

视频源网址:http://www.imooc.com/learn/531

点击下载jar包


二维码的类别

二维码依据码制的编码原理,通常分为三种:

线性堆叠式二维码、矩阵式二维码、邮政码。

  1. 线性堆叠式二维码:建立在一维条码基础上,按需要堆积成两行或多行。与一维码很类似。
  2. 矩阵式二维码:(最常用)在一个矩阵空间通过黑、白像素在矩阵中的不同分布进行编码。在矩阵相应元素位置上,用点(方点、圆点或其它形状)的出现表示二进制“1”,点的不出现表示二进制的“0”。QR CODE
  3. 邮政码:通过不同长度的条进行编码,主要用于邮件编码。
二维码详解:

优缺点

二维码优点:

	(1)高密度编码,信息容量大;
	(2)编码范围广;
	(3)容错能力强;
	(4)编码可靠性高;
	(5)可引入加密措施;
	(6)成本低,易制作,持久耐用。

二维码缺点:

	(1)二维码技术成为手机病毒、钓鱼网站传播的新渠道;
	(2)信息泄露。


三大国际标准

  1. PDF417:不支持中文
  2. DM:专利未公开,需支付专利费
  3. QRCode:专利公开,支持中文

因为QRCode 支持中文,免费。读取速度快,数据密度大,占用空间小的优势。本次只介绍怎么生成QRCode二维码
纠错等级:
L级:7%   
M级:15%  
Q级:25%  
H级:30%

JSP生成二维码的方法: --jar包在页头

①借助第三方jar,如zxing和qrcodejar ②JavaScript,如jquery.qrcode.js


1.zxing方式

/**
     * 使用zxing创建QrCode格式二维码 
     * @param content 二维码的内容
     * @param fullPath 完整的资源存储路径
     */
    public static void createQrCode(String content, String fullPath) {
        //定义宽高和图片格式和二维码内容
        int width = 300;
        int height = 300;
        String format = "png";
        /*String content = "";*/

        //定义文件路径
        /*Path filePath = new File("E:/JavaExcelTest/QrCode02.png").toPath();*/
        Path filePath = new File(fullPath).toPath();

        //定义二维码参数:编码格式
        HashMap config = new HashMap();
        config.put(EncodeHintType.CHARACTER_SET, "UTF-8");
        //二维码的纠错等级:L,M,Q,H.从低到高,纠错等级越高,所存储的数据就越少
        config.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
        //二维码的空白间隔值,默认为5
        config.put(EncodeHintType.MARGIN, 2);
        MultiFormatWriter mfw = new MultiFormatWriter();
        try {
            //BarcodeFormat.QR_CODE是一种二维码的格式
            BitMatrix bm = mfw.encode(content, BarcodeFormat.QR_CODE, width, height, config);
            //写入资源
            MatrixToImageWriter.writeToPath(bm, format, filePath);
        } catch (WriterException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println("写入完毕!");
    }

    /**
     * 使用zxings解析QrCode格式二维码
     * @param fullPath 完整的资源存储路劲
     */
    public static void readQrCode(String fullPath) {
        try {
            MultiFormatReader multiFormatReader = new MultiFormatReader();
            File file = new File(fullPath);
            //读取资源转为图片
            BufferedImage image = ImageIO.read(file);
            BinaryBitmap binaryBitmap = new BinaryBitmap(new HybridBinarizer(
                new BufferedImageLuminanceSource(image)));
            //解析为result对象
            Result result = multiFormatReader.decode(binaryBitmap);
            System.out.println("二维码数据: " + result.toString());
            System.out.println("二维码编码格式: " + result.getBarcodeFormat());
            System.out.println("二维码内容: " + result.getText());
        } catch (NotFoundException e) {
            System.out.println("文件未找到!");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

2.QRCode

/**
     * 通过QRCode创建QrCode
     * @param content 二维码的文本内容
     * @param fullPath 二维码的存储路径
     */
    public static void createQrCode(String content, String fullPath) {
        Qrcode qrCode = new Qrcode();
        qrCode.setQrcodeErrorCorrect('M');//纠错等级
        qrCode.setQrcodeVersion('7');//版本号1-40
        qrCode.setQrcodeEncodeMode('B');//'N'是数字,'A'是a-Z,'B'是其他字符

        //宽高公式:width=67+12*(版本号-1)
        int width = 67 + 12 * (7 - 1);
        int height = 67 + 12 * (7 - 1);

        BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics2D grap = bufferedImage.createGraphics();
        //设置背景
        grap.setBackground(Color.white);
        //设置画笔颜色
        grap.setColor(Color.black);
        //清除画板
        grap.clearRect(0, 0, width, height);

        //偏移量,防止解析发生异常
        int pixoff = 2;

        try {
            //字节转换
            byte[] contentByte = content.getBytes("UTF-8");
            if (contentByte.length > 0 && contentByte.length < 120) {
                boolean[][] s = qrCode.calQrcode(contentByte);
                for (int i = 0; i < s.length; i++) {
                    for (int j = 0; j < s.length; j++) {
                        if (s[j][i]) {
                            grap.fillRect(j * 3 + pixoff, i * 3 + pixoff, 3, 3);
                        }
                    }
                }
            }
            grap.dispose();
            bufferedImage.flush();
            ImageIO.write(bufferedImage, "png", new File(fullPath));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println("写入成功");
    }

    /**
     * 通过QRCode解析QRCode
     * @param fullPath 二维码的存储路径
     */
    public static void readQrCode(String fullPath) {
        File file = new File(fullPath);
        try {
            BufferedImage bufferedImage = ImageIO.read(file);
            //创建QRCode解析实例
            QRCodeDecoder qrCode = new QRCodeDecoder();
            /*
             * 解析
             * qrCode.decode(QrCodeImage qrCodeImage)
             * qrCodeImage是一个接口,无法实例化,需自定义类并实现QRCodeImage接口
             */
            String result = new String(qrCode.decode(new MyQrCodeImage(bufferedImage)), "UTF-8");
            System.out.println(result);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

QRCodeImage实现类:
package com.qrCode;

import java.awt.image.BufferedImage;

import jp.sourceforge.qrcode.data.QRCodeImage;

public class MyQrCodeImage implements QRCodeImage {

    BufferedImage bufferedImage;

    public MyQrCodeImage(BufferedImage bufferedImage) {
        this.bufferedImage = bufferedImage;
    }

    @Override
    public int getHeight() {
        return this.bufferedImage.getHeight();
    }

    //获取像素
    @Override
    public int getPixel(int x, int y) {
        return this.bufferedImage.getRGB(x, y);
    }

    @Override
    public int getWidth() {
        return this.bufferedImage.getWidth();
    }

}

3.jQuery方式:最简单,但支持功能太少,不支持中文

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ page import="com.entity.User" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Login</title>
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript" src="js/jquery.qrcode.min.js"></script>
<style type="text/css">
body{
background-color: #fff;
}
.main{
width:500px;
height:200px;
margin: auto auto;
text-align: center;
}
</style>
</head>
<body>
<div class="qrcode"></div>
</body>
<script type="text/javascript">
$(function(){
	 $(".qrcode").qrcode("阿拉蕾 "); 
	
})

</script>
</html>



  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
创建会议并生成二维码,你可以使用以下步骤: 1. 下载并导入生成二维码的库,比如 Google 的 zxing 库。可以在 Maven 中添加以下依赖: ```xml <dependency> <groupId>com.google.zxing</groupId> <artifactId>core</artifactId> <version>3.3.3</version> </dependency> ``` 2. 创建一个会议对象,包含会议的信息,如会议名称、时间、地点等。 ```java public class Meeting { private String name; private String time; private String location; // 构造函数和 getter/setter 方法省略 } ``` 3. 使用 zxing 库生成二维码。下面是一个示例代码: ```java import com.google.zxing.BarcodeFormat; import com.google.zxing.EncodeHintType; import com.google.zxing.WriterException; import com.google.zxing.client.j2se.MatrixToImageWriter; import com.google.zxing.common.BitMatrix; import com.google.zxing.qrcode.QRCodeWriter; import java.io.IOException; import java.nio.file.FileSystems; import java.nio.file.Path; import java.util.HashMap; import java.util.Map; public class QRCodeGenerator { private static final String QR_CODE_IMAGE_PATH = "./MyQRCode.png"; public static void generateQRCodeImage(String text, int width, int height, String filePath) throws WriterException, IOException { // 创建二维码编写器 QRCodeWriter qrCodeWriter = new QRCodeWriter(); // 设置二维码参数 Map<EncodeHintType, Object> hints = new HashMap<>(); hints.put(EncodeHintType.CHARACTER_SET, "UTF-8"); hints.put(EncodeHintType.MARGIN, 1); // 生成二维码矩阵 BitMatrix bitMatrix = qrCodeWriter.encode(text, BarcodeFormat.QR_CODE, width, height, hints); // 保存二维码图片 Path path = FileSystems.getDefault().getPath(filePath); MatrixToImageWriter.writeToPath(bitMatrix, "PNG", path); } public static void main(String[] args) { Meeting meeting = new Meeting("Java 开发者会议", "2021-12-31 18:00", "上海市人民广场"); try { // 生成会议信息的 JSON 字符串 ObjectMapper objectMapper = new ObjectMapper(); String jsonString = objectMapper.writeValueAsString(meeting); // 生成二维码图片 generateQRCodeImage(jsonString, 350, 350, QR_CODE_IMAGE_PATH); System.out.println("二维码生成,保存在:" + QR_CODE_IMAGE_PATH); } catch (WriterException | IOException e) { System.err.println("生成二维码失败:" + e.getMessage()); } } } ``` 在这个示例中,我们使用了 Jackson 库将会议对象转换成 JSON 格式的字符串,然后使用 zxing 库生成二维码图片,并将二维码保存在指定的文件路径下。你可以根据自己的需求调整代码,然后运行它来生成二维码

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值