Android : Getting byte[] from Image ID
-
12-10-2019 - |
Question
Here is what I am doing:
In onActivityResult, I get the data in an Intent.
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
startActivityForResult(intent, TAKE_PICTURE);
This code gets the image ID:
data.getData().getLastPathSegment();
Now i want to use this image ID to get byte[] imageData so I can upload the image on a server.
How do I go about it?
Solution
Uri selectedImageUri = data.getData();
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(selectedImageUri, projection, null, null, null);
cursor.moveToFirst();
selectedImagePath = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA));
cursor.close();
try
{
File myFile = new File(selectedImagePath);
int filelenghth=(int)myFile.length();
byte [] mybytearray = new byte [filelenghth];
BufferedInputStream bis1 = new BufferedInputStream(new FileInputStream(myFile));
bis1.read(mybytearray,0,mybytearray.length);
dos.write(mybytearray,0,mybytearray.length); // write the array to the data output stream
// or whatever else you want to do with it
finish();
}
catch(Exception e)
{
e.printStackTrace();
}
OTHER TIPS
data.getData() will return to you a URI for your image. (Check data != null first!)
then you just need to perform a http post to your server.
See the following reference on SO for the http post code: Sending images using Http Post
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow