Java生成二维码
使用QRCode生成二维码
jar包qrcode.jar
public class QRCodeUbil {
public void encoderQRCode(String content,String imPath,String imType,int size) throws Exception{
//BufferedImage:内存中的一张图片
/**
*
*/
BufferedImage bufImg = qRcodeCommon(content,imType,size);
File file =new File(imPath);
//生成图片
ImageIO.write(bufImg,imType,file);
}
//产生一个二维码的BufferedImage
public BufferedImage qRcodeCommon(String content ,String imType,int size) throws Exception{
BufferedImage bufImg = null;
//Qrcode 对象,字符串->boolean[][]
Qrcode qrCodeHandler = new Qrcode();
//设置二维码的排错率;7% L<M<Q<H 30%,排错率越高,可存储的信息越少,但是二维码清晰要求越小
qrCodeHandler.setQrcodeErrorCorrect('M');
//可存放的信息类型:N:数字,A:数字加A-Z B:所有
qrCodeHandler.setQrcodeErrorCorrect('B');
//尺寸:取值范围:1-40
qrCodeHandler.setQrcodeVersion(size);
byte[] contentBytes = content.getBytes();
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 j=0;j<codeOut.length;j++){
for(int i=0;i<codeOut.length;i++){
if(codeOut[j][i]){
gs.fillRect(j*3+pixoff,i*3+pixoff,3,3);
}
}
}
//添加图片
Image logo = ImageIO.read(new File("src/123.png"));
int maxHeight = bufImg.getHeight();
int maxWidth = bufImg.getWidth();
gs.drawImage(logo,imgSize/5*2,imgSize/5*2,maxWidth/5,maxHeight/5,null);
gs.dispose();
bufImg.flush();
return bufImg;
}
//解析二维码
public String decodeQRCode(String imPath) throws Exception{
BufferedImage bufImg = ImageIO.read(new File(imPath));
QRCodeDecoder decoder = new QRCodeDecoder();
TowCode tdcImage =new TowCode(bufImg);
byte[] bs=decoder.decode(tdcImage);
String content =new String(bs,"utf-8");
return content;
}
测试代码
public class Test {
public static void main(String[] args) throws Exception {
String imPath ="d:/二维码/www.png";
String content = "www.baidu.com";
QRCodeUbil qrUtil = new QRCodeUbil();
//生成二维码
qrUtil.encoderQRCode(content,imPath,"png",10);
//添加图片
String imgContent= qrUtil.decodeQRCode(imPath);
//解析二维码
System.out.println(imgContent);
}
}
解析二维码有时候是字符 ,增大生成二维码的大小就好了。