首先得导入QRCode jar包
接下来写将信息加密为二维码函数以及解析二维码函数
package com.java.erweima;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
import com.swetake.util.Qrcode;
import jp.sourceforge.qrcode.QRCodeDecoder;
public class QRCode {
//将信息加密为二维码
//content文本信息 imgPath存放二维码路径 imgType图片类型 size大小
public void encode(String content,String imgPath,String imgType,int size)throws Exception
{
BufferedImage bufimg=qrcodecommon(content,imgType,size);
File file=new File(imgPath);
ImageIO .write(bufimg, imgType, file);
}
public BufferedImage qrcodecommon(String content,String imgType,int size)throws Exception {
BufferedImage bufimg=null;
Qrcode qrcodehandler=new Qrcode();
qrcodehandler.setQrcodeErrorCorrect('M');//二维码排错率
qrcodehandler.setQrcodeEncodeMode('B');//可存放信息类型,B:所有
qrcodehandler.setQrcodeVersion(size);//尺寸范围1-40
boolean[][] result = qrcodehandler.calQrcode(content.getBytes("utf-8"));
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<result.length;i++)
{
for(int j=0;j<result.length;j++)
{
if(result[i][j])
{
gs.fillRect(i*3+pixoff, j*3+pixoff, 3, 3);
}
}
}
Image logo=ImageIO.read(new File("src/4.jpg"));//为二维码设置logo
int height=bufimg.getHeight();
int width=bufimg.getWidth();
gs.drawImage(logo, imgsize/5*2, imgsize/5*2,width/5,height/5,null);
gs.dispose();
bufimg.flush();
return bufimg;
}
//解析二维码
public String imgdecode(String imgPath) throws Exception
{
BufferedImage bufimg = ImageIO.read(new File(imgPath));
QRCodeDecoder decoder=new QRCodeDecoder();
QRCodeImpl qri=new QRCodeImpl(bufimg);
byte[] bs = decoder.decode(qri);
String result=new String(bs,"utf-8");
return result;
}
}
因为解析二维码中的decoder.decode()方法中的参数QRCodeImage为接口,所以得写一个类实现这个接口
package com.java.erweima;
import java.awt.image.BufferedImage;
import jp.sourceforge.qrcode.data.QRCodeImage;
public class QRCodeImpl implements QRCodeImage {
BufferedImage bufimg;
public QRCodeImpl(BufferedImage bufimg)
{
this.bufimg=bufimg;
}
@Override
public int getHeight() {
// TODO Auto-generated method stub
return bufimg.getHeight();
}
@Override
public int getPixel(int arg0, int arg1) {
// TODO Auto-generated method stub
return bufimg.getRGB(arg0, arg1);
}
@Override
public int getWidth() {
// TODO Auto-generated method stub
return bufimg.getWidth();
}
}
最后是它的测试类即main方法
package com.java.erweima;
public class Test {
public static void main(String[] args) throws Exception {
String imgPath="src/仲夏.png";
String content="人类的悲欢并不相通,我只是觉得他们吵闹";
//String content="http://www.baidu.com";
QRCode qr=new QRCode();
qr.encode(content, imgPath, "png", 17);
String imgcontent = qr.imgdecode(imgPath);
System.out.println(imgcontent);
}
}
效果: