【发布时间】:2015-02-05 08:42:47
【问题描述】:
由于我自己的限制,我不能使用 ImageIO.read()。我只能在 GET 请求后加载字节,我需要将此字节保存为图像文件。但在我看来,还加载了一些额外的数据,浏览器通常会过滤(可能是响应头)。所以我得到了我什至无法作为图像打开的原始字节数组。
我应该如何处理这些字节?
例子:
byte[] buf = ContentLoader.loadBytes(new URL("http://images.visitcanberra.com.au/images/canberra_hero_image.jpg"));
try {
FileOutputStream fileOutputStream = new FileOutputStream(new File("D:\\image.jpg"));
fileOutputStream.write(buf);
fileOutputStream.flush();
} catch (IOException e) {
e.printStackTrace();
}
loadBytes() 方法:
public static byte[] loadBytes(URL url) {
ByteArrayOutputStream boutArray = new ByteArrayOutputStream();
try {
URLConnection connection = url.openConnection();
BufferedInputStream bin = new BufferedInputStream(connection.getInputStream());
byte[] buffer = new byte[1024 * 16];
while (bin.read(buffer) != -1) {
boutArray.write(buffer);
boutArray.flush();
}
bin.close();
} catch (Exception e) {
return null;
}
return boutArray.toByteArray();
}
【问题讨论】:
-
为什么不直接将原始字节存储到文件中?
-
您想编写自己的 JPEG 解码器吗? (我已经完成了,这是一个有趣的练习)如果没有,请使用 ImageIO.load(内置一个)或查找其他人的 JPEG 解码器。
-
当我将原始字节存储到文件时,我无法打开它。它包含图像字节和一些奇数字节(如果比较浏览器保存和我保存的此图像的大小)
-
如果你的最后一个
read调用返回一个字节,你仍然在写入 16384 个字节(那个字节,加上数组中的其他 16383 个字节恰好来自最后一个块)。 -
@immibis 和其他任何
read()通话一样。不能保证它们中的任何一个都会填满缓冲区。