Java 生成二维码,
分享于 点击 22769 次 点评:187
Java 生成二维码,
简述:Java调用swetake库生成二维码
步骤:
1. 在Maven中添加一个库的依赖项
<dependency>
<groupId>swetake</groupId>
<artifactId>qrcode</artifactId>
<version>0.5</version>
</dependency>
2. 生成二维码图片,并返回该File类型文件(自己实现的)
content:需要二维码图片存入的数据String类型
filePath: 存放的文件夹路径
size: 可以根据自己需要实现不同大小的图片其中SIZE_X是自己定义的常量
在代码中unitSize是可以视为每一个单元格的大小,视为二维码的一个单元格;pixOff是图片与边缘的距离;这里都是手调的应该可以实现一个自适应的规格(待实现)
/**
* 生成不同尺寸的二维码
* @param content
* @param filePath
* @param size
* @return
*/
public static File encoderQRCode(final String content,
final String filePath, final int size) {
//生成实际的长度和宽度像素点数, 长宽默认相同
int width = 145;
int height = width;
// 设置偏移量 不设置可能导致解析出错
int pixoff = 0;
//单元格大小,默认3
int unitSize = 3;
//根据不同的规格确定图片长宽,单元格大小
switch(size){
case SIZE_8:
width = 100;
height = width;
unitSize = 2;
break;
case SIZE_12:
width = 142;
height = width;
unitSize = 3;
break;
case SIZE_15:
width = 185;
height = width;
unitSize = 4;
break;
case SIZE_30:
width = 300;
height = width;
unitSize = 6;
break;
case SIZE_50:
width = 500;
height = width;
unitSize = 10;
break;
case SIZE_100:
width = 1000;
height = width;
unitSize = 20;
break;
}
//打开保存的文件路径
File tempFileDir=new File(filePath);
if(!tempFileDir.exists()){
tempFileDir.mkdirs();
logger.debug("创建临时文件夹");
}
//生成二维码
try {
Qrcode qrcodeHandler = new Qrcode();
qrcodeHandler.setQrcodeErrorCorrect('M');
qrcodeHandler.setQrcodeEncodeMode('B');
qrcodeHandler.setQrcodeVersion(7);
byte[] contentBytes = content.getBytes("gb2312");
BufferedImage bufImg = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
Graphics2D gs = bufImg.createGraphics();
gs.setBackground(Color.WHITE);
gs.clearRect(0, 0, width, height);
// 设定图像颜色> BLACK
gs.setColor(Color.BLACK);
// 输出内容> 二维码
if (contentBytes.length > 0 && contentBytes.length < width - 2 * pixoff) {
boolean[][] codeOut = qrcodeHandler.calQrcode(contentBytes);
pixoff = (width - unitSize * codeOut.length) / 2;
for (int i = 0; i < codeOut.length; i++) {
for (int j = 0; j < codeOut.length; j++) {
if (codeOut[j][i]) {
gs.fillRect(j * unitSize + pixoff, i * unitSize + pixoff, unitSize, unitSize);
}
}
}
} else {
logger.debug("QRCode content bytes length = "
+ contentBytes.length + " not in [ 0," + (width - 2 * pixoff) +" ]. ");
}
gs.dispose();
bufImg.flush();
//生成文件名
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmssSSS");
String fileName = sdf.format(new Date());
File imgFile = new File(tempFileDir, fileName + ".png");
// 生成二维码QRCode图片
ImageIO.write(bufImg, "png", imgFile);
return imgFile;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
相关文章
- 暂无相关文章
用户点评