代码和jar包链接: https://pan.baidu.com/s/1pLyonvt 密码: edvu
package code;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.Date;
import javax.imageio.ImageIO;
import com.swetake.util.Qrcode;
public class CreateQrCode {
public static void main(String[] args) throws Exception {
Qrcode qrcode = new Qrcode();
qrcode.setQrcodeErrorCorrect('M');//纠错等级(分为L、M、H三个等级)
qrcode.setQrcodeEncodeMode('B');//N代表数字,A代表a-Z,B代表其它字符
qrcode.setQrcodeVersion(7);//版本
//生成二维码中要存储的信息
String qrData = "1330300155";
//设置一下二维码的像素
int width = 67+12*(7-1);
int height = 67+12*(7-1);
BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
//绘图
Graphics2D gs = bufferedImage.createGraphics();
gs.setBackground(Color.WHITE);
gs.setColor(Color.BLACK);
gs.clearRect(0, 0, width, height);//清除下画板内容
//设置下偏移量,如果不加偏移量,有时会导致出错。
int pixoff = 2;
byte[] d = qrData.getBytes("gb2312");
if(d.length > 0 && d.length <120){
boolean[][] s = qrcode.calQrcode(d);
for(int i=0;i<s.length;i++){
for(int j=0;j<s.length;j++){
if(s[j][i]){
gs.fillRect(j*3+pixoff, i*3+pixoff, 3, 3);
}
}
}
}
gs.dispose();
bufferedImage.flush();
ImageIO.write(bufferedImage, "png", new File("E:/code/"+System.currentTimeMillis()+".png"));
}
}
/*-----------------解析----------------------*/
package code;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import jp.sourceforge.qrcode.QRCodeDecoder;
public class ReadQRCode {
public static void main(String[] args) throws IOException{
File file = new File("E:/code/qrcode.png");
BufferedImage bufferedImage = ImageIO.read(file);
QRCodeDecoder codeDecoder = new QRCodeDecoder();
/*其中codeDecoder.decode()中参数需要传入一个实现BufferedImage接口的类
* ,我们新建MyQRCodeImage.java类,该类实现了QRCodeImage接口*/
String result = new String(codeDecoder.decode(new MyQRCodeImage(bufferedImage)),"gb2312");
System.out.println(result);
}
}
/*-----------------------创建MyQRcodeImage类实现QRCodeImage-------------------*/
package code;
import java.awt.image.BufferedImage;
import jp.sourceforge.qrcode.data.QRCodeImage;
public class MyQRCodeImage implements QRCodeImage {
BufferedImage bufferedImage;
public MyQRCodeImage(BufferedImage bufferedImage) {
this.bufferedImage = bufferedImage;
}
@Override
public int getHeight() {
return bufferedImage.getHeight();
}
@Override
public int getPixel(int arg0, int arg1) {
return bufferedImage.getRGB(arg0, arg1);
}
@Override
public int getWidth() {
return bufferedImage.getWidth();
}
}