二维码解码编码

pom引入包:

<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>3.4.0</version>
</dependency>
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>javase</artifactId>
<version>3.4.0</version>
</dependency>
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>3.4.0</version>
</dependency>


/**
* 解析图片文件上的二维码
*
* @param imageFile 图片文件
* @return 解析的结果,null表示解析失败
*/
private static String decode(File imageFile) {
try {
BufferedImage image = ImageIO.read(imageFile);
LuminanceSource luminanceSource = new BufferedImageLuminanceSource(image);
Binarizer binarizer = new HybridBinarizer(luminanceSource);

BinaryBitmap binaryBitmap = new BinaryBitmap(binarizer);

Map<DecodeHintType, Object> hints = new HashMap<>();
hints.put(DecodeHintType.CHARACTER_SET, "utf-8");
//优化精度
hints.put(DecodeHintType.TRY_HARDER, Boolean.TRUE);
hints.put(DecodeHintType.POSSIBLE_FORMATS, BarcodeFormat.QR_CODE);
//复杂模式
hints.put(DecodeHintType.PURE_BARCODE, Boolean.TRUE);
Result result = new QRCodeReader().decode(binaryBitmap, hints);

return result.getText();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}

/**
* Zxing图形码生成工具
*
* @param contents 内容
* @param barcodeFormat BarcodeFormat对象
* @param format 图片格式,可选[png,jpg,bmp]
* @param width 宽
* @param height 高
* @param margin 边框间距px
* @param saveImgFilePath 存储图片的完整位置,包含文件名
* @return {boolean}
*/
public static boolean encode(String contents, BarcodeFormat barcodeFormat, Integer margin,
ErrorCorrectionLevel errorLevel, String format, int width, int height, String saveImgFilePath) {
Boolean bool = false;
BufferedImage bufImg;
Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>();
// 指定纠错等级
hints.put(EncodeHintType.ERROR_CORRECTION, errorLevel);
hints.put(EncodeHintType.MARGIN, margin);
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
try {
// contents = new String(contents.getBytes("UTF-8"), "ISO-8859-1");
BitMatrix bitMatrix = new MultiFormatWriter().encode(contents, barcodeFormat, width, height, hints);
MatrixToImageConfig config = new MatrixToImageConfig(0xFF000001, 0xFFFFFFFF);
bufImg = MatrixToImageWriter.toBufferedImage(bitMatrix, config);
bool = writeToFile(bufImg, format, saveImgFilePath);
} catch (Exception e) {
e.printStackTrace();
}
return bool;
}

测试方法:
public static void main(String[] args) {
// 解码
String result = decode(new File("D:\\微信二维码.jpg"));
System.out.println("解码二维码:" + result);
//生成二维码
String newQrCode = "D://newQrCode.png";
encode("http://outer.qtoubao.cn/work/card/index.html?sev_no=10002895", BarcodeFormat.QR_CODE, 3, ErrorCorrectionLevel.H, "png", 200, 200,
newQrCode);
}