如何将整个输入流读到字节数组?


当前回答

你真的需要图像作为字节[]吗?你在字节[]中到底期望什么-图像文件的完整内容,以图像文件的任何格式编码,或RGB像素值?

这里的其他答案向您展示了如何将文件读入字节[]。您的字节[]将包含文件的确切内容,并且您需要对其进行解码才能对图像数据进行处理。

用于读取(和写入)图像的Java标准API是ImageIO API,您可以在javax.imageio包中找到它。你可以用一行代码从文件中读入一张图片:

BufferedImage image = ImageIO.read(new File("image.jpg"));

这将给您一个BufferedImage,而不是一个字节[]。要获取图像数据,可以在BufferedImage上调用getRaster()。这将为您提供一个光栅对象,该对象具有访问像素数据的方法(它有几个getPixel() / getPixels()方法)。

查找javax.imageio的API文档。ImageIO java.awt.image。BufferedImage, java。awt。image。raster等等。

ImageIO默认支持多种图像格式:JPEG, PNG, BMP, WBMP和GIF。可以添加对更多格式的支持(您需要一个实现ImageIO服务提供程序接口的插件)。

另请参阅下面的教程:使用图像

其他回答

20年后,终于有了一个不需要第三方库的简单解决方案,这要感谢Java 9:

InputStream is;
…
byte[] array = is.readAllBytes();

还要注意方便的方法readNBytes(byte[] b, int off, int len)和transferTo(OutputStream)来解决重复的需求。

请参阅InputStream.available()文档:

It is particularly important to realize that you must not use this method to size a container and assume that you can read the entirety of the stream without needing to resize the container. Such callers should probably write everything they read to a ByteArrayOutputStream and convert that to a byte array. Alternatively, if you're reading from a file, File.length returns the current length of the file (though assuming the file's length can't change may be incorrect, reading a file is inherently racy).

您需要从InputStream中读取每个字节,并将其写入ByteArrayOutputStream。

然后你可以通过调用toByteArray()来检索底层的字节数组:

InputStream is = ...
ByteArrayOutputStream buffer = new ByteArrayOutputStream();

int nRead;
byte[] data = new byte[16384];

while ((nRead = is.read(data, 0, data.length)) != -1) {
  buffer.write(data, 0, nRead);
}

return buffer.toByteArray();

另一种情况是在发送请求到服务器并等待响应后,通过流获得正确的字节数组。

/**
         * Begin setup TCP connection to PC app
         * to open integrate connection between mobile app and pc app (or mobile app)
         */
        mSocket = new Socket(IP, port);
       // mSocket.setSoTimeout(30000);

        DataOutputStream mDos = new DataOutputStream(mSocket.getOutputStream());

        String str = "MobileRequest#" + params[0] + "#<EOF>";

        mDos.write(str.getBytes());

        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        /* Since data are accepted as byte, all of them will be collected in the
        following byte array which initialised with accepted data length. */
        DataInputStream mDis = new DataInputStream(mSocket.getInputStream());
        byte[] data = new byte[mDis.available()];

        // Collecting data into byte array
        for (int i = 0; i < data.length; i++)
            data[i] = mDis.readByte();

        // Converting collected data in byte array into String.
        String RESPONSE = new String(data);

如果你碰巧使用谷歌Guava,它将像使用ByteStreams一样简单:

byte[] bytes = ByteStreams.toByteArray(inputStream);