最近公司要求扫描二维码和生成二维码的功能。而群里部分网友也提到了。我这里就写了一个demo,和大家分享。代码很简介,希望大家能够喜欢。
网友表示在网上搜索了很多,发现不是代码不全,就是jar不匹配。
我这里共享了一个zxing的2.2版本(支持JDK6)的例子,也提供了下载地址。实现代码如下:
Zxing2.2(支持JDK6) 下载地址:http://download.csdn.net/download/dong707/10210016
package com.herman.test;
import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.util.HashMap; import java.util.Map;
import javax.imageio.ImageIO;
import com.google.zxing.BarcodeFormat; import com.google.zxing.BinaryBitmap; import com.google.zxing.DecodeHintType; import com.google.zxing.EncodeHintType; import com.google.zxing.MultiFormatReader; import com.google.zxing.MultiFormatWriter; import com.google.zxing.NotFoundException; import com.google.zxing.WriterException; import com.google.zxing.client.j2se.BufferedImageLuminanceSource; import com.google.zxing.client.j2se.MatrixToImageWriter; import com.google.zxing.common.HybridBinarizer; import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
public class ZxingUtil { private static final Map<EncodeHintType, ErrorCorrectionLevel> encodeMap = new HashMap<EncodeHintType, ErrorCorrectionLevel>(); private static final Map<DecodeHintType, ErrorCorrectionLevel> decodeMap=new HashMap<DecodeHintType, ErrorCorrectionLevel>(); private static final String charset="UTF-8",format="png"; private static final int size=150; private ZxingUtil() {}
public static void createQRCode(String data, File file) throws WriterException, IOException { MatrixToImageWriter.writeToFile(new MultiFormatWriter().encode( new String(data.getBytes(charset), charset), BarcodeFormat.QR_CODE, size, size, encodeMap), format, file); }
public static String readQRCode(String filePath) throws FileNotFoundException, IOException, NotFoundException { return new MultiFormatReader().decode(new BinaryBitmap(new HybridBinarizer(new BufferedImageLuminanceSource(ImageIO.read(new FileInputStream(filePath))))),decodeMap).getText(); } public static void main(String [] arg){ try{ createQRCode("http://blog.csdn.net/xmtblog", new File("D:\\111.png")); System.out.println(readQRCode("D:\\111.png")); }catch(Exception e){ e.printStackTrace(); } } }
|