我需要在PDF中解码DataMatrix,在我的情况下,DataMatrix它不是图像。
我的第一个想法是将页面转换为图像并使用DataMatrix裁剪区域并在解码后,但似乎(图像)结果已损坏,我无法正确解码。任何想法如何保持PDF的质量?
String sourceDir = "data/test2.pdf";
File pdf = new File(sourceDir);
PDDocument document = PDDocument.load(sourceDir);
List<PDPage> list = document.getDocumentCatalog().getAllPages();
String key;
for (PDPage page : list) {
BufferedImage image = page.convertToImage(BufferedImage.TYPE_INT_RGB, 300);
BufferedImage dest = image.getSubimage(0, 2600, 800, 800);
File outputFile = new File( "data/test2.jpg");
ImageIO.write(dest, "png", outputFile);
LuminanceSource lumSource = new BufferedImageLuminanceSource (dest);
BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(lumSource));
Hashtable<DecodeHintType, Object> hint = new Hashtable<DecodeHintType, Object>();
hint.put(DecodeHintType.TRY_HARDER, BarcodeFormat.DATA_MATRIX);
DataMatrixReader DMreader = new DataMatrixReader();
try {
Result result = DMreader.decode(bitmap, hint);
System.out.println(result);
}catch(Exception e){
System.out.println("NO Data Matrix");
}
}
}
版本2.0
PDDocument document = PDDocument.load(new File(sourceDir));
PDFRenderer pdfRenderer = new PDFRenderer(document);
for (int page = 0; page < document.getNumberOfPages(); ++page)
{
BufferedImage bufferedImage = pdfRenderer.renderImageWithDPI(page, 600, ImageType.RGB);
BufferedImage datamatrixImg = bufferedImage.getSubimage(150, 6000, 600, 900);
File outputfile = new File("out/image_"+page+".jpg");
ImageIO.write(datamatrixImg, "jpg", outputfile);
LuminanceSource lumSource = new BufferedImageLuminanceSource(datamatrixImg);
BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(lumSource));
Hashtable<DecodeHintType, Object> hint = new Hashtable<DecodeHintType, Object>();
hint.put(DecodeHintType.TRY_HARDER, BarcodeFormat.DATA_MATRIX);
DataMatrixReader DMreader = new DataMatrixReader();
try {
Result result = DMreader.decode(bitmap, hint);
System.out.println("Decode: "+ result );
} catch (Exception e) {
System.out.println("No DataMatrix");
}
}
document.close();