您的位置:首页 > 编程语言 > Java开发

java通过zxing生成二维码

2017-07-07 10:05 363 查看
需要的jar包

Zxing-javase-3.2.0.jar

zxing.jar

如出现类找不到请切换jdk版本

public class Test5 {

/**
* 生成二维码
*/
public static void createCode() {
//内容(可以写上网址例如:http://www.baidu.com)
String text = "大家好,我叫***";
//二维码的长宽
int width = 300;
int height = 300;
// 二维码的图片格式
String format = "png";
/**
* 设置二维码的参数
*/
HashMap hints = new HashMap();
// 内容所使用编码
hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
try {
BitMatrix bitMatrix = new MultiFormatWriter().encode(text, BarcodeFormat.QR_CODE, width, height, hints);
// 生成二维码文件(路径)
Path file = new File("D:/TDC-test.png").toPath();
//写入到文件
MatrixToImageWriter.writeToPath(bitMatrix, format, file);

} catch (Exception e) {
e.printStackTrace();
}
}

/**
* 解析二维码
* @param filePath 二维码图片路径
* @return
*/
public static String decodeQr(String filePath) {
String retStr = "";
String retStr2="" ;
if ("".equalsIgnoreCase(filePath) && filePath.length() == 0) {
return "图片路径为空!";
}
try {
BufferedImage bufferedImage = ImageIO.read(new FileInputStream(
filePath));
LuminanceSource source = new BufferedImageLuminanceSource(
bufferedImage);
Binarizer binarizer = new HybridBinarizer(source);
BinaryBitmap bitmap = new BinaryBitmap(binarizer);
HashMap<DecodeHintType, Object> hintTypeObjectHashMap = new HashMap();
hintTypeObjectHashMap.put(DecodeHintType.CHARACTER_SET, "UTF-8");
Result result = new MultiFormatReader().decode(bitmap,
hintTypeObjectHashMap);
retStr = result.getText();
retStr2=result.getBarcodeFormat().toString();
} catch (Exception e) {
e.printStackTrace();
}
return retStr+retStr2;
}

//测试
public static void main(String[] args) {

// TODO Auto-generated method stub
//调用生成二维码的方法
Test5.createCode();
//调用解析二维码的方法
System.out.println(decodeQr("D:/TDC-test.png"));
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: