本文介绍了获得从mediastore URI文件名和路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 onActivityResult 从mediastore图像选择,我可以得到一个URI使用下面的图像返回:

 乌里selectedImage = data.getData();
 

此转换为字符串给出了这样的:

 内容://媒体/外部/图片/媒体/ 47
 

或一个路径给出了:

  /外部/图片/媒体/ 47
 

不过,我似乎无法找到一个方法来转换到这一点的绝对路径,因为我想要加载的图像转换为位图,而无需地方复制。我知道这可以通过URI和内容解析器来完成,但这似乎打破有关重新启动手机,我想 MediaStore 不保留其编号之间重新启动相同。

解决方案

 公共字符串getRealPathFromURI(上下文的背景下,乌里contentUri){
  光标光标= NULL;
  尝试 {
    的String []凸出= {MediaStore.Images.Media.DATA};
    光标= context.getContentResolver()查询(contentUri,凸出,NULL,NULL,NULL);
    INT与Column_Index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
    cursor.moveToFirst();
    返回cursor.getString(Column_Index中);
  } 最后 {
    如果(光标!= NULL){
      cursor.close();
    }
  }
}
 

I have an onActivityResult returning from an mediastore image selection which I can get a URI for an image using the following:

Uri selectedImage = data.getData();

Converting this to a string gives this:

content://media/external/images/media/47

Or to a path gives:

/external/images/media/47

However I can't seem to find a way to convert this into an absolute path, as I want to load the image into a bitmap without having to copy it somewhere. I know this can be done using the URI and content resolver but this seems to break on rebooting of the phone, I guess MediaStore doesn't keep its numbering the same between reboots.

解决方案
public String getRealPathFromURI(Context context, Uri contentUri) {
  Cursor cursor = null;
  try {
    String[] proj = { MediaStore.Images.Media.DATA };
    cursor = context.getContentResolver().query(contentUri,  proj, null, null, null);
    int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
    cursor.moveToFirst();
    return cursor.getString(column_index);
  } finally {
    if (cursor != null) {
      cursor.close();
    }
  }
}

这篇关于获得从mediastore URI文件名和路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 22:22