package org.springrain.frame.util;@b@@b@import com.google.zxing.*;@b@import com.google.zxing.client.j2se.BufferedImageLuminanceSource;@b@import com.google.zxing.client.j2se.MatrixToImageWriter;@b@import com.google.zxing.common.BitMatrix;@b@import com.google.zxing.common.HybridBinarizer;@b@import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;@b@import org.apache.commons.lang3.StringUtils;@b@@b@import javax.imageio.ImageIO;@b@import java.awt.image.BufferedImage;@b@import java.io.File;@b@import java.util.HashMap;@b@import java.util.Map;@b@@b@public class QrCodeUtils {@b@@b@ private static final Integer defaultWidth = 300;@b@ private static final Integer defaultHeight = 300;@b@ private static final String defaultQrCodeFormat = "png";@b@@b@ private QrCodeUtils() {@b@ throw new IllegalAccessError("工具类不能实例化");@b@ }@b@@b@ /**@b@ * 生成二维码@b@ *@b@ * @param content 内容@b@ * @param qrFile 需要生成的二维码文件@b@ * @return@b@ * @throws Exception@b@ */@b@@b@ public static File genQrCode(String content, File qrFile) throws Exception {@b@ return genQrCode(content, qrFile, defaultWidth, defaultHeight);@b@ }@b@@b@ /**@b@ * 生成二维码@b@ *@b@ * @param content 内容@b@ * @param qrFile 需要生成的二维码文件@b@ * @param width 二维码文件宽度@b@ * @param height 二维码文件高度@b@ * @return@b@ * @throws Exception@b@ */@b@ public static File genQrCode(String content, File qrFile, Integer width, Integer height) throws Exception {@b@ if (content == null || qrFile == null) {@b@ return null;@b@ }@b@ String qrCodeFormat = FileUtils.getFileFormat(qrFile.getName());@b@ if (StringUtils.isBlank(qrCodeFormat)) {@b@ qrCodeFormat = defaultQrCodeFormat;@b@ }@b@@b@ // 配置参数@b@ HashMap<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>();@b@ // 容错级别 这里选择最高H级别@b@ hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);@b@ // 编码格式@b@ hints.put(EncodeHintType.CHARACTER_SET, GlobalStatic.defaultCharset);@b@ BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height, hints);// 生成矩阵@b@ MatrixToImageWriter.writeToPath(bitMatrix, qrCodeFormat, qrFile.toPath());// 输出图像@b@@b@ return qrFile;@b@ }@b@@b@ /**@b@ * 二维码识别@b@ *@b@ * @param qrFile@b@ * @return@b@ * @throws Exception@b@ */@b@ public static Result decodeQrCode(File qrFile) throws Exception {@b@ BufferedImage image = ImageIO.read(qrFile);@b@ LuminanceSource source = new BufferedImageLuminanceSource(image);@b@ Binarizer binarizer = new HybridBinarizer(source);@b@ BinaryBitmap binaryBitmap = new BinaryBitmap(binarizer);@b@ Map<DecodeHintType, Object> hints = new HashMap<DecodeHintType, Object>();@b@ hints.put(DecodeHintType.CHARACTER_SET, GlobalStatic.defaultCharset);@b@ Result result = new MultiFormatReader().decode(binaryBitmap, hints);// 对图像进行解码@b@@b@ return result;@b@@b@ }@b@@b@}