pom依赖
com.google.zxing javase 3.3.0
//text 表示需要写入到二维码中的信息
public static String getQR(String text){
QRCodeWriter wr = new QRCodeWriter();
BitMatrix matrix = null;
try {
matrix = wr.encode(text, BarcodeFormat.QR_CODE, 150, 150);
ByteArrayOutputStream out = new ByteArrayOutputStream();
MatrixToImageWriter.writeToStream(matrix, "png", out);
//转base64编码输出
byte[] str = Base64.getEncoder().encode(out.toByteArray());
String s = new String(str);
return s;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
方式2(可自定义颜色):
private static BufferedImage qrcodeCom() {
int height=100; //定义图片高度
int width=100;
//需要写入二维码中的数据
String qrContent="140429199709061617";
Qrcode qrcode = new Qrcode();
qrcode.setQrcodeEncodeMode('B');//N代表数字,A代表a-Z,B代表其它字符
qrcode.setQrcodeErrorCorrect('Q'); // 设置二维码排错率,可选L(7%)、M(15%)、Q(25%)、H(30%),排错率越高可存储的信息越少,但对二维码清晰度的要求越小
qrcode.setQrcodeVersion(4);//版本,取值范围1-40,值越大尺寸越大,可存储的信息越大
byte[] contentBytes = new byte[0]; //设置编码
try {
contentBytes = qrContent.getBytes("utf-8");
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
BufferedImage bfimg =new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics2D grap=bfimg.createGraphics();
grap.setBackground(Color.white);//设置背景色
grap.setColor(Color.red);//设置二维码颜色
grap.clearRect(0, 0, width, height);//清除下画板内容
int pixoff = 2;// 设置偏移量,不设置可能导致解析出错
if (contentBytes.length>0&&contentBytes.length<800) {
boolean[][] codeout=qrcode.calQrcode(contentBytes);//让字符串生成二维码
for (int i = 0; i < codeout.length; i++) {
for (int j = 0; j < codeout.length; j++) {
if (codeout[i][j]) {
grap.fillRect(i*3+pixoff, j*3+pixoff, 3, 3);
}
}
}
}
return bfimg; //项目需要 所以我返回的是流
//生成图片存储到磁盘中
try {
ImageIO.write(bfimg, "png", new File("D:/pic/red.png"));
} catch (IOException e) {
throw new RuntimeException(e);
}
//二维码转base64编码输出
ByteArrayOutputStream stream = new ByteArrayOutputStream();
try {
ImageIO.write(bfimg, "png", stream);
} catch (IOException e) {
throw new RuntimeException(e);
}
byte[] base64 = Base64.getEncoder().encode(stream.toByteArray());
String str = "data:image/png;base64,"+new String(base64);
System.err.println(str);
}



