java 二维码生成和解析

460 阅读2分钟
<!-- 二维码   -->
		<dependency>
			<groupId>com.google.zxing</groupId>
			<artifactId>javase</artifactId>
			<version>3.3.0</version>
		</dependency>

package com.hxkj.springboot.core.utils;

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.geom.RoundRectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Hashtable;

import javax.imageio.ImageIO;

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.Result;
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;

public class QrCodeUtils {

	/**
	 * @Title: encodeQrCode
	 * @Description: zixing普通二维码生成
	 * @param content
	 *            二维码内容
	 * @param prePath
	 *            保存路径前缀
	 * @param qrCodeName
	 *            二维码文件保存名称
	 * @return
	 * @return String
	 * @author huzhihui_c@qq.com
	 * @date 2016年10月10日 上午10:55:54
	 */
	public static String encodeQrCode(String content, String prePath, String qrCodeName) {
		try {
			int width = 300; // 二维码图片宽度
			int height = 300; // 二维码图片高度
			String format = "png";// 二维码的图片格式

			Hashtable<EncodeHintType, String> hints = new Hashtable<EncodeHintType, String>();
			hints.put(EncodeHintType.CHARACTER_SET, "utf-8"); // 内容所使用字符集编码
			hints.put(EncodeHintType.MARGIN, "2");
			BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height, hints);
			// 生成二维码
			Path path = Paths.get(prePath, qrCodeName);
			MatrixToImageWriter.writeToPath(bitMatrix, format, path);
			System.out.println("success:-------------------生成二维码成功");
		} catch (Exception e) {
			System.out.println("error:-------------------生成二维码失败" + e.getMessage());
			return null;
		}
		return qrCodeName;
	}

	/**
	 * @Title: decodeQrCode
	 * @Description: zixing二维码解析
	 * @param qrCodeUrl
	 * @return
	 * @return String
	 * @author huzhihui_c@qq.com
	 * @date 2016年10月10日 上午11:35:21
	 */
	public static String decodeQrCode(String qrCodeUrl) {
		String retStr = "";
		try {
			BufferedImage bufferedImage = ImageIO.read(new FileInputStream(qrCodeUrl));
			LuminanceSource source = new BufferedImageLuminanceSource(bufferedImage);
			Binarizer binarizer = new HybridBinarizer(source);
			BinaryBitmap bitmap = new BinaryBitmap(binarizer);
			HashMap<DecodeHintType, Object> hintTypeObjectHashMap = new HashMap<>();
			hintTypeObjectHashMap.put(DecodeHintType.CHARACTER_SET, "UTF-8");
			Result result = new MultiFormatReader().decode(bitmap, hintTypeObjectHashMap);
			retStr = result.getText();
			System.out.println("success:-------------------二维码解析成功");
		} catch (Exception e) {
			System.out.println("error:-------------------二维码解析失败" + e.getMessage());
		}
		return retStr;
	}

	/**
	 * @Title: encodeLogoQrCode 
	 * @Description:     生成带logo的二维码
	 * @param content
	 * @param prePath
	 * @param qrCodeName
	 * @param logoPath
	 * @return   
	 * @return String    
	 * @author huzhihui_c@qq.com
	 * @date 2016年10月10日 下午1:23:22
	 */
	public static String encodeLogoQrCode(String content, String prePath, String qrCodeName, String logoPath) {
		try {
			// 基本二维码生成
			int width = 300; // 二维码图片宽度
			int height = 300; // 二维码图片高度
			String format = "png";// 二维码的图片格式

			Hashtable<EncodeHintType, String> hints = new Hashtable<EncodeHintType, String>();
			hints.put(EncodeHintType.CHARACTER_SET, "utf-8"); // 内容所使用字符集编码
			hints.put(EncodeHintType.MARGIN, "2");
			BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height, hints);

			BufferedImage bufferQrCodeImage = MatrixToImageWriter.toBufferedImage(bitMatrix);// 普通二维码的图片流
			BufferedImage bufferLogoImage = ImageIO.read(new File(logoPath));// logo文件
			Graphics2D g2 = bufferQrCodeImage.createGraphics();
			int matrixWidth = bufferQrCodeImage.getWidth();
			int matrixHeigh = bufferQrCodeImage.getHeight();
			g2.drawImage(bufferLogoImage, matrixWidth / 5 * 2, matrixHeigh / 5 * 2, matrixWidth / 5, matrixHeigh / 5,null);// logo绘制
			BasicStroke stroke = new BasicStroke(5, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND);
			g2.setStroke(stroke);// 设置笔画对象
			// 指定弧度的圆角矩形
			RoundRectangle2D.Float round = new RoundRectangle2D.Float(matrixWidth / 5 * 2, matrixHeigh / 5 * 2,matrixWidth / 5, matrixHeigh / 5, 20, 20);
			g2.setColor(Color.white);
			g2.draw(round);// 绘制圆弧矩形

			// 设置logo 有一道灰色边框
			BasicStroke stroke2 = new BasicStroke(1, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND);
			g2.setStroke(stroke2);// 设置笔画对象
			RoundRectangle2D.Float round2 = new RoundRectangle2D.Float(matrixWidth / 5 * 2 + 2, matrixHeigh / 5 * 2 + 2,
					matrixWidth / 5 - 4, matrixHeigh / 5 - 4, 20, 20);
			g2.setColor(new Color(128, 128, 128));
			g2.draw(round2);// 绘制圆弧矩形

			g2.dispose();
			bufferQrCodeImage.flush();
			ImageIO.write(bufferQrCodeImage, format, new File(prePath+qrCodeName));
			System.out.println("success:-------------------生成带logo二维码成功");
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("error:-------------------生成带logo二维码失败" + e.getMessage());
		}

		return "";
	}

	public static void main(String[] args) {
		encodeLogoQrCode("nihao a ","D:/","aaa.jpg","D:/logo.jpg");
	}
}