Android - Choose Image From Gallery And Store It In A File Type Variable
I am a new to Android Development. I wish to select an image or a video from the Gallery of an Android Device. Store it in a variable of typeFile. I am doing this, since I need to
Solution 1:
All you need to do is just create a File
variable with the path of image which you've selected from gallery. Change your OnActivityResult
as :
protectedvoidonActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1 && resultCode == RESULT_OK) {
UriselectedImageUri= data.getData();
imagepath = getPath(selectedImageUri);
FileimageFile=newFile(imagepath);
}
}
Solution 2:
this works for image selection. also tested in API 29,30. if anyone needs it.
privatestaticfinalintPICK_IMAGE=5;
Intentintent=newIntent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(Intent.createChooser(intent, "select image"),
PICK_IMAGE);
publicvoidonActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == PICK_IMAGE && resultCode == RESULT_OK) {
UriselectedImageUri= data.getData();
StringselectedImagePath= getRealPathFromURIForGallery(selectedImageUri);
FileimageFile=newFile(selectedImagePath);
}
}
public String getRealPathFromURIForGallery(Uri uri) {
if (uri == null) {
returnnull;
}
String[] projection = {MediaStore.Images.Media.DATA};
Cursorcursor=this.getContentResolver().query(uri, projection, null,
null, null);
if (cursor != null) {
intcolumn_index=
cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
assertfalse;
cursor.close();
return uri.getPath();
}
Solution 3:
Try this
You can try this also
publicvoidonActivityResult(int requestCode, int resultCode, Intent data)
{
if (requestCode == 1 && resultCode == RESULT_OK && data != null)
{
Filedestination=newFile(Environment.getExternalStorageDirectory(),System.currentTimeMillis() + ".jpg");
//You will get file path of captured camera imageBitmapphoto= (Bitmap) data.getExtras().get("data");
iv_profile.setImageBitmap(photo);
}
}
Post a Comment for "Android - Choose Image From Gallery And Store It In A File Type Variable"