0

我在从战争文件中加载图像时遇到了一些麻烦。我的功能如下:

private String printResource(ResourceBean resource) throws IOException {
     URLConnection connection = getServerURL(resource.getPath()).openConnection();
        BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        StringBuilder response = new StringBuilder();
     String inputLine;
        while ((inputLine = in.readLine()) != null)
         response.append(inputLine).append("\n");
      in.close();
      return response.toString();
}

这个函数的返回值会直接写在网页中。我的问题如下。图像不显示,如果我下载并打开它。程序告诉我,图像无效或损坏。

我不知道问题可能出在哪里,我将非常感谢您的回答。

编辑:

我对该函数添加了一些更改:

private String printResource(ResourceBean resource, HttpServletResponse response) throws IOException {
    URL url = getServerURL(resource.getPath());
    if (resource.getType().equals("pic")) {
        masterLogger.debug("Resource is a pic, special treatment");
        BufferedImage img = ImageIO.read(url);
        File f = new File(resource.getId());
        ImageIO.write(img, "jpg", f);
        FileOutputStream fis = new FileOutputStream(f);
        return fis.toString();
    } else {
        URLConnection connection = getServerURL(resource.getPath()).openConnection();
        BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        StringBuilder responseText = new StringBuilder();
        String inputLine;
        while ((inputLine = in.readLine()) != null)
            responseText.append(inputLine).append("\n");
        in.close();
        return responseText.toString();
    }
}

现在我在 ImageIO.write() 第 1538 行得到一个 NullPointer。

更多信息:

  • 我从战争文件中的资源中加载 jpg
  • URL 是正确的,否则第一行会抛出 NullPointerException。
4

1 回答 1

3

采用:

BufferedImage img = ImageIO.read(url);

例子:

URLConnection connection = new URL(url).openConnection();
BufferedImage img = ImageIO.read(connection.getInputStream());
ImageIO.write(img, "jpg", new File("downloaded_1.jpg"));
ImageIO.write(img, "png", new File("downloaded_2.png"));

或者您可以写入 servlet 响应(提供正确的请求和响应属性)或ByteArrayOutputStream实例

如果它来自战争,最好的途径是通过ServletContext前:InputStream input = getServletContext().getResourceAsStream(path);

于 2013-05-10T19:53:32.943 回答