准备工作:导入QRCode.jar
下载链接:https://files-cdn.cnblogs.com/files/bigroc/QRCode.zip
工具类:
public class QRCodeUtil {
//参数分别为:扫码后信息,二维码路径,二维码图片格式,二维码图片边长
public void encoderQRCode(String content,String imgPatg,String imgType,int size) throws Exception{
//内存中的一张二维码图片
RenderedImage bufImg = qRcodeCommon(content,imgType,size);
File file = new File(imgPatg);
//生成图片,
ImageIO.write(bufImg, imgType, file);
}
public BufferedImage qRcodeCommon(String content,String imgType,int size) throws Exception{
BufferedImage bufImg = null;
Qrcode qrCodeHandler = new Qrcode();
//设置二维码的排错率:7% L<M<Q<H 30%:排错率越高,可存储信息越少,但是对二维码清晰度要求低
qrCodeHandler.setQrcodeErrorCorrect('M');
//二维码可存放的信息:N:只能放数字,A:数字+A-Z B:都支持
qrCodeHandler.setQrcodeEncodeMode('B');
//尺寸:取值范围:1-40
qrCodeHandler.setQrcodeVersion(size);
//字符串转Boolean数组
byte[] contentBytes = content.getBytes("UTF-8");
boolean[][] codeOut = qrCodeHandler.calQrcode(contentBytes);
int imgSize = 67 + 12*(size - 1);
//内存中的图片
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;
//画
for(int i=0;i<codeOut.length;i++) {
for(int j=0;j<codeOut.length;j++) {
if(codeOut[i][j]) {
gs.fillRect(i*3+pixoff, j*3+pixoff, 3, 3);
}
}
}
//增加logo(img),加载一个img对象
Image logo = ImageIO.read(new File("src/logo.jpg"));
//在已生成的二维码上画logo,坐标,宽高(logo不能太大,否则有可能识别不了)
int maxHeigth = bufImg.getHeight();
int maxWdith = bufImg.getWidth();
gs.drawImage(logo,imgSize/5*2, imgSize/5*2, maxWdith/5,maxHeigth/5,null);
gs.dispose();//释放空间
bufImg.flush();//清理
return bufImg;
}
}
测试:
public class qrcodeTest {
public static void main(String[] args) throws Exception {
//生成二维码
String imgPath = "src/二维码.png";//生成二维码图片的路径
String content = "http://www.baidu.com";//二维码中信息,可以是文字信息网址等
QRCodeUtil qrUtil = new QRCodeUtil();
qrUtil.encoderQRCode(content, imgPath, "png", 7);//7为生成二维码图片的大小
}
}