我利用的是QRCode.jar和Qrcode_swetake.jar做的
jar都在这里jar
主函数类:
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
public class Test {
public static void main(String[] args) {
QRCodeEncoderHandler header=new QRCodeEncoderHandler();
String imgPath = "D:/test/111.png";
String content = "12345";
try {
BufferedImage bufImg=header.encoderQRCode(content, imgPath);
File file=new File(imgPath);
ImageIO.write(bufImg, "png", file);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("OK");
}
}
工具类:
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import com.swetake.util.Qrcode;
public class QRCodeEncoderHandler {
public BufferedImage encoderQRCode(String content, String imgPath) throws Exception {
BufferedImage bufImg = null;
Qrcode qrcodeHandler = new Qrcode();
qrcodeHandler.setQrcodeEncodeMode('M');
qrcodeHandler.setQrcodeEncodeMode('B');
qrcodeHandler.setQrcodeVersion(7);
byte[] contentBytes = content.getBytes("utf-8");
int imgSize = 140;
bufImg= new BufferedImage(imgSize, imgSize, BufferedImage.TYPE_INT_RGB);
Graphics2D gs = bufImg.createGraphics();
gs.setBackground(Color.WHITE);
gs.clearRect(0, 0, imgSize, imgSize);
gs.setColor(Color.BLACK);
//设置偏移量,不设置可能导致解析出错
int pixoff = 2;
if (contentBytes.length > 0 && contentBytes.length < 800) {
boolean[][] codeOut = qrcodeHandler.calQrcode(contentBytes);
for (int i = 0; i < codeOut.length; i++) {
for (int j = 0; j < codeOut.length; j++) {
if (codeOut[j][i]) {
gs.fillRect(j * 3 + pixoff, i * 3 + pixoff, 3, 3);
}
}
}
}else{
throw new Exception("QRCode content bytes length = " + contentBytes.length + " not in [0, 800].");
}
gs.dispose();
bufImg.flush();
return bufImg;
}
}