话不多数,直接上源码,再进行的分析。
/***
*
* ClassName: QRcode
* @Description: getQRcode
* @author GuCheng
* @date 2018-7-26
*/
public class QRcode {
/***
*
* <p>Description: one QRcode</p>
* @param QRData 二维码内容
* @param path 二维码存放路径
* @param fileName 生成的二维码的名
* @param format 二维码生成的图片格式
*/
public QRcode(String QRData,String path,String fileName,String format) {
getQRcode(QRData,path,fileName,format);
}
/***
*
* <p>Description:a List QRcode</p>
* @param QRobjList
* @param path
*采用构造方法重载,传入一个list<二维码参数obj>
*/
public QRcode(List<QRobj> QRobjList,String path){
for (QRobj qRobj : QRobjList) {
getQRcode(qRobj.getQRData(),path,qRobj.getFileName(),qRobj.getFormat());
}
}
/***
*
* @Description: TODO
* @param qrData 二维码内容
* @param path 生成的二维码存放路径
* @param fileName 二维码的文件名
* @param format 生成的二维码图片格式
* @return void
* @throws
* @author GuCheng
* @date 2018-7-26
*/
public void getQRcode(String qrData,String path,String fileName,String format) {
try {
Qrcode qrcode = new Qrcode();
qrcode.setQrcodeErrorCorrect('M');// 纠错等级(分为L、M、H三个等级)
qrcode.setQrcodeEncodeMode('B');// N代表数字,A代表a-Z,B代表其它字符
int width = 67 + 12 * 6;//版本-1
int height = 67 + 12 *6;//版本-1
qrcode.setQrcodeVersion(7);// 版本
BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
// 绘图
Graphics2D gs = bufferedImage.createGraphics();
gs.setBackground(Color.WHITE);
gs.setColor(Color.BLACK);
gs.clearRect(0, 0, width, height);// 清除下画板内容
// 设置下偏移量,如果不加偏移量,有时会导致出错。
int pixoff = 2;
byte[] d = qrData.getBytes("utf-8");
if (d.length > 0 && d.length < 120) {
boolean[][] s = qrcode.calQrcode(d);
for (int i = 0; i < s.length; i++) {
for (int j = 0; j < s.length; j++) {
if (s[j][i]) {
gs.fillRect(j * 3 + pixoff, i * 3 + pixoff, 3, 3);
}
}
}
}
gs.dispose();
bufferedImage.flush();
ImageIO.write(bufferedImage, "png", new File(path+"/"+fileName+"."+format));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
******************************************************************************************
二维码参数object
/***
*
* ClassName: QRobj
* @Description: 用作于批量生产二维码图片
* @author GuCheng
* @date 2018-7-26
*/
public class QRobj {
private String QRData;
private String path;
private String fileName;
private String format;
public String getQRData() {
return QRData;
}
public void setQRData(String qRData) {
QRData = qRData;
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public String getFormat() {
return format;
}
public void setFormat(String format) {
this.format = format;
}
}
******************************************************
测试类
自己写。
其实想把这个封装成一个小工具,以后需要做二维码时,直接导入这个jar包,调用QRcode的构造方法就直接ok,但是又考虑到封装的类只提供了两个构造方法的接口,实在有点low,所以就把源码上传,后续使用也会更灵活。