Java: BufferedImage to byte array and back

JavaArraysByteBufferedimage

Java Problem Overview


I see that a number of people have had a similar problem, however I'm yet to try find exactly what I'm looking for.

So, I have a method which reads an input image and converts it to a byte array:

    File imgPath = new File(ImageName);
	BufferedImage bufferedImage = ImageIO.read(imgPath);
    WritableRaster raster = bufferedImage .getRaster();
	DataBufferByte data   = (DataBufferByte) raster.getDataBuffer();

What I now want to do is convert it back into a BufferedImage (I have an application for which I need this functionality). Note that "test" is the byte array.

    BufferedImage img = ImageIO.read(new ByteArrayInputStream(test));
	File outputfile = new File("src/image.jpg");
	ImageIO.write(img,"jpg",outputfile);

However, this returns the following exception:

    Exception in thread "main" java.lang.IllegalArgumentException: im == null!

This is because the BufferedImage img is null. I think this has something to do with the fact that in my original conversion from BufferedImage to byte array, information is changed/lost so that the data can no longer be recognised as a jpg.

Does anyone have any suggestions on how to solve this? Would be greatly appreciated.

Java Solutions


Solution 1 - Java

This is recommended to convert to a byte array

ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(img, "jpg", baos);
byte[] bytes = baos.toByteArray();

Solution 2 - Java

Note that calling close or flush will do nothing, you can see this for yourself by looking at their source/doc:

> Closing a ByteArrayOutputStream has no effect. > > The flush method of OutputStream does nothing.

Thus use something like this:

ByteArrayOutputStream baos = new ByteArrayOutputStream(THINK_ABOUT_SIZE_HINT);
boolean foundWriter = ImageIO.write(bufferedImage, "jpg", baos);
assert foundWriter; // Not sure about this... with jpg it may work but other formats ?
byte[] bytes = baos.toByteArray();

Here are a few links concerning the size hint:

Of course always read the source code and docs of the version you are using, do not rely blindly on SO answers.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser1875290View Question on Stackoverflow
Solution 1 - JavaNikolay KuznetsovView Answer on Stackoverflow
Solution 2 - JavaChristophe RoussyView Answer on Stackoverflow