gpt4 book ai didi

java - 扫描 PDF 并转换为缓冲图像以解码 QR 时出现 Zxing 格式异常

转载 作者:行者123 更新时间:2023-11-30 11:05:34 25 4
gpt4 key购买 nike

我在 PDF 转换后连续成功解码 QR 时遇到问题。我不断得到,

"Exception in thread "main" com.google.zxing.FormatException."

我的转换尝试是在以下时间完成的:PDF框

public static BufferedImage convertPDFtoBufferedImageType2(String PDFPath) throws IOException{

PDDocument document = null;
try {

document = PDDocument.load(PDFPath);
PDPage firstPage = (PDPage) document.getDocumentCatalog().getAllPages().get(0);
return firstPage.convertToImage();

} catch (IOException ex) {
Logger.getLogger(PDF_Utility.class.getName()).log(Level.SEVERE, null, ex);
return null;
} finally {
if(document != null)
document.close();
}
}

第二次尝试使用 ghost4j

public static BufferedImage convertPDFtoBufferedImage(String PDFPath) throws IOException, RendererException, DocumentException{

System.setProperty("jna.library.path", "C:\\Program Files\\gs\\gs9.16\\bin\\");

PDFDocument document = new PDFDocument();
document.load(new File(PDFPath));
SimpleRenderer renderer = new SimpleRenderer();
renderer.setResolution(300);
List<Image> imgs = renderer.render(document);
Image im = imgs.get(0);

BufferedImage bi = new BufferedImage
(im.getWidth(null),im.getHeight(null),BufferedImage.TYPE_INT_RGB);
Graphics bg = bi.getGraphics();
bg.drawImage(im, 0, 0, null);
bg.dispose();
return bi;
}

我的二维码解码器是:

public static String readQRCode(BufferedImage image, String charset, Map hintMap) 
throws FileNotFoundException, IOException, NotFoundException, ChecksumException, FormatException {
Result qrCodeResult = null;
BinaryBitmap binaryBitmap = new BinaryBitmap(
new HybridBinarizer(new BufferedImageLuminanceSource(image)));
try{
qrCodeResult = new com.google.zxing.qrcode.QRCodeReader().decode(binaryBitmap,hintMap);
}catch(NotFoundException | FormatException e){ //attempt without hints
qrCodeResult = new com.google.zxing.qrcode.QRCodeReader().decode(binaryBitmap);
}
return qrCodeResult.getText();
}

我两次调用 decode 的原因是因为有时“更努力”

hintMap.put(DecodeHintType.TRY_HARDER, Boolean.TRUE);

实际上没有抓到二维码,但是默认抓到了。无论如何,这些代码片段确实从一堆文档中捕获了我的大部分 QR 扫描,但有时它根本没有捕获到它。我什至尝试将其写成图像,然后重新读入:

ImageIO.write((RenderedImage) im, "png", new File("/path/to/my/img.png"));

有趣的是,http://zxing.org/w/decode.jspx确实解码了输出图像,但我的代码不能。我也尝试了不同的字符集:CHAR_SET = "UTF-8";和 CHAR_SET = "ISO-8859-1";

通过获取格式异常,找到了代码,但“不符合条形码的格式规则。这可能是由于误检测。”

为困惑的代码道歉,但这些尝试已经获得了大部分成功的扫描。 9/10 率?有趣的是,有时同一文档的另一份扫描件也能奏效。感谢任何帮助/建议/疯狂的巫术组合!谢谢!

编辑:我得到了一个样本(在去掉周围的内容之后。真正的图像有内容!Zxing 网站也能够捕获这个 QR 码(有和没有内容!(我的程序已经忽略了其他 1Ds格式和内容)。 QR Code

最佳答案

@Tilman Hausherr 指出 PDFBox 默认渲染大小很低,所以我按照他的建议将默认值更改为 300dpi。总的来说,它适用于我的情况,但肯定会降低速度。将需要调整我的算法以同时运行一个快速的和这个较慢的算法作为备份。

return firstPage.convertToImage(BufferedImage.TYPE_4BYTE_ABGR, 300);

编辑:提高了捕捉条码的成功率,但没有成功捕捉所有。增加 dpi 没有帮助。

关于java - 扫描 PDF 并转换为缓冲图像以解码 QR 时出现 Zxing 格式异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29612730/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com