从战争加载图像

时间:2013-05-10 19:50:03

标签: java image web war

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

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。

更多信息:

  • 我从war文件中的资源中加载了一个jpg
  • 网址是正确的,第一行会抛出NullPointerException。

1 个答案:

答案 0 :(得分: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);