1.首先跳转到系统相册选择图片 public void ChoosePicture(View view) { // 激活
public void ChoosePicture(View view)
{
// 激活系统图库,选择一张图片
Intent intent = new Intent();
intent.setAction(Intent.ACTION_PICK);
intent.setType("image/*");
startActivityForResult(intent, 0);
}
2.重载startActivityForResult函数,处理所选择的图片
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
if( requestCode == 0)
{
if( data != null )
{
Bitmap bitmapLocal = null;
Uri uri = data.getData(); //获取图片uri
String imagePath = getRealPathFromURI(uri); // 根据URI找到图片真正的路径
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 2;
bitmapLocal = BitmapFactory.decodeFile(imagePath, options);
this.image.setImageBitmap(bitmapLocal);
this.bitmap = bitmapLocal;
super.onActivityResult(requestCode, resultCode, data);
}
}
}
其中,getRealPathFromURI函数将文件的uri转化为文件路径,具体代码如下:
private String getRealPathFromURI(Uri contentURI) {
String result;
Cursor cursor = getContentResolver().query(contentURI, null, null, null, null);
//不能直接调用contentprovider的接口函数,需要使用contentresolver对象,通过URI间接调用contentprovider
if (cursor == null) {
// Source is Dropbox or other similar local file path
result = contentURI.getPath();
} else {
cursor.moveToFirst();
int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
result = cursor.getString(idx);
cursor.close();
}
return result;
}
到这里我们就成功将获取到图片的文件路径啦。
--结束END--
本文标题: android跳到系统相册选择图片并根据uri获取真实图片路径
本文链接: https://lsjlt.com/news/29046.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
2024-01-21
2023-10-28
2023-10-28
2023-10-27
2023-10-27
2023-10-27
2023-10-27
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0