title: How can I quickly convert a BufferedImage to a byte[]?
body: <p>I need to convert a <code>BufferedImage</code> to a <code>byte[]</code>, but It is too slow. The byte is eventually base64 encoded and sent to an android client. The Method I have been using is like this:</p>
  
  <pre><code>public static byte[] ImageToBytes(BufferedImage im) throws IOException
  {
  
  //make sure its NN
  if(im!=null)
  {
  
  //create a ByteArrayOutputStream
  ByteArrayOutputStream baos = new ByteArrayOutputStream();
  
  //write our image to it
  ImageIO.write( im, "png", baos );
  
  //flush the stream
  baos.flush();
  
  //get the image in byte form
  byte[] imageInByte = baos.toByteArray();
  
  //close the stream
  baos.close();
  
  //return our value encoded in base64
  return imageInByte;
  
  }
  
  return null;
  }
  </code></pre>
  
  <p>This is far too slow for my program. Changing the <code>png</code> to <code>jpeg</code> makes it fail on the mobile side. The <code>JpegCodec</code> version also fails on the mobile side. By fail I mean the Android method <code>BitmapFactory.decodeByteArray()</code> returns <code>null</code>.</p>