Java: BufferedImage to byte array and back

This is recommended to convert to a byte array

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

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:

  • Java: Memory efficient ByteArrayOutputStream
  • jpg bits per pixel

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