Sunday, June 3, 2012

Android: Converting file to byte array

This came up as a requirement because I had to attach profile pictures to vCard on my eJabberd server. My first approach was to: 
  1. Decode the jpg as bitmap.
  2. Convert the bitmap into a byte array. 
  3. Attach the byte array to the vCard, and perform the save. 
This approach, however, was inadvertently saving the .bmp version of the file instead of the jpg copy. The .bmp version of the same file was too big and causing the server to timeout on transaction. I did not realize this silly mistake until I examine the server log. 


This then raise the requirement to convert the .jpg directly to a byte array. I was unable to use some of the existing Java libraries because Android does not contain them. Googling and Stackoverflowing for a bit eventually I found the solution: 



InputStream is = new BufferedInputStream(new FileInputStream(
"/mnt/file_path_here"));


ByteArrayOutputStream bos = new ByteArrayOutputStream();


while (is.available() > 0) {
bos.write(is.read());
}


return bos.toByteArray();