Java error while creating BufferedImage from ByteArrayInputStream

I am 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 zero. The input stream is valid (since I use it earlier to get the image format). What can make ImageIO return null? Do I need to use a flash or close anywhere?

+4
source share
1 answer

Your call to getFormatName consumes inputStream , so the stream pointer is at the end of the byte array. Any attempt to read from this stream will report that it is at the end of the "file". You need to reset the thread (or create a new one) before passing it to the ImageIO.read () method:

 String format = getFormatName(new ByteArrayInputStream(imageData)); BufferedImage img = ImageIO.read(new ByteArrayInputStream(imageData)); 
+5
source

Source: https://habr.com/ru/post/1333459/


All Articles