Java 识别读取pdf中的二维码信息

本文章内容

通过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;
    }
  • 5
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值