使用 getResource 在 java 中未读取输入图像

Input image not getting read in java with getResource

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

看到给定的代码问题与 URL 和路径有关,因为输入未被读取


 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 存在一些问题,我没有正确使用它。我希望代码足够解释,因为我很新也有安全原因所以我不能把整个代码。抱歉错误

对于资源(从来没有File)存在一个通用的class:Path

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

然而,每当该路径(例如 URL ´jar:file//... .jar!... ... .png")将被用作文件时,path.toString() 建议,可以使用 InputStream。

第二个广义化的class是一个InputStream,它更底层:

InputStream in = TestClass.getResourceAsStream(imagepath);

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

最后的办法是使用 createFromByteArray 的实际 byte[]

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);