Android - 从图库中选择图像并将其存储在文件类型变量中 [英] Android - Choose Image from Gallery and store it in a File type variable

查看:26
本文介绍了Android - 从图库中选择图像并将其存储在文件类型变量中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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 upload the image/video on dropbox using the Android API from my application. The constructor takes in the fourth parameter of the type File. I am not sure, what to pass as a file since all the examples I searched display the image chosen in an ImageView by using the url and making a bitmap.

imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));

这是代码,我有.

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);
}

推荐答案

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

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 :

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);
    }
}

这篇关于Android - 从图库中选择图像并将其存储在文件类型变量中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆