首頁 > 軟體

Java Spring boot實現生成二維條碼

2022-02-09 10:00:28

一、引入spring boot依賴:

   <!--引入生成二維條碼的依賴-->
   <!-- https://mvnrepository.com/artifact/com.google.zxing/core -->
   <dependency>
       <groupId>com.google.zxing</groupId>
       <artifactId>core</artifactId>
       <version>3.3.0</version>
   </dependency>
   <!-- https://mvnrepository.com/artifact/com.google.zxing/javase -->
   <dependency>
       <groupId>com.google.zxing</groupId>
       <artifactId>javase</artifactId>
       <version>3.3.0</version>
   </dependency>

二、工具類程式碼:

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.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Hashtable;

/**
 * 二維條碼生成工具類
 */
public class QrCodeUtils {
    private static final String CHARSET = "utf-8";
    public static final String FORMAT = "JPG";
    // 二維條碼尺寸
    private static final int QRCODE_SIZE = 300;
    // LOGO寬度
    private static final int LOGO_WIDTH = 60;
    // LOGO高度
    private static final int LOGO_HEIGHT = 60;

    /**
     * 生成二維條碼
     *
     * @param content      二維條碼內容
     * @param logoPath     logo地址
     * @param needCompress 是否壓縮logo
     * @return 圖片
     * @throws Exception
     */
    public static BufferedImage createImage(String content, String logoPath, boolean needCompress) throws Exception {
        Hashtable<EncodeHintType, Object> hints = new Hashtable<EncodeHintType, Object>();
        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 (logoPath == null || "".equals(logoPath)) {
            return image;
        }
        // 插入圖片
        QrCodeUtils.insertImage(image, logoPath, needCompress);
        return image;
    }

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

    /**
     * 生成二維條碼(指定路徑儲存)
     *
     * @param content 內容
     * @param imgPath logo圖片地址(內嵌圖片)
     * @param destPath 生成二維條碼存放地址
     * @param needCompress 是否壓縮logo
     * @throws Exception
     */
    public static void encode(String content, String imgPath, String destPath, boolean needCompress) throws Exception {
        BufferedImage image = QrCodeUtils.createImage(content, imgPath, needCompress);
        mkdirs(destPath);
        // String file = new Random().nextInt(99999999)+".jpg";
        // ImageIO.write(image, FORMAT_NAME, new File(destPath+"/"+file));
        ImageIO.write(image, FORMAT, new File(destPath));
    }

    /**
     * 生成二維條碼(直接將二維條碼以圖片輸出流返回)
     *
     * @param content 內容
     * @param imgPath logo圖片地址(內嵌圖片)
     * @param needCompress 是否壓縮logo
     * @return
     * @throws Exception
     */
    public static BufferedImage encode(String content, String imgPath, boolean needCompress) throws Exception {
        BufferedImage image = QrCodeUtils.createImage(content, imgPath, needCompress);
        return image;
    }

    public static void mkdirs(String destPath) {
        File file = new File(destPath);
        // 當資料夾不存在時,mkdirs會自動建立多層目錄,區別於mkdir.(mkdir如果父目錄不存在則會丟擲異常)
        if (!file.exists() && !file.isDirectory()) {
            file.mkdirs();
        }
    }

    /**
     * 生成二維條碼(內嵌LOGO)
     *
     * @param content      內容
     * @param logoPath     LOGO地址
     * @param output       輸出流
     * @param needCompress 是否壓縮LOGO
     * @throws Exception
     */
    public static void encode(String content, String logoPath, OutputStream output, boolean needCompress)
            throws Exception {
        BufferedImage image = QrCodeUtils.createImage(content, logoPath, needCompress);
        ImageIO.write(image, FORMAT, output);
    }

    /**
     * 獲取指定檔案的輸入流,獲取logo
     *
     * @param logoPath 檔案的路徑
     * @return
     */
    public static InputStream getResourceAsStream(String logoPath) {
        return QrCodeUtils.class.getResourceAsStream(logoPath);
    }

    /**
     * 解析二維條碼
     *
     * @param file
     *            二維條碼圖片
     * @return
     * @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
     * @throws Exception
     */
    public static String decode(String path) throws Exception {
        return QrCodeUtils.decode(new File(path));
    }

	//測試一:
    public static void main(String[] args) throws Exception {
        String text = "https://blog.csdn.net/weixin_43763430";
        String logoPath = "D:\qrCode\logo.jpg";
        String destPath = "D:\qrCode\csdn.jpg";
        QrCodeUtils.encode(text,logoPath,destPath,true);
    }
}

三、呼叫工具類生成二維條碼

1、將連結生成二維條碼圖片並儲存到指定路徑

工具類中的主方法是指定了二維條碼連結的內容是部落格地址,並儲存在D:qrCodecsdn.jpg,二維條碼巢狀了頭像的圖片,期望實現的是生成二維條碼後被掃碼直接進入到部落格也沒。如若不嵌入頭像,直接將logoPath引數設為null。

	//測試一:
    public static void main(String[] args) throws Exception {
        String text = "https://blog.csdn.net/weixin_43763430";
        String logoPath = "D:\qrCode\logo.jpg";
        String destPath = "D:\qrCode\csdn.jpg";
        QrCodeUtils.encode(text,logoPath,destPath,true);
    }

執行該主方法後,可在指定路徑中看到生成的二維條碼圖片。

2、將連結生成二維條碼直接顯示在頁面

運用spring boot生成二維條碼無需將儲存二維條碼的圖片,只須前端呼叫springboot介面即可在頁面上顯示二維條碼。實現了實時生成二維條碼。Controller層介面程式碼範例如下:

	@GetMapping("/anon/coupon/qrCodeTest")
    @ApiOperation(value = "獲取二維條碼")
    public void qrCodeTest(HttpServletResponse response) throws Exception {
        String text = "https://blog.csdn.net/weixin_43763430";
        String logoPath = "D:\qrCode\logo.jpg";
        //String destPath = "D:\qrCode\csdn.jpg";
        QrCodeUtils.encode(text,logoPath,response.getOutputStream(),true);
    }

開啟瀏覽器存取該介面地址,頁面就會顯示生成的二維條碼。掃描二維條碼即可進入到部落格頁面。

3、將以get請求傳參連結生成二維條碼

二維條碼運用到各種業務中,通常需要根據不同使用者識別其相對應的內容,如以上範例是存取的部落格主頁面,如若想根據存取者傳遞的引數存取部落格中特定的文章,文章存取各篇文章是用的get請求方式,即可根據傳參實現get請求傳入不同引數生成二維條碼的內容不同。

	@GetMapping("/anon/coupon/qrCodeTest")
    @ApiOperation(value = "獲取二維條碼")
    public void qrCodeTest(@RequestParam(value = "id") String id,HttpServletResponse response) throws Exception {
        String text = "https://blog.csdn.net/weixin_43763430/article/details/" + id;
        String logoPath = "D:\qrCode\logo.jpg";
        //String destPath = "D:\qrCode\csdn.jpg";
        QrCodeUtils.encode(text,logoPath,response.getOutputStream(),true);
    }

用瀏覽器存取該介面地址,頁面生成二維條碼,用手機掃描二維條碼即可跳轉到部落格中該篇文章頁面。

總結

到此這篇關於Java Spring boot實現生成二維條碼的文章就介紹到這了,更多相關Java Spring boot生成二維條碼內容請搜尋it145.com以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援it145.com!


IT145.com E-mail:sddin#qq.com