//所需jar包下载地址:http://download.csdn.net/download/huchgu/9996818
//二维码演示实现类,支持中文无乱码,在项目中导入所需jar即可运行
public class QrcodeDemo {public static void main(String[] args) {
String str = "https://github.com/zxing/zxing"; //二维码内容
String path = "E:/test.png"; //二维码图片生成路径
QrcodeDemo t = new QrcodeDemo(); //实例化演示类
t.encode(str, path,400,400); //生成二维码图片
String res = t.decode(path); //根据传入的2维码图片所在路径,解析得到二维码图片里的内容
System.out.println("解码结果:"+res); //打印扫描结果}
/* 编码:生成二维码图片
* str:二维码内容
* path:二维码图片生成 路径及名称,如 D:/Qr_pics/test.png
* width:设置二维码图片宽的长度
* height:设置二维码图片高的长度
* */
public void encode(String str, String path,int width,int height) {
try {
BitMatrix byteMatrix = new MultiFormatWriter()
.encode(str, BarcodeFormat.QR_CODE, width, height); //后两个参数设置二维码图片大小-图片像素大小
File file = new File(path); //新建矩阵文件
MatrixToImageWriter.writeToFile(byteMatrix, "gif", file); //将矩阵文件转换成图片文件
} catch (Exception e) {
e.printStackTrace();
}
}
/*
* 解码:获取二维码里的内容
* imgPath:即将被解码图片的路径,如 D:/Qr_pics/test.png
* */
public String decode(String imgPath) {
try {
File file = new File(imgPath); //获取该图片文件
BufferedImage image = ImageIO.read(file);
if (image != null) {
LuminanceSource source = new BufferedImageLuminanceSource(image);
BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
Hashtable hashtable = new Hashtable(); //将图片反解码为二维矩阵
hashtable.put(DecodeHintType.CHARACTER_SET, "UTF-8");
Result result = new MultiFormatReader().decode(bitmap, hashtable); //将该二维矩阵解码成内容
return result.getText();
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}