用QRcode来写 用到jar包有两个 qrcode.jar(生成时候用)和Qrcode_swetake.jar(解析时候有用到)
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import jp.sourceforge.qrcode.QRCodeDecoder;
import jp.sourceforge.qrcode.exception.DecodingFailedException;
import com.swetake.util.Qrcode;
public class QRcode {
public static void main(String[] args) {
getQRencoder();
getQRdecoder();
}
//调用生成二维码
public static void getQRencoder(){
String imgPath = "C:/Users/Adminstaion/Desktop/QRCode.jpg";
String content = "http://www.baidu.com";
encoderQRCode(content, imgPath);
System.out.println("打包内容:"+content);
}
//调用解析二维码
public static void getQRdecoder(){
String imgPath = "C:/Users/Adminstaion/Desktop/QRCode.jpg";
String decoderContent = decoderQRCode(imgPath);
System.out.println("解析结果:"+decoderContent);
}
/////////////////////////////生成、解析二维码/////////////////////////////////////////
// 生成二维码
public static void encoderQRCode(String content, String imgPath){
try{
Qrcode qrcode = new Qrcode();
//二维码排错率 可选L、M、Q、H 排错率越高 可存储信息越少 清晰度要求越小
qrcode.setQrcodeErrorCorrect('M');
//1为21*21 每增1 边长都增4 最高版本为是40
int version = 7;
qrcode.setQrcodeVersion(version);
int imgSize = 67 + 12 * (version- 1) ;
byte[] contentBytes = content.getBytes("UTF-8");
BufferedImage 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 < 120){
boolean[][] codeOut = qrcode.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{
System.out.println("二维码字节长度不在0到120之间");
}
gs.dispose();
bufImg.flush();
File imgFile = new File(imgPath);
// 生成二维码
ImageIO.write(bufImg, "jpg", imgFile);
}catch (Exception e){
e.printStackTrace();
}
}
//解析二维码
public static String decoderQRCode(String imgPath){
//二维码图片路径
File imageFile = new File(imgPath);
BufferedImage bufImg = null;
String decodedData = null;
try{
bufImg = ImageIO.read(imageFile);
QRCodeDecoder decoder = new QRCodeDecoder();
decodedData = new String(decoder.decode(new J2SEImage(bufImg)),"UTF-8");
}catch (IOException e){
e.printStackTrace();
}catch (DecodingFailedException dfe){
dfe.printStackTrace();
}
return decodedData;
}
}