拿手機的二維碼掃描軟體掃過火車票、名片之後,難免會想:這東西自己能不能生成?答案是完全可以,而且用 Java 幾行就能做到。下面示範如何產生一張 QRCode 圖片,並用手機實測掃描。
Qrcode_swetake.jar(官網 https://www.swetake.com/qr/index-e.html)qrcode.jar(官網 https://sourceforge.jp/projects/qrcode/)若日後需要更完整的格式支援,也可以改用 ZXing,它同時涵蓋一維條碼與多種二維碼格式。
public class QRCodeEncoderHandler {
/**
生成二維碼(QRCode)圖片
@param content 要編碼的字串
@param imgPath 輸出的圖片路徑
*/
public void encoderQRCode(String content, String imgPath) {
try {
Qrcode qrcodeHandler = new Qrcode();
qrcodeHandler.setQrcodeErrorCorrect('M'); // 糾錯等級 M
qrcodeHandler.setQrcodeEncodeMode('B'); // 二進位編碼模式
qrcodeHandler.setQrcodeVersion(7); // 版本 7
byte[] contentBytes = content.getBytes("gb2312");
BufferedImage bufImg = new BufferedImage(140, 140, BufferedImage.TYPE_INT_RGB);
Graphics2D gs = bufImg.createGraphics();
gs.setBackground(Color.WHITE);
gs.clearRect(0, 0, 140, 140);
// 設定圖像顏色 > BLACK
gs.setColor(Color.BLACK);
// 設定偏移量,不設定可能導致解析出錯
int pixoff = 2;
if (contentBytes.length > 0 && contentBytes.length < 120) {
boolean[][] codeOut = qrcodeHandler.calQrcode(contentBytes);
for (int i = 0; i < codeOut.length; i++) {
for (int j = 0; j < codeOut.length; j++) {
if (codeOut[j][i]) {
gs.fillRect(j * 3 + pixoff, i * 3 + pixoff, 3, 3);
}
}
}
} else {
System.err.println("QRCode content bytes length = " + contentBytes.length + " not in [ 0,120 ].");
}
gs.dispose();
bufImg.flush();
ImageIO.write(bufImg, "png", new File(imgPath));
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
String imgPath = "D:/test/twocode/Michael_QRCode.png";
String content = "Hello 大大、小小,welcome to QRCode!"
+ "\nMyblog [ https://www.linuxidc.com ]"
+ "\nEMail [ sjsky007@gmail.com ]"
+ "\nTwitter [ @suncto ]";
new QRCodeEncoderHandler().encoderQRCode(content, imgPath);
System.out.println("encoder QRcode success");
}
}
'B'(二進位)模式搭配 gb2312 取得位元組,是為了讓中文能正確進入 QR 碼;解碼端也得用相同字集還原。pixoff 不能省。它為圖形留出安靜區(quiet zone),少了留白,掃描器往往無法定位。程式跑完後,在 D:/test/twocode/Michael_QRCode.png 就能看到生成的圖片。拿手機的掃描軟體(例如快拍二維碼)對準螢幕,成功識別後會顯示出原本寫入的網址、信箱與 Twitter 帳號。有興趣的朋友可以試著把它改成名片格式,或加上自己的 vCard 資訊。