Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

Java 生成二維碼的完整實例源碼

下面這段代碼基於 com.swetake.util.Qrcode 類,把任意字符串編碼成 JPG 圖片,流程清晰、可直接運行。

完整源碼

import java.io.*;
import java.util.Date;

import java.awt.*;
import java.awt.image.*;
import javax.imageio.*;

import com.swetake.util.Qrcode;

public class QRCodeEncoderTest {
    public QRCodeEncoderTest() {
    }

    public static void create_image(String sms_info) throws Exception {
        try {
            Qrcode testQrcode = new Qrcode();
            testQrcode.setQrcodeErrorCorrect('M');   // 糾錯等級 M
            testQrcode.setQrcodeEncodeMode('B');     // 二進制編碼模式
            testQrcode.setQrcodeVersion(20);         // 版本號,決定矩陣尺寸

            String testString = sms_info;
            byte[] d = testString.getBytes("gbk");
            System.out.println(d.length);

            BufferedImage bi = new BufferedImage(98, 98,
                    BufferedImage.TYPE_BYTE_BINARY);
            Graphics2D g = bi.createGraphics();
            g.setBackground(Color.WHITE);
            g.clearRect(0, 0, 98, 98);
            g.setColor(Color.BLACK);

            // 限制最大字節數
            if (d.length > 0 && d.length < 300) {
                boolean[][] s = testQrcode.calQrcode(d);
                for (int i = 0; i < s.length; i++) {
                    for (int j = 0; j < s.length; j++) {
                        if (s[j][i]) {
                            g.fillRect(j * 2 + 3, i * 2 + 3, 2, 2);
                        }
                    }
                }
            }
            g.dispose();
            bi.flush();

            File f = new File("D:\\QRCodeTest\\" + sms_info + ".jpg");
            if (!f.exists()) {
                f.createNewFile();
            }
            ImageIO.write(bi, "jpg", f);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws Exception {
        System.out.println(new Date());
        QRCodeEncoderTest.create_image("QRCode");
        System.out.println(new Date());
    }
}

關鍵參數說明

  • 糾錯等級:'L'、'M'、'Q'、'H' 由低到高,等級越高越抗污損,但可容納的數據量隨之下降。一般場景選 'M' 即可。
  • 編碼模式:'B' 為二進制,數字與字母可選 'N'/'A' 以獲得更高密度。
  • 版本號:決定矩陣的模塊數,版本 20 對應較大的信息容量,代碼中同時把畫布固定為 98×98 並以 2 像素為一個模塊繪製。

實務建議

示例把輸出路徑寫死為 D:\QRCodeTest\,實際項目中應改為可配置參數,並確保目錄存在。另外 getBytes("gbk") 依賴平台字符集,跨環境部署時建議統一使用 UTF-8,並在解碼端約定一致,避免中文亂碼。若項目使用 Maven 或 Gradle,直接引入成熟開源庫(如 ZXing)會比自行維護移植類更省心。

Copyright © Linux教程網 All Rights Reserved