如何在没有 ImageIO.read() 的情况下将加载的字节转换为图像

How to convert loaded bytes into image without ImageIO.read()

我不能使用 ImageIO.read() 因为我自己的限制。我只能在 GET 请求后加载字节,我需要将这些字节作为图像保存到文件中。但在我看来,还加载了一些额外的数据,浏览器通常会过滤这些数据(可能是响应 headers)。所以我得到了原始字节数组,我什至无法将其作为图像打开。

我应该如何处理这些字节?

示例:

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

常见问题。在 Java 中复制流的标准方法是:

int count;
while ((count = in.read(buffer)) > 0)
{
    out.write(buffer, 0, count);
}
out.close();
in.close();

注意需要将read()返回的结果存储到一个变量中;您需要在下一个 write() 调用中使用它;你不应该 flush() 在循环中;并且您需要关闭输入和输出流。

而您为什么要使用 ByteArrayInputStream 完全是个谜。这只是浪费时间和 space。直接从 URL 输入流读取,并直接写入 FileOutputStream

以下代码对我有用:-

    URL url = new URL("my url...");
    InputStream is = url.openStream();
    OutputStream os = new FileOutputStream("img.jpg");

    byte[] b = new byte[2048];
    int length;

    while ((length = is.read(b)) != -1) {
        os.write(b, 0, length);
    }

    is.close();
    os.close();