QRCode二维码生成

使用开源google.zxing

依赖jar包:core-3.3.1.jar,javase-3.3.1.jar

 

http://mvnrepository.com/artifact/com.google.zxing/core/3.3.1

http://mvnrepository.com/artifact/com.google.zxing/javase/3.3.1

 

public class QRCodeUtil {

	/**
	 * 生成二维码
	 * @param outputStream
	 * @param content
	 * @param size
	 * @param imageFormat
	 * @return
	 * @throws Exception
	 */
	public static boolean generateQRCode(OutputStream outputStream,String content, int size, String imageFormat)
					throws Exception {
		Hashtable<EncodeHintType, Object> hintMap = new Hashtable<EncodeHintType, Object>();
		hintMap.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);
		hintMap.put(EncodeHintType.MARGIN,0);
		QRCodeWriter qrCodeWriter = new QRCodeWriter();
		BitMatrix byteMatrix = qrCodeWriter.encode(content,BarcodeFormat.QR_CODE, size, size,hintMap);
		MatrixToImageWriter.writeToStream(byteMatrix, imageFormat, outputStream);
		return true;
	}
	
	/**
	 * 识别二维码
	 * @param file
	 * @return
	 * @throws Exception
	 */
	public static String recogniseQRCode(File file) throws Exception{
		String contents = null;

		MultiFormatReader formatReader = new MultiFormatReader();

		BufferedImage image;
		try {
			image = ImageIO.read(file);
			LuminanceSource source = new BufferedImageLuminanceSource(image);
			Binarizer binarizer = new HybridBinarizer(source);
			BinaryBitmap binaryBitmap = new BinaryBitmap(binarizer);

			Map<DecodeHintType, Object> hints = new HashMap<DecodeHintType, Object>();
			hints.put(DecodeHintType.CHARACTER_SET, "UTF-8");

			com.google.zxing.Result result = formatReader.decode(binaryBitmap, hints);
			contents = result.toString();
			
		} catch (Exception e) {
			e.printStackTrace();
		}

		return contents;
	}
	public static void main(String[] args) {
		String contents = "bacd";
		try {
			File file = new File("E:/temp/qrcode.jpg");
//			OutputStream os = new FileOutputStream(file);
//			generateQRCode(os, contents,200, "jpg");
			System.out.println(recogniseQRCode(file));
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
		
	}
	
	
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值