本文章内容
通过Java程序识别、读取二维码存储的信息。
前言
在实际开发过程中,会因为各种业务需求,导致需通过程序识别二维码信息内容。并根据读取到的内容结合相应业务来做不一样的操作。
步骤
1、把pdf转成图片格式,因为只能识别png或jpg等图片文件中的二维码。下面以png格式为例,代码如下:
/**
* pdf 转 png
*/
public void pdfFileToImage() {
//pdf文件
File pdffile = new File("D:/test.pdf");
// 转成的 png 文件存储全路径及文件名
String targetPath = "D:/test.png";
try {
FileInputStream instream = new FileInputStream(pdffile);
InputStream byteInputStream = null;
try {
PDDocument doc = PDDocument.load(instream);
PDFRenderer renderer = new PDFRenderer(doc);
int pageCount = doc.getNumberOfPages();
if (pageCount > 0) {
BufferedImage image = renderer.renderImage(0, 2.0f);
image.flush();
ByteArrayOutputStream bs = new ByteArrayOutputStream();
ImageOutputStream imOut;
imOut = ImageIO.createImageOutputStream(bs);
ImageIO.write(image, "png", imOut);
byteInputStream = new ByteArrayInputStream(bs.toByteArray());
byteInputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
File uploadFile = new File(targetPath);
FileOutputStream fops;
fops = new FileOutputStream(uploadFile);
fops.write(readInputStream(byteInputStream));
fops.flush();
fops.close();
} catch (Exception e) {
e.printStackTrace();
}
}
private static byte[] readInputStream(InputStream inStream) throws Exception {
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while ((len = inStream.read(buffer)) != -1) {
outStream.write(buffer, 0, len);
}
inStream.close();
return outStream.toByteArray();
}
2、识别png图片中的二维码信息。代码如下:
/**
* 识别 png图片中的二维码信息
*/
public String extractImages() throws IOException, DocumentException {
String filename = "D:/test.png";
String returnResult = "";
MultiFormatReader multiFormatReader = new MultiFormatReader();
File file = new File(filename);
BufferedImage image = ImageIO.read(file);
// 定义二维码参数
Map hints = new HashMap();
hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
// 获取读取二维码结果
BinaryBitmap binaryBitmap = new BinaryBitmap(new HybridBinarizer(new BufferedImageLuminanceSource(image)));
Result result = null;
try {
result = multiFormatReader.decode(binaryBitmap, hints);
returnResult = result.getText();
} catch (NotFoundException e) {
e.printStackTrace();
}
return returnResult;
}