如何将整个InputStream
读入字节数组? java
您须要从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();
您可使用Apache Commons IO处理此任务和相似任务。 this
IOUtils
类型具备静态方法来读取InputStream
并返回byte[]
。 编码
InputStream is; byte[] bytes = IOUtils.toByteArray(is);
在内部,这将建立一个ByteArrayOutputStream
并将字节复制到输出,而后调用toByteArray()
。 它经过复制4KiB块中的字节来处理大型文件。 spa
您是否真的须要将图像做为byte[]
? 您对byte[]
指望是什么-图像文件的完整内容,以图像文件所使用的任何格式或RGB像素值进行编码? 插件
这里的其余答案显示了如何将文件读取为byte[]
。 您的byte[]
将包含文件的确切内容,而且您须要对其进行解码以对图像数据进行任何处理。 code
Java的用于读取(和写入)图像的标准API是ImageIO API,您能够在包javax.imageio
找到它。 您只需一行代码就能够从文件中读取图像: 对象
BufferedImage image = ImageIO.read(new File("image.jpg"));
这将为您提供BufferedImage
,而不是byte[]
。 要获取图像数据,能够在BufferedImage
上调用getRaster()
。 这将为您提供一个Raster
对象,该对象具备访问像素数据的方法(它具备几个getPixel()
/ getPixels()
方法)。 教程
查找有关javax.imageio.ImageIO
, java.awt.image.BufferedImage
, java.awt.image.Raster
等的API文档。 接口
ImageIO默认状况下支持多种图像格式:JPEG,PNG,BMP,WBMP和GIF。 能够增长对更多格式的支持(您须要一个实现ImageIO服务提供商接口的插件)。
另请参见如下教程: 使用图像
我试图用修复垃圾数据的方法来编辑@numan的答案,可是编辑被拒绝了。 虽然这段简短的代码并不出色,但我看不到其余更好的答案。 这对我来讲最有意义:
ByteArrayOutputStream out = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; // you can configure the buffer size int length; while ((length = in.read(buffer)) != -1) out.write(buffer, 0, length); //copy streams in.close(); // call this in a finally block byte[] result = out.toByteArray();
btw ByteArrayOutputStream不须要关闭。 尝试/最终构造被省略以提升可读性
public static byte[] getBytesFromInputStream(InputStream is) throws IOException { ByteArrayOutputStream os = new ByteArrayOutputStream(); byte[] buffer = new byte[0xFFFF]; for (int len = is.read(buffer); len != -1; len = is.read(buffer)) { os.write(buffer, 0, len); } return os.toByteArray(); }