【问题标题】:Java - downloading image by bytes downloads a broken imageJava - 按字节下载图像会下载损坏的图像
【发布时间】:2014-08-21 05:39:22
【问题描述】:

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

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

我用这个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将字节数组转换为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);

现在结果图像如下所示:


(来源:gyazo.com

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

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

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

【问题讨论】:

  • 你的代码很适合我

标签: java image networking


【解决方案1】:

在每次循环迭代中,您可能读取的字节数可能少于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。它们可能更高效,或者至少更具可读性。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-04-08
    • 1970-01-01
    • 2020-05-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-29
    • 1970-01-01
    相关资源
    最近更新 更多