java 识别图片中的二维码
1、pom文件中引入
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>javase</artifactId>
<version>3.2.1</version>
</dependency>
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>3.3.3</version>
</dependency>
2、编写测试类,目前测试采用的是网页中的图片。可以根据需要更改图片存储地址
import com.google.zxing.*;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.common.HybridBinarizer;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
public class QRTest {
public static void main(String[] args) {
System.out.println(deEncodeByPath("https://xyz.bj.bcebos.com/test.JPG"));
}
public static String deEncodeByPath(String path){
String content = null;
BufferedImage image;
URL url = null;
try {
url = new URL(path);
image = ImageIO.read(url);
LuminanceSource source = new BufferedImageLuminanceSource(image);
Binarizer binarizer = new HybridBinarizer(source);
BinaryBitmap binaryBitmap = new BinaryBitmap(binarizer);
Map<DecodeHintType,Object> hints = new HashMap<>();
hints.put(DecodeHintType.CHARACTER_SET,"UTF-8");
Result result = new MultiFormatReader().decode(binaryBitmap,hints);
System.out.println("图片中内容 : " + result.getText());
content = result.getText();
} catch (Exception ex) {
ex.printStackTrace();
}
return content;
}
}