1. 程式人生 > 實用技巧 >spring boot:用zxing生成二維碼,支援logo(spring boot 2.3.2)

spring boot:用zxing生成二維碼,支援logo(spring boot 2.3.2)

一,zxing是什麼?

1,zxing的用途

如果我們做二維碼的生成和掃描,通常會用到zxing這個庫,

ZXing是一個開源的,用Java實現的多種格式的1D/2D條碼影象處理庫。

zxing還可以實現使用手機的內建的攝像頭完成條形碼的掃描及解碼

2,zxing官方專案地址:

https://github.com/zxing/zxing

說明:劉巨集締的架構森林是一個專注架構的部落格,地址:https://www.cnblogs.com/architectforest

對應的原始碼可以訪問這裡獲取:https://github.com/liuhongdi/

說明:作者:劉巨集締 郵箱: [email protected]

二,演示專案的相關資訊

1,專案地址

https://github.com/liuhongdi/qrcode

2, 專案功能說明:

生成二維碼直接展示

生成二維碼儲存成圖片

解析二維碼圖片中的文字資訊

3,專案結構,如圖:

三,配置檔案說明

1,pom.xml

        <!--qrcode begin-->
        <dependency>
            <groupId>com.google.zxing</groupId>
            <artifactId>core</
artifactId> <version>3.4.0</version> </dependency> <dependency> <groupId>com.google.zxing</groupId> <artifactId>javase</artifactId> <version>3.4.0</version> </dependency
> <!--qrcode end-->

匯入zxing庫供生成qrcode使用

四,java程式碼說明

1,QrCodeUtil.java

/**
 * 二維碼工具類
 * by liuhongdi
 */
public class QrCodeUtil {

    //編碼格式,採用utf-8
    private static final String UNICODE = "utf-8";
    //圖片格式
    private static final String FORMAT = "JPG";
    //二維碼寬度畫素pixels數量
    private static final int QRCODE_WIDTH = 300;
    //二維碼高度畫素pixels數量
    private static final int QRCODE_HEIGHT = 300;
    //LOGO寬度畫素pixels數量
    private static final int LOGO_WIDTH = 100;
    //LOGO高度畫素pixels數量
    private static final int LOGO_HEIGHT = 100;

    //生成二維碼圖片
    //content 二維碼內容
    //logoPath logo圖片地址
    private static BufferedImage createImage(String content, String logoPath) throws Exception {
        Hashtable<EncodeHintType, Object> hints = new Hashtable<EncodeHintType, Object>();
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
        hints.put(EncodeHintType.CHARACTER_SET, UNICODE);
        hints.put(EncodeHintType.MARGIN, 1);
        BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, QRCODE_WIDTH, QRCODE_HEIGHT,
                hints);
        int width = bitMatrix.getWidth();
        int height = bitMatrix.getHeight();
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                image.setRGB(x, y, bitMatrix.get(x, y) ? 0xFF000000 : 0xFFFFFFFF);
            }
        }
        if (logoPath == null || "".equals(logoPath)) {
            return image;
        }
        // 插入圖片
        QrCodeUtil.insertImage(image, logoPath);
        return image;
    }

    //在圖片上插入LOGO
    //source 二維碼圖片內容
    //logoPath LOGO圖片地址
    private static void insertImage(BufferedImage source, String logoPath) throws Exception {
        File file = new File(logoPath);
        if (!file.exists()) {
            throw new Exception("logo file not found.");
        }
        Image src = ImageIO.read(new File(logoPath));
        int width = src.getWidth(null);
        int height = src.getHeight(null);
            if (width > LOGO_WIDTH) {
                width = LOGO_WIDTH;
            }
            if (height > LOGO_HEIGHT) {
                height = LOGO_HEIGHT;
            }
            Image image = src.getScaledInstance(width, height, Image.SCALE_SMOOTH);
            BufferedImage tag = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            Graphics g = tag.getGraphics();
            g.drawImage(image, 0, 0, null); // 繪製縮小後的圖
            g.dispose();
            src = image;
        // 插入LOGO
        Graphics2D graph = source.createGraphics();
        int x = (QRCODE_WIDTH - width) / 2;
        int y = (QRCODE_HEIGHT - height) / 2;
        graph.drawImage(src, x, y, width, height, null);
        Shape shape = new RoundRectangle2D.Float(x, y, width, width, 6, 6);
        graph.setStroke(new BasicStroke(3f));
        graph.draw(shape);
        graph.dispose();
    }

    //生成帶logo的二維碼圖片,儲存到指定的路徑
    // content 二維碼內容
    // logoPath logo圖片地址
    // destPath 生成圖片的儲存路徑
    public static String save(String content, String logoPath, String destPath) throws Exception {
        BufferedImage image = QrCodeUtil.createImage(content, logoPath);
        File file = new File(destPath);
        String path = file.getAbsolutePath();
        File filePath = new File(path);
        if (!filePath.exists() && !filePath.isDirectory()) {
            filePath.mkdirs();
        }
        String fileName = file.getName();
        fileName = fileName.substring(0, fileName.indexOf(".")>0?fileName.indexOf("."):fileName.length())
                + "." + FORMAT.toLowerCase();
        System.out.println("destPath:"+destPath);
        ImageIO.write(image, FORMAT, new File(destPath));
        return fileName;
    }

    //生成二維碼圖片,直接輸出到OutputStream
    public static void encode(String content, String logoPath, OutputStream output)
            throws Exception {
        BufferedImage image = QrCodeUtil.createImage(content, logoPath);
        ImageIO.write(image, FORMAT, output);
    }

    //解析二維碼圖片,得到包含的內容
    public static String decode(String path) throws Exception {
        File file = new File(path);
        BufferedImage image = ImageIO.read(file);
        if (image == null) {
            return null;
        }
        BufferedImageLuminanceSource source = new BufferedImageLuminanceSource(image);
        BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
        Result result;
        Hashtable<DecodeHintType, Object> hints = new Hashtable<DecodeHintType, Object>();
        hints.put(DecodeHintType.CHARACTER_SET, UNICODE);
        result = new MultiFormatReader().decode(bitmap, hints);
        return result.getText();
    }
}

工具類,包含了生成二維碼、儲存二維碼,展示二維碼,解析二維碼

2,HomeController.java

@RequestMapping("/home")
@Controller
public class HomeController {
    //生成帶logo的二維碼到response
    @RequestMapping("/qrcode")
    public void qrcode(HttpServletRequest request, HttpServletResponse response) {
        String requestUrl = "http://www.baidu.com";
        try {
            OutputStream os = response.getOutputStream();
            QrCodeUtil.encode(requestUrl, "/data/springboot2/logo.jpg", os);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //生成不帶logo的二維碼到response
    @RequestMapping("/qrnologo")
    public void qrnologo(HttpServletRequest request, HttpServletResponse response) {
        String requestUrl = "http://www.baidu.com";
        try {
            OutputStream os = response.getOutputStream();
            QrCodeUtil.encode(requestUrl, null, os);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //把二維碼儲存成檔案
    @RequestMapping("/qrsave")
    @ResponseBody
    public String qrsave() {
        String requestUrl = "http://www.baidu.com";
        try {
            QrCodeUtil.save(requestUrl, "/data/springboot2/logo.jpg", "/data/springboot2/qrcode2.jpg");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "檔案已儲存";
    }

    //解析二維碼中的文字
    @RequestMapping("/qrtext")
    @ResponseBody
    public String qrtext() {
        String url = "";
        try {
             url = QrCodeUtil.decode("/data/springboot2/qrcode2.jpg");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "解析到的url:"+url;
    }
}

入口處包含了四個方法,接下來我們做測試

五,測試效果

1,生成不帶logo的二維碼,訪問:

http://127.0.0.1:8080/home/qrnologo

效果:

2,生成帶logo的二維碼:訪問

http://127.0.0.1:8080/home/qrcode

效果:

3,生成二維碼儲存成檔案:訪問:

http://127.0.0.1:8080/home/qrsave

程式碼中檔案被儲存成了:/data/springboot2/qrcode2.jpg

4,解析二維碼中包含的文字資訊:訪問:

http://127.0.0.1:8080/home/qrtext

返回:

解析到的url:http://www.baidu.com

成功解析到了圖片中包含的url地址

六,檢視spring boot版本

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.3.2.RELEASE)