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?

1 Answer 1

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));
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.