【Java开发】生成二维码

import com.swetake.util.Qrcode;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.nio.charset.StandardCharsets;

/**
 * @ClassName QRCode
 * @Description TODO 二维码生成核心类
 * @Author hulin
 * @Date 1/10/2020 8:19 PM
 * @Version 1.0
 */
public class QRCode {
    /**
     * 二维码生成
     *
     * @param content 二维码存储的内容
     * @param imgPath 二维码存储的路径
     */
    public static void getQRCodeImg(String content, String imgPath) {
        /**
         * 二维码基本信息设置
         */
        //实例化一个Qrcode
        Qrcode qrcode = new Qrcode();
        //设置二维码的排错率 L:7%; M:15%;Q:25%;H:30%
        qrcode.setQrcodeErrorCorrect('M');
        //设置编码 A:英文 N:数字 B:国际编码 K:中文
        qrcode.setQrcodeEncodeMode('B');
        //设置二维码的版本
        qrcode.setQrcodeVersion(15);
        /**
         * 开始绘制二维码
         */
        int width = 235;
        int height = 235;
        //画板
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        //画笔
        Graphics2D gs = image.createGraphics();
        //设置背景色
        gs.setBackground(Color.WHITE);
        //设置绘制区域
        gs.clearRect(0, 0, width, height);
        //设置画笔的颜色
        gs.setColor(Color.BLACK);
        //开始绘制,拿到内容
        try {
            byte[] codeOut = content.getBytes(StandardCharsets.UTF_8);
            boolean[][] code = qrcode.calQrcode(codeOut);
            //拿到二维数组里面的内容
            for (int i = 0; i < code.length; i++) {
                for (int j = 0; j < code.length; j++) {
                    if (code[j][i])
                        gs.fillRect(j * 3 + 2, i * 3 + 2, 3, 3);
                }
            }
            //释放画笔
            gs.dispose();
            image.flush();
            //保存
            ImageIO.write(image, "png", new File(imgPath));
            System.out.println("二维码成功生成!");
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public static void main(String[] args) {
        getQRCodeImg("我的第一个二维码!", "web/img/test.png");
        getQRCodeImg("https://www.baidu.com", "web/img/baidu.png");
    }
}
发布了395 篇原创文章 · 获赞 130 · 访问量 20万+

猜你喜欢

转载自blog.csdn.net/qq_40507857/article/details/105391535