Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Byte Array to image in Java - without knowing the type

Sounds simple right? Use

ImageIO.read(new ByteArrayInputStream(bytes));

Here's the wrinkle. For some reason it is detecting a jpeg as a bmp, and that is the first ImageReader returned when I call

ImageInputStream iis = ImageIO.createImageInputStream(new ByteArrayInputStream(bytes));
Iterator<ImageReader> readers=ImageIO.getImageReaders(iis);

This causes the image to come out corrupted. Is there a way to tell through java short of looking directly at the bytes for the header, and failing that does anyone know of a good reference for the byte headers for the different images?

Just letting you guys know I am still working on this. I'll let you know if/when I have an answer. I thank all of you for your responses so far.

like image 826
PHeath Avatar asked Jul 31 '09 14:07

PHeath


People also ask

How do you check if a byte array is a valid image Java?

You can try to generate an image from the byte array and check for the ArgumentException if its not. Show activity on this post. Most other types of image files have similar magick numbers. But checking that won't actually tell you if the file is a valid image file.

Can we convert byte array to file in Java?

Convert byte[] array to File using Java In order to convert a byte array to a file, we will be using a method named the getBytes() method of String class. Implementation: Convert a String into a byte array and write it in a file.

Can you print [] byte?

You can simply iterate the byte array and print the byte using System. out. println() method.


1 Answers

Haven't played with ImageIO in a awhile, and have not tested this, but I seem to recall something like this working. (since you say you know your file is a jpg and not a bitmap, I am using that information to help find the right loader).

String inFormat = "jpg";

Iterator inReaders = ImageIO.getImageReadersByFormatName(inFormat);

...

nextInReader.setInput( iis );
like image 147
jedierikb Avatar answered Sep 20 '22 07:09

jedierikb