导入依赖
com.google.zxing core 3.3.0 com.google.zxing javase 3.0.0 代码package com.example.qrCodeDemo;
import ch.qos.logback.core.encoder.ByteArrayUtil;
import com.google.zxing.*;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.itextpdf.text.pdf.qrcode.EncodeHintType;
import com.itextpdf.text.pdf.qrcode.ErrorCorrectionLevel;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.nio.file.Path;
import java.util.HashMap;
import static java.awt.Image.SCALE_FAST;
/**
-
@Description: 生成二维码
-
@Author ajin
-
@Version 1.0
-
@Tool: IntelliJ IDEA
*/
public class GenerateQRCodeUtil {private static final int width = 300; //定义图片宽度
private static final int height = 300; //定义图片高度
private static final String format = “png”; //定义图片格式/**
- @Author: ajin
- @Description: 生成二维码到本地
*/
public static void generateQRCode(String targetPath, String content) {
//定义二维码的参数
HashMap hashMap = new HashMap();
hashMap.put(EncodeHintType.CHARACTER_SET, “utf-8”); //设置编码
hashMap.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L); //设置容错等级,等级越高,容量越小
//生成二维码
try {
//生成矩阵
//内容格式宽高
BitMatrix bitMatrix = new MultiFormatWriter().encode(content,
BarcodeFormat.QR_CODE //二维码类型
, width, height, hashMap);
Path file = new File(targetPath).toPath();//设置路径
MatrixToImageWriter.writeToPath(bitMatrix, format, file);//输出图像
} catch (Exception e) {
e.printStackTrace();
}
}
/**
- @Author: ajin
- @Description: 解析二维码内容
/
public static void parseQRCode(String rootPath) {
try {
/
* MultiFormatReader 多格式读取
* /
MultiFormatReader formatReader = new MultiFormatReader();
File file = new File(rootPath);
//读取图片buffer中
BufferedImage bufferedImage = ImageIO.read(file);
/
* BinaryBitmap 二进制位图
* HybridBinarizer 混合二值化器
* BufferedImageLuminanceSource 图像缓存区 亮度 资源
* */
BinaryBitmap binaryBitmap = new BinaryBitmap(new HybridBinarizer(new BufferedImageLuminanceSource(bufferedImage)));
//定义二维码参数
HashMap hashMap = new HashMap();
hashMap.put(EncodeHintType.CHARACTER_SET, “utf-8”);//编码方式
// hashMap.put(BarcodeFormat.QR_CODE, “CODE_128”);//二维码类型
//hashMap.put(DecodeHintType.TRY_HARDER, Boolean.TRUE);//优化精度
//hashMap.put(DecodeHintType.PURE_BARCODE, Boolean.TRUE);//复杂模式,开启PURE_BARCODE模式
Result result = formatReader.decode(binaryBitmap, hashMap);
System.out.println(“二维码类型:” + result.getBarcodeFormat());//BarcodeFormat 条形码格式
System.out.println(“二维码文本内容:” + result.getText());
} catch (Exception e) {
e.printStackTrace();
}
}
}