我在从战争文件中加载图像时遇到了一些麻烦。我的功能如下:
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。