生成自己的二维码

生成自己的二维码

Posted by catmai on April 21, 2020

生成自己的二维码

用Java生成二维码

项目中存在生成二维码的需求,查询了一下资料,发现生成二维码的方式有很多,也比较简单。选用了zxing包来生成自己定义的二维码。话不多说,直接贴代码。

首先需要引用zxing的jar包,项目是利用MAVEN管理的,直接在pom文件中引用就可以了。

<dependency>
	<groupId>com.google.zxing</groupId>
	<artifactId>core</artifactId>
	<version>3.2.1</version>
</dependency>
<dependency>
	<groupId>com.google.zxing</groupId>
	<artifactId>javase</artifactId>
	<version>3.2.1</version>
</dependency>

引用之后,定义一个工具类,提供几个方法就可以很方便的调用了。

public class QRcodeUtil {

    private static final int width = 300;// 默认二维码宽度
    private static final int height = 300;// 默认二维码高度
    private static final String format = "png";// 默认二维码文件格式
    private static final Map<EncodeHintType, Object> hints = new HashMap<>();// 二维码参数

    static {
        hints.put(EncodeHintType.CHARACTER_SET, "utf-8");// 字符编码
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);// 容错等级 L、M、Q、H 其中 L 为最低, H 为最高
        hints.put(EncodeHintType.MARGIN, 2);// 二维码与图片边距
    }
    /**
     * 返回一个 BufferedImage 对象
     * @param content 二维码内容
     * @param width   宽
     * @param height  高
     */
    public static BufferedImage toBufferedImage(String content, int width, int height) throws WriterException, IOException {
        BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height, hints);
        return MatrixToImageWriter.toBufferedImage(bitMatrix);
    }
    /**
     * 将二维码图片输出到一个流中
     * @param content 二维码内容
     * @param stream  输出流
     * @param width   宽
     * @param height  高
     */
    public static void writeToStream(String content, OutputStream stream, int width, int height) throws WriterException, IOException {
        BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height, hints);
        MatrixToImageWriter.writeToStream(bitMatrix, format, stream);
    }
    /**
     * 生成二维码图片文件
     * @param content 二维码内容
     * @param path    文件保存路径
     * @param width   宽
     * @param height  高
     */
    public static void createQRCode(String content, String path, int width, int height) throws WriterException, IOException {
        BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height, hints);
        MatrixToImageWriter.writeToPath(bitMatrix, format, new File(path).toPath());
    }
}

writeToStream方法可以很直接的把二维码写到页面上,createQRCode则是把二维码图片生成到指定的路径下。

测试一下

String str = "http://catmai.top";
String path = "D:\\qrcode.png";
try {
     QRcodeUtil.createQRCode(str,path,300,300);
} catch (WriterException e) {
     e.printStackTrace();
} catch (IOException e) {
     e.printStackTrace();
}

执行方法后可以再D盘下找到一张图片,用手机扫描后会自动跳转到http://catmai.top 页面。如果内容是文本,直接填写文本内容就可以了,可以用手机扫一下下面生成的二维码试一下。

photo2

如果是写到页面上。

	@RequestMapping("/index")
    public void index(){
        ServletOutputStream outputStream = null;
        String str = "http://catmai.top";
        try {
            outputStream = response.getOutputStream();
            QRcodeUtil.writeToStream(str, outputStream, 300, 300);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

通过ServletOutputStream可以很直接的把二维码直接输出到页面。直接访问项目地址即可。