Java-按字节下载图像下载损坏的图像
您好,我很好奇如何用java下载数据,所以我仔细研究了几种方法,决定使用Java-按字节下载图像下载损坏的图像,java,image,networking,Java,Image,Networking,您好,我很好奇如何用java下载数据,所以我仔细研究了几种方法,决定使用BufferedInputStream 现在,当我下载时,我以1024字节突发的方式下载文件,每次它下载1kb时,我将临时数组连接到主数据数组中 我使用concat方法: public static byte[] concat(byte[] data, byte[] bytes) { byte[] result = Arrays.copyOf(data, data.length + bytes.length);
BufferedInputStream
现在,当我下载时,我以1024字节突发的方式下载文件,每次它下载1kb时,我将临时数组连接到主数据数组中
我使用concat方法:
public static byte[] concat(byte[] data, byte[] bytes) {
byte[] result = Arrays.copyOf(data, data.length + bytes.length);
System.arraycopy(bytes, 0, result, data.length, bytes.length);
return result;
}
这是我的下载过程:
URL target = new URL ("http://freshhdwall.com/wp-content/uploads/2014/08/Image-Art-Gallery.jpg");
URLConnection t = target.openConnection();
t.setRequestProperty("User-Agent", "NING/1.0");
t.connect();
BufferedInputStream stream = new BufferedInputStream(t.getInputStream());
final byte[] bytes = new byte[1024];
int count;
byte[] data = new byte[0];
while ( (count = stream.read(bytes, 0, bytes.length)) != -1) {
System.out.println(count);
data = concat(data, bytes);
}
现在下载后,我使用ByteArrayInputStream
将字节数组转换为BuffereImage
:
InputStream s = new ByteArrayInputStream(data);
BufferedImage m = ImageIO.read(s);
然后我显示结果:
JFrame j = new JFrame();
j.add(new JLabel(new ImageIcon(m)));
j.pack();
j.setVisible(true);
现在,结果图像如下所示:
(来源:) 如您所见,图像在下载时看起来已损坏,缺少字节。 这是真实的图像:
我做错了什么,它会这样显示图像?在每次循环迭代中,您可能读取的字节数少于
字节。长度字节。因此,不能使用数组的完整长度。你需要准确地使用实际阅读的部分
一个解决办法是使用
while ((count = stream.read(bytes, 0, bytes.length)) != -1) {
System.out.println(count); // this should hint at this
data = concat(data, bytes, count); // use the count
}
及
以便只复制实际接收到的字节
考虑使用一些解决方案。它们可能更高效,或者至少更可读。您的代码对我来说非常有用
public static byte[] concat(byte[] data, byte[] bytes, int count) {
byte[] result = Arrays.copyOf(data, data.length + count);
System.arraycopy(bytes, 0, result, data.length, count);
return result;
}