/**
* 生成二维码
* @author Administrator
*
*/
public class CreatQRCode {
public static void main(String[] args) {
// 设置图片的长度和宽度
int width = 300;
int height = 300;
// 图片格式
String format = "png";
// 二维码内容
String contents = "第一个二维码生成" + "\n" + "这是第二行";
try {
// 解决了生成或读取二维码中文乱码问题
contents = new String(contents.getBytes("UTF-8"), "ISO-8859-1");
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
}
// 定义二维码的参数
// HashMap hints = new HashMap();
// hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
// hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
// //边距
// hints.put(EncodeHintType.MARGIN, 2);
// 生成二维码。。。。。QR_CODE格式的。
// MultiFormatWriter()
try {
// 生成矩阵
BitMatrix bitMatrix = new MultiFormatWriter().encode(contents, BarcodeFormat.QR_CODE, width, height);
// 新建二维码存储路径
Path filePath = new File("D:/二维码生成/img.png").toPath();
// 输出图像
MatrixToImageWriter.writeToPath(bitMatrix, format, filePath);
System.out.print("二维码已生成");
} catch (Exception e) {
e.printStackTrace();
}
}
}
目前流行的三大国际标准
PDF417:不支持中文
DM:专利未公开,需支付专利费用
QR code:开源,支持中文
QR code比其他二维码相比,具有识读速度快,数据密度大,占用空间小的优势。
纠错能力:
L级:约可纠错7%的数据码字
M级:约可纠错15%的数据码字
Q级:约可纠错25%的数据码字
H级:约可纠错30%的数据码字
纠错能力越高,存储的数据就越少
/**
* 解析二维码
* @author Administrator
*
*/
public class ReadQRCode {
public static void main(String[] args) {
try {
MultiFormatReader multiFormatReader = new MultiFormatReader();
// 文件路径
File file = new File("D:/二维码生成/img.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 = multiFormatReader.decode(binaryBitmap, hints);
Result result = multiFormatReader.decode(binaryBitmap);
System.out.println("解析结果:"+result.toString());
System.out.println("二维码格式类型:"+result.getBarcodeFormat());
System.out.println("二维码文本内容"+result.getText());
} catch (Exception e) {
e.printStackTrace();
}
}
}
jar包链接:zxing的jar包