利用JAVA生成二维码

时间:2021-02-14 19:53:51

本文章整理于慕课网的学习视频《JAVA生成二维码》,如果想看视频内容请移步慕课网

*上对于二维码的解释.

二维条码是指在一维条码的基础上扩展出另一具有可读性的条码,使用黑白矩形图案表示二进制数据,被设备扫描后可获取其中所包含的信息。一维条码的宽度记载着数据,而其长度没有记载数据。二维条码的长度、宽度均记载着数据。二维条码有一维条码没有的“定位点”和“容错机制”。容错机制在即使没有辨识到全部的条码、或是说条码有污损时,也可以正确地还原条码上的信息。


利用JAVA生成QR Code格式的二维码

 相关jar包下载地址(ZXing.jar)。

public class CreateQRCode {

    /**
* @param args
*/
public static void main(String[] args) {
//设定二维码宽高,类型,二维码要展示的内容。
int width = 300;
int height = 300;
String format = "png";
String content = "https://www.baidu.com/";
//定义二维码参数(格式,错误等级)
HashMap hints = new HashMap();
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
hints.put(EncodeHintType.ERROR_CORRECTION,ErrorCorrectionLevel.M);
hints.put(EncodeHintType.MARGIN,2); try {
BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height);
// 二维码生成路径
Path file = new File("D:/code/img.png").toPath();
MatrixToImageWriter.writeToPath(bitMatrix, format, file);
} catch (Exception e) {
e.printStackTrace();
}
}
}

利用JAVA解析二维码

public class ReadQRCode {

    /**
* @param args
*/
public static void main(String[] args) {
MultiFormatReader formatReader = new MultiFormatReader();
// 二维码路径
File file = new File("D:/code/img.png");
BufferedImage image;
try {
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 (IOException | NotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} }