使用zxing生成二维码,会比较简单。很适合初学者学习。
这是用QR Code生成和解析二维码文章地址:https://blog.csdn.net/qq_41879385/article/details/81429376
使用jQuery制作带Logo的二维码:https://blog.csdn.net/qq_41879385/article/details/81625354
package com.code;
import java.io.File;
import java.nio.file.Path;
import java.util.HashMap;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
/**
*
* @author 谢财盛
* 文件名:QRcode.java
* 时间日期:2018年7月29日下午11:10:04
* 作用:TODO
* 版本号:1.0
*/
public class Zxing {
public static void main(String[] args) {
int width = 500; //设置二维码宽
int height = 500; //设置二维码高
String format = "png"; //二维码的格式
String conten = "www.baidu.com"; //二维码的内容(可以是文字)
//定义二维码参数
HashMap hamp = new HashMap();
hamp.put(EncodeHintType.CHARACTER_SET,"utf-8");
hamp.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
hamp.put(EncodeHintType.MARGIN,2);
try {
BitMatrix bitMatrix = new MultiFormatWriter().encode(conten, BarcodeFormat.QR_CODE, width, height,hamp);
Path file = new File("D:/code/img1.png").toPath();
MatrixToImageWriter.writeToPath(bitMatrix, format, file);
} catch (Exception e) {
e.printStackTrace();
}
}
}
注意:如果报错java.io.FileNotFoundException: D:\abc\img1.png (系统找不到指定的路径。)。说明在你的这个盘里面没有这个文件,所以再执行这个main之前,要去D盘先建一个code文件夹。
接下来实现使用zxing来解析二维码:
package com.code;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import javax.imageio.ImageIO;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.NotFoundException;
import com.google.zxing.Result;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.common.HybridBinarizer;
public class ReadZxing {
public static void main(String[] args) {
try {
MultiFormatReader formatReader = new MultiFormatReader();
File file = new File("D:/code/img1.png"); //这个是上面我们生成的二维码的路径
BufferedImage image = ImageIO.read(file);
BinaryBitmap binaryBitmap = new BinaryBitmap(new HybridBinarizer(new BufferedImageLuminanceSource(image)));
//定义二维码参数
HashMap hints = new HashMap();
hints.put(EncodeHintType.CHARACTER_SET,"utf-8");
Result result = formatReader.decode(binaryBitmap, hints);
System.out.println("解析结果:"+result.toString());
System.out.println("二维码格式类型:"+result.getBarcodeFormat());
System.out.println("二维码文本内容:"+result.getText());
} catch (NotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
运行类,结果:
二维码内容是www.baidu.com,文字也可以。
推荐以下这两篇文章,非常好,是个很好的学习资料,
二维码的生成细节和原理https://coolshell.cn/articles/10590.html
java——基于zxing的二维码生成器https://www.jianshu.com/p/7ae3b7002530
这两篇都非常的不错,推荐大家去看看,对二维码更深一层的了解。