Zxing是Google提供的关于条码(一维码、二维码)的解析工具,提供了二维码的生成与解析的方法。
1、二维码生成
try {
String content = "http://www.oschina.net";
String path = "D:/testImage/qrcode";
String filename = "qrcode.jpg";
MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
Map hints = new HashMap();
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
BitMatrix bitMatrix = multiFormatWriter.encode(content, BarcodeFormat.QR_CODE, 400, 400,hints);
File file1 = new File(path);
if(!file1.exists()){
file1.mkdirs();
}
file1 = new File(path,filename);
MatrixToImageWriter.writeToFile(bitMatrix, "jpg", file1);
} catch (Exception e) {
e.printStackTrace();
}
2、二维码解析
try {
MultiFormatReader formatReader = new MultiFormatReader();
String filePath = "D:/testImage/qrcode/qrcode169.jpg";
File file = new File(filePath);
BufferedImage image = ImageIO.read(file);;
LuminanceSource source = new BufferedImageLuminanceSource(image);
Binarizer binarizer = new HybridBinarizer(source);
BinaryBitmap binaryBitmap = new BinaryBitmap(binarizer);
Map hints = new HashMap();
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
Result result = formatReader.decode(binaryBitmap,hints);
System.out.println("result = "+ result.toString());
System.out.println("resultFormat = "+ result.getBarcodeFormat());
System.out.println("resultText = "+ result.getText());
} catch (Exception e) {
e.printStackTrace();
}