准备工作
zxing包似乎没有提供相关的Jar包下载,那么我们首先来编译生成zxing的Jar包。
下载源码
<i class="fa fa-github"></i>zxing
新建Module
在IDEA中新建Module,并把zxing的core源码拷贝进去,javase的源码也要拷贝进去
编译Jar包
打开Project Structure,选择Artifacts,选择相应的Path,勾选上Include In Project,如图所示:
最后右键zxing这个Module,选择build即可在相应的Path下找到编译好的Jar包
生成二维码
public static void WriteQRcode(String content, File file) {
try {
MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
int width = 400;
int height = 400;
Map hints = new HashMap();
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
BitMatrix bitMatrix = multiFormatWriter.encode(content, BarcodeFormat.QR_CODE, width, height, hints);
Path path = file.toPath();
MatrixToImageWriter.writeToPath(bitMatrix, "jpg", path);
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
识别二维码
public static void ReadQRcode(File file) {
try {
MultiFormatReader multiFormatReader = new MultiFormatReader();
BufferedImage image = ImageIO.read(file);
LuminanceSource source = new BufferedImageLuminanceSource(image);
Binarizer binarizer = new HybridBinarizer(source);
BinaryBitmap binaryBitmap = new BinaryBitmap(binarizer);
Map hints = new HashMap();
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
Result result = multiFormatReader.decode(binaryBitmap, hints);
System.out.println("result: " + result.toString());
System.out.println("resultFormat: " + result.getBarcodeFormat());
System.out.println("resultText: " + result.getText());
} catch (IOException e) {
e.printStackTrace();
} catch (NotFoundException e) {
e.printStackTrace();
}
}
网友评论