java 生成二维码

package com.alone.web.utils;

import java.awt.image.BufferedImage;
import java.io.File;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;
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.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;

/**
 * 二维码
 * 
 * @author 程新井
 *
 */
public class QRCodeUtils {

	/**
	 * 二维码生成器
	 * 
	 * @param content
	 *            生成二维码的内容
	 * @param width
	 *            二维码的宽度
	 * @param height
	 *            二维码高度
	 * @param format
	 *            二维码 图片格式
	 * @return
	 */
	public static final BufferedImage getQRCode(String content, int width, int height, String format) {
		
		Hashtable hints = new Hashtable();
		hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
		BitMatrix bitMatrix = null;
		try {
			// 对内容进行编码
			bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height, hints);
		} catch (WriterException e1) {
			e1.printStackTrace();
		}
		// 输出二维码图片
		BufferedImage image = MatrixToImageWriter.toBufferedImage(bitMatrix);
		return image;
	}

	/**
	 * 二维码解析器
	 * 
	 * @param path
	 *            二维码图片的路径
	 * @return 二维码的内容
	 */
	public static final String deQRCode(String path) {
		// 二维码图片路径
		File imageFile = new File(path);
		BufferedImage image = null;
		Result result = null;
		try {
			image = ImageIO.read(imageFile);
			LuminanceSource source = new BufferedImageLuminanceSource(image);
			Binarizer binarizer = new HybridBinarizer(source);
			BinaryBitmap binaryBitmap = new BinaryBitmap(binarizer);
			Map hints = new HashMap();
			hints.put(DecodeHintType.CHARACTER_SET, "UTF-8");
			// 解码获取二维码中信息
			result = new MultiFormatReader().decode(binaryBitmap, hints);
		} catch (Exception e) {
			e.getStackTrace();
		}
		return result.getText();
	}
}

你可能感兴趣的:(java)