Java生成二维码之zxing

0

pom.xml

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

代码

package com.acgist.qrcode;

import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

import javax.imageio.ImageIO;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;

import com.acgist.logger.Logger;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.Binarizer;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.DecodeHintType;
import com.google.zxing.EncodeHintType;
import com.google.zxing.LuminanceSource;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.NotFoundException;
import com.google.zxing.Result;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

/**
 * 二维码工具
 */
public class QRCodeUtils {

	public static final void main(String[] args) {
		long b = System.currentTimeMillis();
		encode("https://www.baidu.com", 300, 300, 1, "D:\\yy.png", "D:\\code.png");
		// System.out.println(decode("D:\\code.png"));
		long e = System.currentTimeMillis();
		System.out.println(e - b);
	}

	private final static int LOGO_MAX_WH = 40; // LOGO最大高宽

	/**
	 * 生成二维码
	 * 
	 * @param content 图片地址
	 * @param width 图片宽度
	 * @param height 图片高度
	 * @param margin 边距:小于表示默认
	 * @param codePath 输出地址
	 */
	public static final void encode(String content, int width, int height, int margin, String codePath) {
		encode(content, width, height, margin, null, null, null, codePath);
	}

	/**
	 * 生成二维码
	 * 
	 * @param content 图片地址
	 * @param width 图片宽度
	 * @param height 图片高度
	 * @param margin 边距:小于表示默认
	 * @param os 输出流
	 */
	public static final void encode(String content, int width, int height, int margin, OutputStream os) {
		encode(content, width, height, margin, null, null, null, os);
	}

	/**
	 * 生成二维码
	 * 
	 * @param content 图片地址
	 * @param width 图片宽度
	 * @param height 图片高度
	 * @param margin 边距:小于表示默认
	 * @param logoPath logo地址:可以为空
	 * @param codePath 输出地址
	 */
	public static final void encode(String content, int width, int height, int margin, String logoPath, String codePath) {
		encode(content, width, height, margin, null, null, logoPath, codePath);
	}

	/**
	 * 生成二维码
	 * 
	 * @param content 图片地址
	 * @param width 图片宽度
	 * @param height 图片高度
	 * @param margin 边距:小于表示默认
	 * @param logoPath logo地址:可以为空
	 * @param os 输出流
	 */
	public static final void encode(String content, int width, int height, int margin, String logoPath, OutputStream os) {
		encode(content, width, height, margin, null, null, logoPath, os);
	}

	/**
	 * 生成二维码
	 * 
	 * @param content 图片地址
	 * @param width 图片宽度
	 * @param height 图片高度
	 * @param margin 边距:小于0表示默认
	 * @param level 容错率:可以为空
	 * @param charset 编码:默认UTF-8
	 * @param logoPath logo地址:可以为空
	 * @param codePath 输出地址
	 */
	public static final void encode(String content, int width, int height, int margin, ErrorCorrectionLevel level, String charset, String logoPath, String codePath) {
		if (StringUtils.isEmpty(codePath)) {
			return;
		}
		OutputStream os = null;
		try {
			os = new FileOutputStream(new File(codePath));
			encode(content, width, height, margin, level, charset, logoPath, os);
		} catch (FileNotFoundException e) {
			Logger.error(QRCodeUtils.class, "打开输出流错误", e);
		} finally {
			IOUtils.closeQuietly(os);
		}
	}

	/**
	 * 生成二维码
	 * 
	 * @param content 图片地址
	 * @param width 图片宽度
	 * @param height 图片高度
	 * @param margin 边距:小于0表示默认
	 * @param level 容错率:可以为空
	 * @param charset 编码:默认UTF-8
	 * @param logoPath logo地址:可以为空
	 * @param os 输出流
	 */
	public static final void encode(String content, int width, int height, int margin, ErrorCorrectionLevel level, String charset, String logoPath, OutputStream os) {
		if (StringUtils.isEmpty(content) || os == null) {
			return;
		}
		Graphics2D graphics2d = null;
		BufferedImage logoImage = null;
		BufferedImage codeImage = null;
		try {
			Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>();
			if (margin >= 0) {
				hints.put(EncodeHintType.MARGIN, margin); // 边距
			}
			if (level != null) {
				hints.put(EncodeHintType.ERROR_CORRECTION, level); // 容错率
			}
			if (StringUtils.isNotEmpty(charset)) {
				hints.put(EncodeHintType.CHARACTER_SET, charset); // 编码
			} else {
				hints.put(EncodeHintType.CHARACTER_SET, "UTF-8"); // 编码
			}
			MultiFormatWriter formatWriter = new MultiFormatWriter();
			BitMatrix bitMatrix = formatWriter.encode(content, BarcodeFormat.QR_CODE, width, height, hints);
			codeImage = MatrixToImageWriter.toBufferedImage(bitMatrix);
//			graphics2d = codeImage.createGraphics();
			BufferedImage target = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); // 设置ARGB颜色
			graphics2d = target.createGraphics();
			graphics2d.drawImage(codeImage, 0, 0, null); // 画二维码
			if (StringUtils.isNotEmpty(logoPath)) { // 画logo
				logoImage = ImageIO.read(new File(logoPath));
				int logoWidth = logoImage.getWidth() > LOGO_MAX_WH ? LOGO_MAX_WH : logoImage.getWidth();
				int logoHeight = logoImage.getHeight() > LOGO_MAX_WH ? LOGO_MAX_WH : logoImage.getHeight();
				int marginLeft = (width - logoWidth) / 2;
				int marginTop = (height - logoHeight) / 2;
				graphics2d.drawImage(logoImage.getScaledInstance(logoWidth, logoHeight, Image.SCALE_SMOOTH), marginLeft, marginTop, null);
			}
			target.flush();
			ImageIO.write(target, "png", os);
		} catch (WriterException e) {
			Logger.error(QRCodeUtils.class, "二维码生成错误", e);
		} catch (IOException e) {
			Logger.error(QRCodeUtils.class, "二维码生成错误", e);
		} finally {
			if (graphics2d != null) {
				graphics2d.dispose();
			}
		}
	}

	/**
	 * 解析二维码
	 * 
	 * @param codePath 图片地址
	 * @return 内容
	 */
	public static final String decode(String codePath) {
		return decode(codePath, null);
	}

	/**
	 * 解析二维码
	 * 
	 * @param codePath 图片地址
	 * @param charset 编码
	 * @return 内容
	 */
	public static final String decode(String codePath, String charset) {
		if (StringUtils.isEmpty(codePath)) {
			return null;
		}
		File file = new File(codePath);
		if (!file.exists() || !file.isFile()) {
			return null;
		}
		BufferedImage image;
		try {
			image = ImageIO.read(file);
			return decode(image, charset);
		} catch (IOException e) {
			Logger.error(QRCodeUtils.class, "二维码图片文件读取错误", e);
		}
		return null;
	}

	/**
	 * 二维码解析
	 * 
	 * @param image 图片流
	 * @param charset 编码
	 * @return 内容
	 */
	public static final String decode(BufferedImage image, String charset) {
		MultiFormatReader formatReader = new MultiFormatReader();
		LuminanceSource source = new BufferedImageLuminanceSource(image);
		Binarizer binarizer = new HybridBinarizer(source);
		BinaryBitmap binaryBitmap = new BinaryBitmap(binarizer);
		Map<DecodeHintType, Object> hints = new HashMap<DecodeHintType, Object>();
		if (StringUtils.isEmpty(charset)) {
			hints.put(DecodeHintType.CHARACTER_SET, "UTF-8");
		} else {
			hints.put(DecodeHintType.CHARACTER_SET, charset);
		}
		Result result = null;
		try {
			result = formatReader.decode(binaryBitmap, hints);
			return result.getText();
		} catch (NotFoundException e) {
			Logger.error(QRCodeUtils.class, "二维码解析错误", e);
		}
		return null;
	}

}