本实例使用的是google的zxing工具
先导包:
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>3.3.0</version>
</dependency>
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>javase</artifactId>
<version>3.3.0</version>
</dependency>
生成二维码
public static void main(String[] args) throws WriterException, IOException {
/** 定义Map集合封装二维码配置信息 */
Map<EncodeHintType, Object> hints = new HashMap<>();
/** 设置二维码图片的内容编码 */
hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
/** 设置二维码图片的上、下、左、右间隙 */
hints.put(EncodeHintType.MARGIN, 1);
/** 设置二维码的纠错级别 */
hints.put(EncodeHintType.ERROR_CORRECTION,
ErrorCorrectionLevel.H);
/**
* 创建二维码字节转换对象
* 第一个参数:二维码图片中的内容
* 第二个参数:二维码格式器
* 第三个参数:生成二维码图片的宽度
* 第四个参数:生成二维码图片的高度
* 第五个参数:生成二维码需要配置信息
* */
BitMatrix matrix = new
MultiFormatWriter().encode("https://www.baidu.com",
BarcodeFormat.QR_CODE, 600, 600, hints);
/** 获取二维码图片真正的宽度 */
int matrix_width = matrix.getWidth();
/** 获取二维码图片真正的高度 */
int matrix_height = matrix.getHeight();
/** 定义一张空白的缓冲流图片 */
BufferedImage image = new
BufferedImage(matrix_width, matrix_height,
BufferedImage.TYPE_INT_RGB);
/** 把二维码字节转换对象 转化 到缓冲流图片上 */
for (int x = 0; x < matrix_width; x++){
for (int y = 0; y < matrix_height; y++){
/** 通过x、y坐标获取一点的颜色 true: 黑色 false: 白色 */
int rgb = matrix.get(x, y) ? 0xFF000000 : 0xFFFFFF;
image.setRGB(x, y, rgb);
}
}
File file = new File("C:\\Users\\gqs_1145511747719778\\Desktop\\test.jpg");
ImageIO.write(image,"jpg",file);
}
解析二维码
public void read(){
File file = new File("C:\\Users\\gqs_1145511747719778\\Desktop\\test.jpg");
BufferedImage bufferedImage = null;
try {
bufferedImage = ImageIO.read(file);
} catch (IOException e) {
e.printStackTrace();
}
LuminanceSource source = new BufferedImageLuminanceSource(bufferedImage);
BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
Hashtable<DecodeHintType, String> hints = new Hashtable<DecodeHintType, String>();
hints.put(DecodeHintType.CHARACTER_SET, "utf-8");
Result result = null;
try {
result = new MultiFormatReader().decode(bitmap, hints);
} catch (NotFoundException e) {
e.printStackTrace();
}
System.out.println(result.toString());
//return result.toString();
}