使用getResource在Java中无法读取输入图像

时间:2019-04-17 10:30:32

标签: java pdfbox

我试图将用户选择的图像添加到通过netbeans中的pdfbox生成的pdf中。如果我直接给直接提供路径,那么它就可以了,但是获取图像路径的URL并添加不起作用。

看到给定的代码问题是URL和Path,因为输入没有被读取


 public static ByteArrayOutputStream PDFGenerator(........,Path imagespath)
  {
    ........
    if (finalpdf.Images != null)
    {
      Path imagepath = Paths.get(imagespath.toString(), "room.png");
      PDImageXObject Addedimage = PDImageXObject.createFromFile(imagepath.toString(), pdf);
      AddImages(content, Addedimage, 229.14f, 9.36f);
    }

    //AddImages method is following
  public static void AddImages(PDPageContentStream content, PDImageXObject image, float x, float y) throws IOException
  {

    content.drawImage(image, x, y);

  }
}

  //Following is snippet from my test method
  public void testClass()
  {
    ........
    finalpdf.Images = "room.png";
    URL imageurl = testclass.class.getResource("room.png");
    Path imagepath = Paths.get(imageurl.getPath().substring(1));
    ByteArrayOutputStream baos = PDFGenerator.generatefurtherpdf(finalpdf, "0000.00", "00.00", imagepath);

    writePDF(baos, "YourPdf.pdf");

  }

我希望它能以这种方式工作,但是我确定它与Path有关,但我没有正确使用它。我希望该代码具有足够的解释性,因为我还很新,也有安全方面的原因,所以我不能放入整个代码。对不起,错了

1 个答案:

答案 0 :(得分:1)

对于资源(从来没有File),存在一个广义类:Path

Path path = Paths.get(imageurl.toURI());

但是无论何时该路径(例如,URL为´jar:file // ... .jar!... .... png“)都将用作文件,path.toString()建议使用该路径,可以使用InputStream。

第二个广义类是InputStream,它是更底层的:

InputStream in = TestClass.getResourceAsStream(imagepath);

这是从未使用过的getResource().openStream()的捷径。资源路径不正确时抛出NullPointerException。

最后一种解决方法是将实际的byte[]用于createFromByteArray

byte[] bytes = Files.readAllBytes(path);
PDImageXObject Addedimage = PDImageXObject.createFromByteArray(doc, bytes, name);

使用临时文件

  Path imagepath2 = Files.createTempFile("room", ".png");
  Files.copy(imagepath, imagepath2);
  PDImageXObject Addedimage = PDImageXObject.createFromFile(imagepath2.toString(), pdf);