使用开源google.zxing
依赖jar包:core-3.3.1.jar,javase-3.3.1.jar
http://mvnrepository.com/artifact/com.google.zxing/core/3.3.1
http://mvnrepository.com/artifact/com.google.zxing/javase/3.3.1
public class QRCodeUtil {
/**
* 生成二维码
* @param outputStream
* @param content
* @param size
* @param imageFormat
* @return
* @throws Exception
*/
public static boolean generateQRCode(OutputStream outputStream,String content, int size, String imageFormat)
throws Exception {
Hashtable<EncodeHintType, Object> hintMap = new Hashtable<EncodeHintType, Object>();
hintMap.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);
hintMap.put(EncodeHintType.MARGIN,0);
QRCodeWriter qrCodeWriter = new QRCodeWriter();
BitMatrix byteMatrix = qrCodeWriter.encode(content,BarcodeFormat.QR_CODE, size, size,hintMap);
MatrixToImageWriter.writeToStream(byteMatrix, imageFormat, outputStream);
return true;
}
/**
* 识别二维码
* @param file
* @return
* @throws Exception
*/
public static String recogniseQRCode(File file) throws Exception{
String contents = null;
MultiFormatReader formatReader = new MultiFormatReader();
BufferedImage image;
try {
image = ImageIO.read(file);
LuminanceSource source = new BufferedImageLuminanceSource(image);
Binarizer binarizer = new HybridBinarizer(source);
BinaryBitmap binaryBitmap = new BinaryBitmap(binarizer);
Map<DecodeHintType, Object> hints = new HashMap<DecodeHintType, Object>();
hints.put(DecodeHintType.CHARACTER_SET, "UTF-8");
com.google.zxing.Result result = formatReader.decode(binaryBitmap, hints);
contents = result.toString();
} catch (Exception e) {
e.printStackTrace();
}
return contents;
}
public static void main(String[] args) {
String contents = "bacd";
try {
File file = new File("E:/temp/qrcode.jpg");
// OutputStream os = new FileOutputStream(file);
// generateQRCode(os, contents,200, "jpg");
System.out.println(recogniseQRCode(file));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}