mavn pom.xml
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>javase</artifactId>
<version>3.5.3</version>
</dependency>
java 测试类
java
import com.google.zxing.BinaryBitmap;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.NotFoundException;
import com.google.zxing.Result;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
public class QRCodeReader {
public static String decodeQRCode(String filePath) {
try {
BufferedImage bufferedImage = ImageIO.read(new File(filePath));
BinaryBitmap binaryBitmap = new BinaryBitmap(new HybridBinarizer(new BufferedImageLuminanceSource(bufferedImage)));
Result result = new MultiFormatReader().decode(binaryBitmap);
return result.getText();
} catch (NotFoundException e) {
System.err.println("No QR code found in the image.");
} catch (IOException e) {
System.err.println("Error reading the image file: " + e.getMessage());
}
return null;
}
public static void main(String[] args) {
String filePath = QRCodeReader.class.getResource("/861393067237070.png").getPath();
String qrCodeText = decodeQRCode(filePath);
if (qrCodeText != null) {
System.out.println("Decoded QR Code: " + qrCodeText);
} else {
System.out.println("Failed to decode QR code.");
}
}
}
重点关注:
main方法