android获取本地图片路径
时间: 2023-07-30 19:05:47 浏览: 172
获取本地图片路径可以通过以下步骤实现:
1. 获取图片URI
```java
Uri uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
```
2. 获取查询的字段
```java
String[] projection = {MediaStore.Images.Media.DATA};
```
3. 查询数据
```java
Cursor cursor = getContentResolver().query(uri, projection, null, null, null);
```
4. 遍历查询结果,获取图片路径
```java
List<String> paths = new ArrayList<>();
if (cursor != null) {
while (cursor.moveToNext()) {
String path = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA));
paths.add(path);
}
cursor.close();
}
```
完整代码如下:
```java
Uri uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
String[] projection = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(uri, projection, null, null, null);
List<String> paths = new ArrayList<>();
if (cursor != null) {
while (cursor.moveToNext()) {
String path = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA));
paths.add(path);
}
cursor.close();
}
```
注意:需要在 AndroidManifest.xml 中添加读取外部存储的权限。
```xml
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
```
阅读全文