文章主要用QrCodejar包來生成二維碼,用掃一掃即可掃出來對應的二維碼:
準備對應Q人Codejar包
package com.allen.test;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
import com.swetake.util.Qrcode;
public class QrCodeAllenTest {
public static void getQrCodeByImage(String contents,String path){
int width =140;
int height = 140;
try {
Qrcode qrCode = new Qrcode();
//設置出錯率
qrCode.setQrcodeErrorCorrect('M');
qrCode.setQrcodeEncodeMode('B');
//二維碼尺寸(1-40)
qrCode.setQrcodeVersion(7);
//設置尺寸
BufferedImage bufImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_BGR);
//繪製二維碼圖片
Graphics2D gs = bufImg.createGraphics();
//設置二維碼的背景顏色:白色
gs.setBackground(Color.white);
//創建圖片的矩形區域
gs.clearRect(0, 0, width, height);
//設置二維碼的顏色
gs.setColor(Color.green);
//獲取內容,通過數組形式,設置編碼格式
byte[] contentByte = contents.getBytes("gb2312");
//設置偏移量(不設置可能會導致解析錯誤)
int pixOff = 2;
//輸出二維碼:插件最大隻能存儲120個字符
if(contentByte.length>0 && contentByte.length<120){
//把一維數組中的值放到一個boolean類型的數組中
boolean [][]codeOut = qrCode.calQrcode(contentByte);
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.out.println("解析出錯了!!!!,內容長度超出最大的限制");
}
gs.dispose();
bufImg.flush();
//生成二維碼圖片
File imgFile = new File(path);
ImageIO.write(bufImg, "png", imgFile);
System.out.println("二維碼生成成功!!!");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String[] args){
System.out.println("哈哈");
String contents = "<h1>你好!JAVA!QrCode</h1>";
String path = "G://ewm//";
QrCodeAllenTest.getQrCodeByImage(contents, path);
}
}