gpt4 book ai didi

Java - 按字节下载图像下载损坏的图像

转载 作者:行者123 更新时间:2023-11-30 03:46:54 25 4
gpt4 key购买 nike

你好,我很好奇如何在java中下载数据,所以我研究了几种方法并决定使用BufferedInputStream

现在,当我下载时,我会突发下载 1024 字节的文件,每次下载 1kb 时,我都会将临时数组连接到主数据数组。tH

我使用这个连接方法:

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 将字节数组转换为 BufferedImage:

    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);

现在结果图像如下所示:

img
(来源:gyazo.com)

如您所见,下载时图像看起来已损坏,缺少字节。这是真实的图像:

img http://freshhdwall.com/wp-content/uploads/2014/08/Image-Art-Gallery.jpg

我做错了什么,它会显示这样的图像?

最佳答案

在每次循环迭代中,您可能读取少于 bytes.length 字节。因此,您不能使用数组的完整长度。您需要准确地使用实际读取的部分。

一种解决方案是使用

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;
}

以便仅复制您实际收到的字节。

考虑使用一些解决方案 here 。它们可能更高效,或者至少更具可读性。

关于Java - 按字节下载图像下载损坏的图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25418946/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com