背景:
在我们的日常开发中经常会涉及到二维码的生成与解析,这里简单介绍一下二维码的生成与与解析,主要是利用google开发的一套插件,maven版本地址:https://mvnrepository.com/artifact/com.google.zxing/core
一、添加依赖
<!--解析二维码依赖-->
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>javase</artifactId>
<version>3.3.0</version>
</dependency>
<!--生成二维码依赖-->
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>3.3.0</version>
</dependency>
二、代码工具类
public class QRCode {
private static final int BLACK = 0xff000000;
private static final int WHITE = 0xFFFFFFFF;
public static void main(String[] args) {
String localPath = "D:\\qrcode\\"+String.valueOf(System.currentTimeMillis())+".png";
File file = new File(localPath);
//生成二维码
encode("https://blog.csdn.net/hy_coming", file, BarcodeFormat.QR_CODE, 200, 200);
//解析二维码
decode(file);
}
/**
* 生成二维码
*
* @param content
* @param file
* @param format
* @param width
* @param height
*/
private static void encode(String content, File file, BarcodeFormat format, int width, int height) {
try {
content = new String(content.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);
//相关参数设置
Map<EncodeHintType, Object> hints = new HashMap<>(16);
//白边为0
hints.put(EncodeHintType.MARGIN, 0);
BitMatrix bitMatrix = new MultiFormatWriter().encode(content, format, width, height,hints);
writeToFile(bitMatrix, "png", file);
} catch (WriterException | IOException e) {
e.printStackTrace();
}
}
private static void writeToFile(BitMatrix bitMatrix, String format, File file) throws IOException {
BufferedImage image = toBufferImage(bitMatrix);
ImageIO.write(image, format, file);
}
private static BufferedImage toBufferImage(BitMatrix bitMatrix) {
int width = bitMatrix.getWidth();
int height = bitMatrix.getHeight();
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
image.setRGB(x, y, bitMatrix.get(x, y) ? BLACK : WHITE);
}
}
return image;
}
/**
* 解析二维码内容
*
* @param file
*/
private static void decode(File file) {
try {
BufferedImage image = ImageIO.read(file);
if (null == image) {
System.out.println("image is null");
return;
}
LuminanceSource source = new BufferedImageLuminanceSource(image);
BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
Map<DecodeHintType, Object> hints = new HashMap<>();
hints.put(DecodeHintType.CHARACTER_SET, "UTF-8");
Result result = new MultiFormatReader().decode(bitmap, hints);
System.out.println("解析后的内容:" + result);
} catch (IOException | NotFoundException e) {
e.printStackTrace();
}
}
}
三、结果验证
图片:
解析内容:
Connected to the target VM, address: '127.0.0.1:60216', transport: 'socket'
解析后的内容:https://blog.csdn.net/hy_coming
Disconnected from the target VM, address: '127.0.0.1:60216', transport: 'socket'
四、白边问题
在自己的实践过程当中,本地是可以解决白边的问题,只是需要将参数中的margin属性设置为0,但是有一个神奇的问题就是手机上显示的时候总是去除不掉,或者显示的时候总是超出,这个问题我一直没有解决,以后再看吧,给一个参考文章:https://www.cnblogs.com/Marydon20170307/p/9546411.html