前言
后端识别二维码图片
代码
- 引入依赖
<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>
- 编写工具类
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.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;public class QrUtil {public static String qrToText(File file) throws IOException {BufferedImage read = ImageIO.read(file);String s = qrToText(read);return s;}public static String qrToText(String url) throws IOException {URL u = new URL(url);BufferedImage read = ImageIO.read(u);String s = qrToText(read);return s;}public static String qrToText(InputStream inputStream) throws IOException {BufferedImage read = ImageIO.read(inputStream);String s = qrToText(read);return s;}public static String qrToText(BufferedImage bufferedImage) {String content = null;try {LuminanceSource source = new BufferedImageLuminanceSource(bufferedImage);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);content = result.getText();} catch (Exception ex) {ex.printStackTrace();}return content;}
}
- 测试用例(qrtest.png为待解析的二维码),然后运行
@Testpublic void testQr() throws IOException {String str = QrUtil.qrToText(new File("C:\\test\\qrtest.png"));System.out.println(str);}