pdf中二维码识别的优化方案
博主平常所接触的业务基本都是围绕着各种财票,税票;要知道财税票的查验都需要票据的五要素,而二维码是我们能通过代码直接获取到票据五要素最直接的通道;加上国家推进票据的电子化,未来涉及到电子票据相关业务必然会有通过二维码识别要素信息的场景;废话不多说了,直接上代码。
首先需要引入解析pdf必要的maven依赖
org.apache.pdfbox
pdfbox
2.0.19
通常我们都是把pdf转为图片然后整张去读取二维码,由于图片面积问题偶尔会造成二维码识别失败问题;要知道二维码在pdf文件中就是一张图片,所以我们把pdf中的图片取出来去识别就行了
private static String[] getByQRCodeTryHarder(byte[] bytes) throws IOException {
log.info("bytes.length:{}",bytes.length);
//读取pdf中的图片
// 设置编码字符集
HashMap hints = new HashMap();
hints.put(DecodeHintType.CHARACTER_SET, "utf-8");
hints.put(DecodeHintType.TRY_HARDER, Boolean.TRUE);
hints.put(DecodeHintType.PURE_BARCODE, Boolean.TRUE);
List imageList = new ArrayList();
PDDocument document = null;
document = PDDocument.load(bytes);
//取第一页pdf
PDPage page = document.getPage(0);
PDResources resources = page.getResources();
//解析获取pdf中的图片
for (COSName name : resources.getXObjectNames()){
if (resources.isImageXObject(name)) {
PDImageXObject obj = (PDImageXObject) resources.getXObject(name);
imageList.add(obj.getImage());
}
}
//遍历解析处理图片集合
MultiFormatReader reader = new MultiFormatReader();
for (int i = 0; i < imageList.size(); i++) {
BufferedImage image = imageList.get(i);
Result result = null;
try {
result =reader.decode(new BinaryBitmap(new HybridBinarizer(new BufferedImageLuminanceSource(image))), hints);
}catch (NotFoundException e) {//报此异常表示不是二维码或未识别到,识别下一张
e.printStackTrace();
}
if (null != result && !StringUtils.isEmpty(result.getText())) {
System.out.println(Arrays.toString(result.getText().split(",")));
return result.getText().split(",");
}
}
return null;
}
|