第一篇
java生成二维码代码:
public static void getQRCodeImage(String content,String imgPath){
//实例化一个Qrcode对象,生成二维码
Qrcode qrCode= new Qrcode();
//设置编码
qrCode.setQrcodeEncodeMode('B');
//设置容错率(15%)
qrCode.setQrcodeErrorCorrect('M');
//设置二维码版本
qrCode.setQrcodeVersion(15);
/*
* 准备画二维码,准备好画板,画笔,绘制
*/
int width = 235;
int height = 235;
//准备画板
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
//准备画笔
Graphics2D gs = image.createGraphics();
//设置背景颜色
gs.setBackground(Color.white);
//绘制矩形
gs.clearRect(0, 0, width, height);
//设置绘制颜色
gs.setColor(Color.black);
//根据内容绘制二维码
try {
byte[] codeout;
codeout = content.getBytes("utf-8");
//将内容转存为二维数组
boolean[][] code = qrCode.calQrcode(codeout);
//遍历这个二维数组,真 假
// 设置偏移量,不设置可能导致解析出错
int pixoff = 2;
for(int i = 0;i<code.length;i++){
for(int j = 0;j<code.length;j++){
if(code[j][i]){
//如果是真就绘制小矩形
gs.fillRect(j*3+pixoff, i*3+pixoff, 3,3);
}
}
}
//释放资源
gs.dispose();
image.flush();
//保存到本地
ImageIO.write(image, "jpg", new File(imgPath));
System.out.println("二维码生成成功!");
} catch (Exception e) {
e.printStackTrace();
}
}
测试调用:
public static void main(String[] args) {
getQRCodeImage(“context”, “E://TestImage/context.jpg”);
}