code: public static byte[] toByteArray(final BufferedImage bi, final String formatName)
  		throws IOException
  	{
  		try (ByteArrayOutputStream baos = new ByteArrayOutputStream())
  		{
  			ImageIO.write(bi, formatName, baos);
  			baos.flush();
  			final byte[] byteArray = baos.toByteArray();
  			return byteArray;
  		}
  	}
docs: Converts the given BufferedImage to a byte array.
  
  @param bi
  the bi
  @param formatName
  the format name
  @return the byte[]
  @throws IOException
  Signals that an I/O exception has occurred.