How do I read an entire InputStream
into a byte array?
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- Difference between Types.INTEGER and Types.NULL in
Do you really need the image as a
byte[]
? What exactly do you expect in thebyte[]
- the complete content of an image file, encoded in whatever format the image file is in, or RGB pixel values?Other answers here show you how to read a file into a
byte[]
. Yourbyte[]
will contain the exact contents of the file, and you'd need to decode that to do anything with the image data.Java's standard API for reading (and writing) images is the ImageIO API, which you can find in the package
javax.imageio
. You can read in an image from a file with just a single line of code:This will give you a
BufferedImage
, not abyte[]
. To get at the image data, you can callgetRaster()
on theBufferedImage
. This will give you aRaster
object, which has methods to access the pixel data (it has severalgetPixel()
/getPixels()
methods).Lookup the API documentation for
javax.imageio.ImageIO
,java.awt.image.BufferedImage
,java.awt.image.Raster
etc.ImageIO supports a number of image formats by default: JPEG, PNG, BMP, WBMP and GIF. It's possible to add support for more formats (you'd need a plug-in that implements the ImageIO service provider interface).
See also the following tutorial: Working with Images
Java 7 and later:
Below Codes
OR
You're doing an extra copy if you use ByteArrayOutputStream. If you know the length of the stream before you start reading it (e.g. the InputStream is actually a FileInputStream, and you can call file.length() on the file, or the InputStream is a zipfile entry InputStream, and you can call zipEntry.length()), then it's far better to write directly into the byte[] array -- it uses half the memory, and saves time.
N.B. the last line above deals with files getting truncated while the stream is being read, if you need to handle that possibility, but if the file gets longer while the stream is being read, the contents in the byte[] array will not be lengthened to include the new file content, the array will simply be truncated to the old length inputStreamLength.
In-case someone is still looking for a solution without a dependency and If you have a file.