JAVA使用com.google.zxing生成二维码和解析二维码案例
1. 需要使用到的xml配置
com.google.zxing
core
3.3.3
com.google.zxing
javase
3.3.3
2. 生成二维码
public class test {
public static boolean createQrCode(OutputStream outputStream, String content) throws WriterException, IOException{
//设置二维码纠错级别MAP
Hashtable hintMap = new Hashtable();
hintMap.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L); // 矫错级别
//设置UTF-8, 防止中文乱码
hintMap.put(EncodeHintType.CHARACTER_SET, "UTF-8");
//设置二维码四周白色区域的大小
//hintMap.put(EncodeHintType.MARGIN,0);
QRCodeWriter qrCodeWriter = new QRCodeWriter();
//创建比特矩阵(位矩阵)的QR码编码的字符串
BitMatrix byteMatrix = qrCodeWriter.encode(content, BarcodeFormat.QR_CODE, 900, 900, hintMap);
// 使BufferedImage勾画QRCode (matrixWidth 是行二维码像素点)
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);
}
}