JAVA使用com.google.zxing生成二维码和解析二维码案例
1. 需要使用到的xml配置
<!-- 二维码工具 -->
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>3.3.3</version>
</dependency>
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>javase</artifactId>
<version>3.3.3</version>
</dependency>
2. 生成二维码
public class test {
public static boolean createQrCode(OutputStream outputStream, String content) throws WriterException, IOException{
Hashtable hintMap = new Hashtable();
hintMap.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);
hintMap.put(EncodeHintType.CHARACTER_SET, "UTF-8");
QRCodeWriter qrCodeWriter = new QRCodeWriter();
BitMatrix byteMatrix = qrCodeWriter.encode(content, BarcodeFormat.QR_CODE, 900, 900, hintMap);
int matrixWidth = byteMatrix.getWidth();
BufferedImage image = new BufferedImage(matrixWidth-200, matrixWidth-200, BufferedImage.TYPE_INT_RGB);
image.createGraphics();
Graphics2D graphics = (Graphics2D) image.getGraphics();
graphics.setColor(Color.WHITE);
graphics.fillRect(0, 0, matrixWidth, matrixWidth);
graphics.setColor(Color.BLACK);
for (int i = 0; i < matrixWidth; i++){
for (int j = 0; j < matrixWidth; j++){
if (byteMatrix.get(i, j)){
graphics.fillRect(i-100, j-100, 1, 1);
}
}
}
return ImageIO.write(image, "JPEG", outputStream);
}
public static void main(String[] args) throws IOException, WriterException {
OutputStream out = new FileOutputStream(new File("C:\\Users\\Administrator\\Desktop\\123456.png"));
String content = "HELLO CDSDN";
createQrCode(out,content);
}
}
3. 解析二维码
public class test2{
public static void getResult(String path) {
try {
BufferedImage image3 = ImageIO.read(new File(path));
LuminanceSource source = new BufferedImageLuminanceSource(image3);
BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
QRCodeMultiReader reader = new QRCodeMultiReader();
Result[] results = reader.decodeMultiple(bitmap);
System.out.println();
} catch (IOException | NotFoundException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
String path = "D:\\Users\\27532\\Desktop\\ee.png";
getResult(path);
}
}