I need to convert a BufferedImage to a byte[], 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:
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;
}
This is far too slow for my program. Changing the png to jpeg makes it fail on the mobile side. The JpegCodec version also fails on the mobile side. By fail I mean the Android method BitmapFactory.decodeByteArray() returns null.
You don’t say why it’s too slow and there isn’t much that can be done to make this code faster because it’s the only way to convert a
BufferedImageto a PNG byte stream. But here are some pointers:The class
ByteArrayOutputStreamis synchronized which costs a lot of performance. You can find a faster implementation in Commons IO (org.apache.commons.io.output.ByteArrayOutputStream)Depending on the size of your image, the allocation algorithm of
ByteArrayOutputStreammight be a problem. Start with an initial size of 1 or 10 KiB.toByteArray()gives you a copy of the existing buffer. If you don’t need that (and usually, you don’t), writing your ownOutputStreammight give you an additional speed boost (not to mention avoiding GC runs)