4

I'm trying to create a BufferedImage from a ByteArrayInputStream with:

  byte[] imageData = getData(imageFile); // returns file as byte[]

  InputStream inputStream = new ByteArrayInputStream(imageData);
  String format = getFormatName(inputStream);

  BufferedImage img = ImageIO.read(inputStream);

But img is always null. The input stream is valid (since I use it before to get the image format). What could be making ImageIO return null? Do I need to use flush or close in any place?

Rui
  • 5,900
  • 10
  • 38
  • 56

1 Answers1

5

Your call to getFormatName consumes the inputStream, so the stream pointer is at the end of the byte array. Any try to read from that stream will tell that it's at the end of the 'file'. You need to reset the stream (or create a new one) before you hand it over to the ImageIO.read() method:

String format = getFormatName(new ByteArrayInputStream(imageData));
BufferedImage img = ImageIO.read(new ByteArrayInputStream(imageData));
mhaller
  • 14,122
  • 1
  • 42
  • 61