1、导入需要的jar包 QRCode.jar
点击下载 QRCode.jar 建立Java工程导入jar包
提取码:sazv
2、示例代码
public class ORImage {
public static void getORCode(String path,String content) throws UnsupportedEncodingException{
//1、创建一个ORCode对象
Qrcode qrcode = new Qrcode();
//2、设置二维码的纠错等级,二维码的纠错等级一共就四个 L: 7% M:15% Q:25% H:30%
qrcode.setQrcodeErrorCorrect('M');
//3、设置二维码的存储形式
qrcode.setQrcodeEncodeMode('B');
//4、设置版本
qrcode.setQrcodeVersion(7);
//5、把存储的信息转换成字节数组
byte[]bt = content.getBytes();
//6、创建一个图像的数据缓冲区(纸)
BufferedImage image = new BufferedImage(140, 140, BufferedImage.TYPE_INT_BGR);
//7、创建一支笔
Graphics2D g = image.createGraphics();
//8、设置二维码的背景颜色
g.setBackground(Color.WHITE);
//9、填充背景颜色
g.fillRect(0, 0, 140, 140);
//10、设置二维码的前景色
g.setColor(Color.BLACK);
//11、判断字节数组的长度>0
if(bt.length>0){
boolean[][] b =qrcode.calQrcode(bt);
for(int i =0;i<b.length;i++){
for(int j=0;j<b.length;j++){
//根据布尔数组绘制二维码,绘制矩形
if(b[j][i]){
g.fillRect(j*3+2, i*3+2, 3, 3);
}
}
}
}
//12、创建文件流对象
File file = new File(path);
try {
//写入二维码
ImageIO.write(image, "png", file);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String[] args) {
try {
//生成的二维码的存放地址 E:\\Hello\\gong.png
getORCode("E:\\Hello\\baidu.png", "Http://www.baidu.com");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
希望可以帮助到需要学习的人,也不辜负小白的汗水,不对的地方,希望大家指正