Android-从图库中选择图像并将其存储在文件类型变量中

pra*_*hah 2 upload android file image-gallery dropbox

我是Android开发的新手。我希望从Android设备的图片库中选择图片或视频。将其存储在type变量中File。我这样做是因为我需要使用我的应用程序中的Android API 在Dropbox上上传图像/视频。构造函数接受File类型的第四个参数。我不确定,作为文件传递的内容是什么,因为我搜索的所有示例都通过使用URL并制作位图来显示在ImageView中选择的图像。

imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
Run Code Online (Sandbox Code Playgroud)

这是代码,我有。

final Intent galleryIntent = new Intent(Intent.ACTION_GET_CONTENT);
//to get image and videos, I used a */"
galleryIntent.setType("*/*"); 
startActivityForResult(galleryIntent, 1);

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == 1 && resultCode == RESULT_OK) {               
    Uri selectedImageUri = data.getData();
    imagepath = getPath(selectedImageUri);                
    }
}

public String getPath(Uri uri) {
    String[] projection = { MediaStore.Images.Media.DATA };
    Cursor cursor = getContentResolver().query(uri, projection, null, null, null);
    int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
    cursor.moveToFirst();                
    int columnIndex = cursor.getColumnIndex(projection[0]);
    String filePath = cursor.getString(columnIndex);
    cursor.close();        
    yourSelectedImage = BitmapFactory.decodeFile(filePath);
    return cursor.getString(column_index);
}
Run Code Online (Sandbox Code Playgroud)

And*_*dyN 5

您需要做的只是File使用从图库中选择的图像路径创建一个变量。更改OnActivityResult为:

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == 1 && resultCode == RESULT_OK) {               
    Uri selectedImageUri = data.getData();
    imagepath = getPath(selectedImageUri); 
    File imageFile = new File(imagepath);
    }
}
Run Code Online (Sandbox Code Playgroud)