導入一個工具類zxing,Java生成二維碼so easy

我們用Spring Boot來輕輕鬆鬆的生成一個二維碼,僅需導入google的zxing工具類就行。

目錄

 

1.引入jar包

2.編寫工具類

3.編寫控制層代碼

4.運行並查看效果


二維碼又稱爲QR Code,就不多說了,生活中處處可見,應用場景相當廣泛。

今天我們就來看看怎麼用Java生成一個二維碼。

1.引入jar包

pom.xml中添加:

        <!-- 二維碼支持包 -->
        <dependency>
            <groupId>com.google.zxing</groupId>
            <artifactId>core</artifactId>
            <version>3.2.0</version>
        </dependency>
        <dependency>
            <groupId>com.google.zxing</groupId>
            <artifactId>javase</artifactId>
            <version>3.2.0</version>
        </dependency>

2.編寫工具類

QRCodeUtil.java:

三個主要功能:

1.創建和插入logo圖片(二維碼正中間那個);

2.生成二維碼;

**生成二維碼可以重載很多方法

** 最主要的區別就是一種是把二維碼圖片存放在某個目錄下,一種通過輸出流直接返回到網頁上

** 其他都是一些小區別,比如有沒有imgPath(logo圖片地址)或needCompress(是否壓縮)這些參數

3.解析二維碼(代碼解析);

package com.erweima.Utils;

import com.google.zxing.*;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.RoundRectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.OutputStream;
import java.util.Hashtable;

/**
 * QRCodeUtil 生成二維碼工具類
 */
public class QRCodeUtil {

    private static final String CHARSET = "utf-8";
    private static final String FORMAT_NAME = "JPG";
    // 二維碼尺寸
    private static final int QRCODE_SIZE = 300;
    // LOGO寬度
    private static final int WIDTH = 60;
    // LOGO高度
    private static final int HEIGHT = 60;


    /**
     * 創建logo圖片(二維碼正中間那個)
     * @param content           內容
     * @param imgPath           LOGO圖片地址
     * @param needCompress      是否壓縮
     * @return
     * @throws Exception
     */
    private static BufferedImage createImage(String content, String imgPath, boolean needCompress) throws Exception {
        Hashtable hints = new Hashtable();
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
        hints.put(EncodeHintType.CHARACTER_SET, CHARSET);
        hints.put(EncodeHintType.MARGIN, 1);
        BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, QRCODE_SIZE, QRCODE_SIZE,
                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 (imgPath == null || "".equals(imgPath)) {
            return image;
        }
        // 插入圖片
        QRCodeUtil.insertImage(image, imgPath, needCompress);
        return image;
    }

    /**
     * 插入logo圖片
     * @param source         二維碼圖片
     * @param imgPath        LOGO圖片地址
     * @param needCompress   是否壓縮
     * @throws Exception
     */
    private static void insertImage(BufferedImage source, String imgPath, boolean needCompress) throws Exception {
        File file = new File(imgPath);
        if (!file.exists()) {
            System.err.println("" + imgPath + "   該文件不存在!");
            return;
        }
        Image src = ImageIO.read(new File(imgPath));
        int width = src.getWidth(null);
        int height = src.getHeight(null);
        if (needCompress) { // 壓縮LOGO
            if (width > WIDTH) {
                width = WIDTH;
            }
            if (height > HEIGHT) {
                height = 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_SIZE - width) / 2;
        int y = (QRCODE_SIZE - 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();
    }


    /**
     * 當文件夾不存在時,mkdirs會自動創建多層目錄,區別於mkdir.(mkdir如果父目錄不存在則會拋出異常)
     * @param destPath
     */
    public static void mkdirs(String destPath) {
        File file = new File(destPath);
        if (!file.exists() && !file.isDirectory()) {
            file.mkdirs();
        }
    }


    /**
     * 生成二維碼可以重載很多方法
     * 最主要的區別就是一種是把二維碼圖片存放在某個目錄下,一種通過輸出流直接返回到網頁上
     * 其他都是一些小區別,比如有沒有imgPath或needCompress這些參數
     */

    /**
     * 生成二維碼
     * @param content           內容
     * @param imgPath           LOGO地址
     * @param destPath          存放目錄
     * @param needCompress      是否壓縮
     * @throws Exception
     */
    public static void encode(String content, String imgPath, String destPath, boolean needCompress) throws Exception {
        BufferedImage image = QRCodeUtil.createImage(content, imgPath, needCompress);
        mkdirs(destPath);
        ImageIO.write(image, FORMAT_NAME, new File(destPath));
    }

    public static BufferedImage encode(String content, String destPath, boolean needCompress) throws Exception {
        BufferedImage image = QRCodeUtil.createImage(content, destPath, needCompress);
        return image;
    }

    /**
     *
     * @param content           內容
     * @param imgPath           LOGO地址
     * @param output            輸出流
     * @param needCompress      是否壓縮
     * @throws Exception
     */
    public static void encode(String content, String imgPath, OutputStream output, boolean needCompress)
            throws Exception {
        BufferedImage image = QRCodeUtil.createImage(content, imgPath, needCompress);
        ImageIO.write(image, FORMAT_NAME, output);
    }

    public static void encode(String content, OutputStream output) throws Exception {
        QRCodeUtil.encode(content, null, output, false);
    }


    /**
     * 解析二維碼
     * @param file      二維碼圖片
     * @return  String
     * @throws Exception
     */
    public static String decode(File file) throws Exception {
        BufferedImage image;
        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, CHARSET);
        result = new MultiFormatReader().decode(bitmap, hints);
        String resultStr = result.getText();
        return resultStr;
    }

    /**
     * 解析二維碼
     * @param path    二維碼圖片地址
     * @return  String
     * @throws Exception
     */
    public static String decode(String path) throws Exception {
        return QRCodeUtil.decode(new File(path));
    }


}

3.編寫控制層代碼

QrCodeController.java:

寫了三個方法:

1.根據text生成普通二維碼;

2.根據text生成帶有logo二維碼;

3.生成二維碼並存放到某文件夾下,還加了一個解析的方法;

package com.erweima.controller;

import com.erweima.Utils.QRCodeUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;


@Controller
public class QrCodeController {


    /**
     * 根據 url 生成 普通二維碼
     */
    @RequestMapping(value = "/createCommonQRCode")
    public void createCommonQRCode(HttpServletResponse response, String url) throws Exception {
        ServletOutputStream stream = null;
        try {
            stream = response.getOutputStream();
            //使用工具類生成二維碼
            QRCodeUtil.encode(url, stream);
        } catch (Exception e) {
            e.getStackTrace();
        } finally {
            if (stream != null) {
                stream.flush();
                stream.close();
            }
        }
    }

    /**
     * 根據 url 生成 帶有logo二維碼
     */
    @RequestMapping(value = "/createLogoQRCode")
    public void createLogoQRCode(HttpServletResponse response, String url) throws Exception {
        ServletOutputStream stream = null;
        try {
            stream = response.getOutputStream();
            String logoPath = Thread.currentThread().getContextClassLoader().getResource("").getPath()
                    + "templates" + File.separator + "logo.jpg";
            //使用工具類生成二維碼
            QRCodeUtil.encode(url, logoPath, stream, true);
        } catch (Exception e) {
            e.getStackTrace();
        } finally {
            if (stream != null) {
                stream.flush();
                stream.close();
            }
        }
    }


}

4.運行並查看效果

本項目提供了三個接口,啓動項目,進行演示;

1.生成普通二維碼,內容爲“I LOVE YOU !”
瀏覽器打開 http://localhost:8080/createCommonQRCode?text=I LOVE YOU ! ,生成的二維碼截圖如下:

 

2.生成帶logo的二維碼,內容爲“https://blog.csdn.net/Ace_2”
瀏覽器打開 http://localhost:8080/createLogoQRCode?text=https://blog.csdn.net/Ace_2 ,生成的二維碼截圖如下:

 

3.生成存放到硬盤的二維碼圖片,並用代碼解析。內容爲“5L中單,不給就送 !”

瀏覽器打開 http://localhost:8080/createSaveQRCode?text=https://blog.csdn.net/Ace_2 ,

生成好了:

打開:

解析結果打印在控制檯:

 

掃描結果就自己驗證了吧,有問題歡迎交流哦!

 

----------------------------------------

 

歡迎關注公衆號“編程江湖”,可以領取Java、Python、微信小程序等學習資料和項目源碼,還能查看技術文章並和大家交流。

​​

(完)

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