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