java 使用Qrcode 生成“有圖片、無圖片”兩種類型 二維碼

二維碼分爲兩種,一種是 中心有logo的,一種是無logo的,只有二維碼內容

這裏提供一個工具類,測試類

1.工具類,(工具類中有相關注解,就不解釋什麼意思了)

package com.jeecg.demo.utils;

import com.swetake.util.Qrcode;
import org.apache.commons.lang3.StringUtils;

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

/**
 * QrcodeUtil
 * <p>  生成二維碼工具類 包含存放中間圖片和不存放中間圖片
 *
 * @author hanyunchuan
 * @version 1.0
 */
public class QrcodeUtil {
    /**
     * 生成二維碼(QRCode)有圖片
     *
     * @param content  二維碼圖片的內容
     * @param imgPath  存放生成二維碼圖片完整的路徑
     * @param logoPath 二維碼圖片中間的logo路徑
     * @param type     生成的圖片後綴
     */
    public static String createQRCode(String content, String imgPath, String logoPath, int version, String type) {
        try {
            if (StringUtils.isBlank(imgPath)) {
                return "imgPath保存圖片的路徑未不存在";
            } else if (StringUtils.isBlank(logoPath)) {
                return "logoPath保存圖片的路徑未不存在";
            } else if (StringUtils.isBlank(content)) {
                return "content二維碼內容爲空";
            }
            Qrcode qrcodeHandler = new Qrcode();
            // 設置二維碼排錯率,可選L(7%)、M(15%)、Q(25%)、H(30%),排錯率越高可存儲的信息越少,但對二維碼清晰度的要求越小
            qrcodeHandler.setQrcodeErrorCorrect('M');
            // N代表數字,A代表字符a-Z,B代表其他字符
            qrcodeHandler.setQrcodeEncodeMode('B');
            // 設置設置二維碼版本,取值範圍1-40,值越大尺寸越大,可存儲的信息越大
            // 這裏對生成二維碼內容長度做了判斷,如果當前二維碼版本不能夠存放足夠內容的話,會自動+1版本 (下方的 catch (ArrayIndexOutOfBoundsException))
            qrcodeHandler.setQrcodeVersion(version);
            // 圖片尺寸
            int imgSize = 67 + 12 * (version - 1);
            byte[] contentBytes = content.getBytes("utf-8");
            BufferedImage image = new BufferedImage(imgSize, imgSize,
                    BufferedImage.TYPE_INT_RGB);
            Graphics2D gs = image.createGraphics();
            gs.setBackground(Color.WHITE);
            gs.clearRect(0, 0, imgSize, imgSize);
            // 設定圖像顏色 > BLACK
            gs.setColor(Color.BLACK);
            // 設置偏移量 不設置可能導致解析出錯
            int pixoff = 2;
            // 輸出內容 > 二維碼
            if (contentBytes.length > 0 && contentBytes.length < 500) {
                boolean[][] codeOut = qrcodeHandler.calQrcode(contentBytes);
                for (int i = 0; i < codeOut.length; i++) {
                    for (int j = 0; j < codeOut.length; j++) {
                        if (codeOut[j][i]) {
                            gs.fillRect(j * 3 + pixoff, i * 3 + pixoff, 3, 3);
                        }
                    }
                }
            } else {
                return "QRCode content bytes length =" + contentBytes.length + " not in [ 0,500]";
            }
            // 實例化一個Image對象。
            Image logo = ImageIO.read(new File(logoPath));
            int widthLogo = logo.getWidth(null) > image.getWidth() * 3 / 10 ? (image.getWidth() * 3 / 10) :
                    logo.getWidth(null), heightLogo = logo.getHeight(null) > image.getHeight() * 3 / 10 ?
                            (image.getHeight() * 3 / 10) : logo.getWidth(null);
            /**
             * logo放在中心
             */
            int x = (image.getWidth() - widthLogo) / 2;
            int y = (image.getHeight() - heightLogo) / 2;
            gs.drawImage(logo, x, y, widthLogo, heightLogo, null);
            gs.dispose();
            image.flush();
            // 生成二維碼QRCode圖片
            File imgFile = new File(imgPath);
            ImageIO.write(image, type, imgFile);
        } catch (ArrayIndexOutOfBoundsException ae) {
            if (version < 20) {
                System.out.print("內容過多提高二維碼級別,當前級別:" + version);
                createQRCode(content, imgPath, logoPath, version + 1, type);
            } else {
                ae.printStackTrace();
                return "error";
            }
        } catch (Exception e) {
            e.printStackTrace();
            return "error";
        }
        return "success";
    }

    /**
     * 生成二維碼(QRCode)無圖片
     *
     * @param content 二維碼圖片的內容    //生成二維碼中要存儲的信息
     * @param imgPath 存放生成二維碼圖片完整的路徑
     * @param type    生成的圖片後綴
     * @param version 二維碼版本號 1 - 20
     * @return StatusCode
     */
    public static String createQRCode(String content, String imgPath, int version, String type) {
        long startTime = System.currentTimeMillis();
        System.out.println("startTime-:" + startTime);
        try {
            Qrcode qrcode = new Qrcode();
            qrcode.setQrcodeErrorCorrect('M');//糾錯等級(分爲L、M、H三個等級)
            qrcode.setQrcodeEncodeMode('B');//N代表數字,A代表a-Z,B代表其它字符
            qrcode.setQrcodeVersion(version);//版本

            //設置一下二維碼的像素
            int width = 67 + 12 * (qrcode.getQrcodeVersion() - 1);
            int height = 67 + 12 * (qrcode.getQrcodeVersion() - 1);
            BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            //繪圖
            Graphics2D gs = bufferedImage.createGraphics();
            gs.setBackground(Color.WHITE);
            gs.setColor(Color.BLACK);
            gs.clearRect(0, 0, width, height);//清除下畫板內容

            //設置下偏移量,如果不加偏移量,有時會導致出錯。
            int pixoff = 2;

            byte[] d = new byte[0];

            d = content.getBytes("gb2312");

            if (d.length > 0 && d.length < 120) {
                boolean[][] s = qrcode.calQrcode(d);
                for (int i = 0; i < s.length; i++) {
                    for (int j = 0; j < s.length; j++) {
                        if (s[j][i]) {
                            gs.fillRect(j * 3 + pixoff, i * 3 + pixoff, 3, 3);
                        }
                    }
                }
            }
            gs.dispose();
            bufferedImage.flush();
            ImageIO.write(bufferedImage, type, new File(imgPath));
        } catch (Exception e) {
            e.printStackTrace();
            return "error";
        }
        long endTime = System.currentTimeMillis();
        System.out.println("endTime-:" + endTime);
        System.out.println("用時-:" + (endTime - startTime));
        return "success";
    }


}

com.swetake.util.Qrcode 類需要下載一個jar包,

這個jar包csdn已存在,我就不上傳了.可以搜索一下qrCode.jar,或者去其他地方下載相關jar包.

[注:含圖片的二維碼生成方法中有二維碼自動增加級別,無圖片的沒有,可以自行添加]

2.測試類:

    public static void main(String[] args) {
        String content = "https://blog.csdn.net/hyc123123123123";
//      二維碼中心有logo
        QrcodeUtil.createQRCode(content, "E:\\del\\qrcode有logo.jpg", "E:\\del\\timg.jpg", 4, "png");
//      二維碼中心無logo
        QrcodeUtil.createQRCode(content, "E:\\del\\qrcode無logo.jpg",  4, "png");
    }

測試生成結果:

有logo:

無logo:

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章