前两个jar :http://mvnrepository.com/artifact/com.google.zxing
import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import javax.imageio.ImageIO;
import com.google.zxing.Binarizer;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.DecodeHintType;
import com.google.zxing.LuminanceSource;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.NotFoundException;
import com.google.zxing.Result;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.common.HybridBinarizer;
/**
* 解析二维码,使用google的zxing javase-2.2.jar core-2.2.jar
* @Title: decode
* @Description: TODO(这里用一句话描述这个方法的作用)
* @param @param filepath
* @param @return
* @param @throws IOException
* @param @throws NotFoundException 设定文件
* @return String 返回类型
* 修改人:liuming
* 修改时间:2017-11-9 下午3:14:29
* @throws
*/
public static String decode(String filepath) throws IOException,
NotFoundException {
try {
// if(!imgFile.isFile()){
// System.out.println("输入非文件");
// return null;
// }
HttpURLConnection httpUrl = null;
URL url = new URL(filepath);
httpUrl = (HttpURLConnection) url.openConnection();
httpUrl.connect();
BufferedInputStream bis = new BufferedInputStream(httpUrl.getInputStream());
BufferedImage bufferedImage = ImageIO.read(bis);
// BufferedImage bufferedImage = ImageIO.read(new FileInputStream(
// filepath));
LuminanceSource source = new BufferedImageLuminanceSource(
bufferedImage);
Binarizer binarizer = new HybridBinarizer(source);
BinaryBitmap bitmap = new BinaryBitmap(binarizer);
HashMap<DecodeHintType, Object> decodeHints = new HashMap<DecodeHintType, Object>();
decodeHints.put(DecodeHintType.CHARACTER_SET, "UTF-8");
Result result = new MultiFormatReader().decode(bitmap, decodeHints);
System.out.println(result);
return result.getText();
} catch (NotFoundException e) {
System.out.println("二维码解析NotFoundException");
e.printStackTrace();
} catch (IOException e) {
System.out.println("二维码解析IOException");
e.printStackTrace();
}
return null;
}