Java生成与解析二维码
前言: 这周有个项目需要生成二维码,研究了一下使用Google的zxing生成二维码,发现效果还可以,在这里记录下。如果需要更加定制化的二维码,也可接通第三方API服务生成二维码。
一、生成二维码 :
@Component("qrcodeHandler") public class QrcodeHandlerImpl implements QrcodeHandler { private static final Logger logger = LoggerFactory.getLogger(QrcodeHandlerImpl.class); /** 二维码颜色 */ private static final int FRONT_COLOR = 0xFF000000; // 前景色黑色 private static final int BACK_COLOR = 0xFFFFFFFF; // 背景色白色 /** 编码格式 */ private static final String CHARACTER_SET = "UTF-8"; /** 图片类型 */ private static final String FORMAT = "png"; /** 二维码尺寸 */ private static final int QRCODE_SIZE = 300; /** logo信息 */ private static final int LOGO_SIZE = 60; private static final HashMap<EncodeHintType, Object> hints; static { hints = new HashMap<EncodeHintType, Object>(); hints.put(EncodeHintType.CHARACTER_SET, CHARACTER_SET); hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M); hints.put(EncodeHintType.MARGIN, 1); } /** * 生成简单的二维码 * * @param contents 二维码实际内容,包括网址、文本、文件等, 如http://www.cnblogs.com/ark-blog/ * @param destFile 生成的二维码文件 */ public void generateSimpleQrcode(String contents, File destFile) { try { // 1. 生成位矩阵 BitMatrix bitMatrix = new MultiFormatWriter().encode(contents, BarcodeFormat.QR_CODE, QRCODE_SIZE, QRCODE_SIZE, hints); // 2. 保存图片 MatrixToImageWriter.writeToPath(bitMatrix, FORMAT, destFile.toPath()); } catch (Exception e) { logger.error("#generateSimpleQrcode() - create qrcode failed, exception=[{}]", e); throw BusinessException.newInstance("500", "create qrcode failed"); } } /** * 生成带logo的二维码 * * @param contents 二维码实际内容,包括网址、文本、文件等, 如http://www.cnblogs.com/ark-blog/ * @param logoFile logo * @param destFile 生成的二维码文件 */ public void generateLogoQrcode(String contents, File logoFile, File destFile) { try { // 1. 创建位矩阵图 MultiFormatWriter multiFormatWriter = new MultiFormatWriter(); BitMatrix bitMatrix = multiFormatWriter.encode(contents, BarcodeFormat.QR_CODE, QRCODE_SIZE, QRCODE_SIZE, hints); BufferedImage qrcodeImage = new BufferedImage(QRCODE_SIZE, QRCODE_SIZE, BufferedImage.TYPE_INT_RGB); for (int x = 0; x < QRCODE_SIZE; x++) { for (int y = 0; y < QRCODE_SIZE; y++) { qrcodeImage.setRGB(x, y, bitMatrix.get(x, y) ? FRONT_COLOR : BACK_COLOR); } } // 2. 在矩阵图上绘制logo Image logoImage = ImageIO.read(logoFile); BufferedImage logoBufferedImage = new BufferedImage(LOGO_SIZE, LOGO_SIZE, BufferedImage.TYPE_INT_RGB); logoBufferedImage.getGraphics().drawImage(logoImage, 0, 0, null); int position = (QRCODE_SIZE - LOGO_SIZE) / 2; Graphics2D graphics2d = qrcodeImage.createGraphics(); graphics2d.drawImage(logoBufferedImage, position, position, null); graphics2d.dispose(); // 3. 保存图片 qrcodeImage.flush(); ImageIO.write(qrcodeImage, FORMAT, destFile); } catch (Exception e) { logger.error("#generateLogoQrcode() - create qrcode failed, exception=[{}]", e); throw BusinessException.newInstance("500", "create qrcode failed"); } } }
二、解析二维码
@Component("qrcodeHandler") public class QrcodeHandlerImpl implements QrcodeHandler { private static final Logger logger = LoggerFactory.getLogger(QrcodeHandlerImpl.class); /** * 解析二维码 * * @param qrcode 待解析二维码文件 * @return 解析结果 */ public Result decode(File qrcode) { try { // 1. 得到qrcode的bigmap数据 BufferedImage bufferedImage = ImageIO.read(qrcode); BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(new BufferedImageLuminanceSource(bufferedImage))); // 2. 解码配置 Map<DecodeHintType, Object> hints = new HashMap<DecodeHintType, Object>(); hints.put(DecodeHintType.CHARACTER_SET, "UTF-8"); // 3. 解析二维码 MultiFormatReader reader = new MultiFormatReader(); Result result = reader.decode(bitmap, hints); logger.trace("#decode() - result=[{}], qrcode-barcodeFormat=[{}], qrcode-content=[{}]", result.toString(), result.getBarcodeFormat(), result.getText()); return result; } catch (Exception e) { logger.error("#decode() - decode qrcode failed, exception=[{}]", e); throw BusinessException.newInstance("500", "Decode qrcode failed"); } } }