今天有一个需求就是生成二维码。大概百度了下有好几种方式
最后我选择了用zxing来生成
生成二维码代码
public class CreateQRcode {
public static void main(String[] args) {
int width = 300;//宽
int height = 300;//高
String format = "png";//图片格式
String contents = "My name is Xiaofeng Dong(我的名字叫董晓峰)";
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(contents, BarcodeFormat.QR_CODE, width, height, hints);
Path file = new File("F:/app/QRcode.png").toPath();
MatrixToImageWriter.writeToPath(BitMatrix, format, file);
} catch (Exception e) {
e.printStackTrace();
}
}
}
读取二维码
public class ReadQRcode {
public static void main(String[] args) {
HashMap hints = new HashMap();
hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
hints.put(EncodeHintType.ERROR_CORRECTION,ErrorCorrectionLevel.M);
hints.put(EncodeHintType.MARGIN, 2);
try {
MultiFormatReader formatReader = new MultiFormatReader();
File file = new File("F:/app/QRcode.png");
BufferedImage image = ImageIO.read(file);
BinaryBitmap binaryBitmap = new BinaryBitmap(new HybridBinarizer(new BufferedImageLuminanceSource(image)));
Result result = formatReader.decode(binaryBitmap,hints);
System.out.println("getTimestamp!"+result.getTimestamp());
System.out.println("getBarcodeFormat!"+result.getBarcodeFormat());
System.out.println("toString!"+result.toString());
System.out.println("getTimestamp!"+result.getText());
} catch (Exception e) {
e.printStackTrace();
}
}
}
最后附上我下载好的jar包
点击下载 -zxing.jar