How do I read an entire InputStream
into a byte array?
Do you really need the image as a byte[]
? What exactly do you expect in the byte[]
- 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[]
. Your byte[]
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:
BufferedImage image = ImageIO.read(new File("image.jpg"));
This will give you a BufferedImage
, not a byte[]
. To get at the image data, you can call getRaster()
on the BufferedImage
. This will give you a Raster
object, which has methods to access the pixel data (it has several getPixel()
/ 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