Search code examples
javaandroidbyteapache-commonsparse-platform

Saving a .jpg to byte[] android


This shouldn't be that hard, but I cannot figure this out. I need to save an image, on my end only, and build it dynamically so all my users will view these images. The tutorials on Parse.com are very helpful, but not in the case of images. I need detailed explanations or helpful links. Thanks for looking.

This is all I have so far as far as saving an image. I am properly getting the file in my Data Browser, but if I try to view it, it only shows my string "beatdown.jpg" not the actual jpg.

....

private void saveImage() {
// TODO Auto-generated method stub

InputStream header = new FileInputStream("beatdown.jpg");   
byte[] head = IOUtils.toByteArray(header);

ParseFile file = new ParseFile(head);
try{
    file.save();
} catch (ParseException e) {
    e.printStackTrace();
}

ParseObject displayImage = new ParseObject("displayImage");
displayImage.put("header", file);
try{
    displayImage.save();
} catch (ParseException e1){
    e1.printStackTrace();
}
}

I understand I am trying to get the string of "beatdown.jpg" to bytes in the code above, and it is not handling it as a .jpg. But I don't know how to make it a .jpg.

EDIT: I added commons-io. But when I run the code (see the above updated code), it won't register on anything on parse.com. I am getting this in my logcat;

Service com.android.exchange.ExchangeService has leaked ServiceConnection com.android.emailcommon.service.ServiceProxy$ProxyConnection@40cf2498 that was originally bound here


Solution

  • The key elements are:

    File f = new File("pathToFile");
    FileInputStream fis = new FileInputStream(f);
    byte[] bytes = new byte[f.length()];
    fis.read(bytes);
    

    Of course there's exception handling and the like to do, but this should be enough to give you the general idea.