QR Code or Quick Response Code is a two dimensional barcode that can be read by modern smartphones and special QR Code scanner devices. Most QR Codes consist of black squares arranged in a square grid on a white backgroundThere are several types of QR codes depending on their symbol size, layout, encoding and structure.
QR Codes can contain data like - simple text, urls, phone numbers, sms, geolocation, email address etc.
How to read QR Code in Java?
Let's use following image as sample QR code.
We can easily read the above QR codes in Java using Google's ZXing library, as shown in below code.
ReadQRCodeZXing.java
package com.blogspot.devnip.qrcode;
import com.google.zxing.BinaryBitmap;
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;
import javax.imageio.ImageIO;
import java.io.File;
import java.io.IOException;
/**
* Read QR code from an image file using Google's ZXing library
*/
public class ReadQRCodeZXing {
public static String readFile(File file) {
try {
BinaryBitmap bitmap = new BinaryBitmap(
new HybridBinarizer(
new BufferedImageLuminanceSource(ImageIO.read(file))));
Result result = new MultiFormatReader().decode(bitmap);
return result.getText();
} catch (NotFoundException | IOException e) {
e.printStackTrace();
return null;
}
}
}
The results can be verified using below test.
ReadQRCodeZXingTest.java
package com.blogspot.devnip.qrcode;
import org.junit.jupiter.api.Test;
import java.io.File;
import java.net.URL;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
class ReadQRCodeZXingTest {
@Test
void test() {
URL url = ReadQRCodeZXingTest.class.getResource("/qrcode/qrcode.png");
assertNotNull(url);
assertEquals("https://devnip.blogspot.com/", ReadQRCodeZXing.readFile(new File(url.getFile())));
}
}
0 comments:
Post a Comment