当前位置:操作系统 > 安卓/Android >>

android系统通过图片绝对路径获取URI的三种方法

最近做项目要通过图片的绝对路径找到图片的URI,然后删除图片,小小总结一下获取URI的方法,亲自试验在

android 4.1.3的系统上都是可用的。

 

1.将所有的图片路径取出,遍历比较找到需要的路径,取出URI,效率较低

其中 MediaStore.MediaColumns.DATA 字段存的就是图片的绝对路径,

最后mImageUri得到的就是图片的URI


 1 Uri mUri = Uri.parse("content://media/external/images/media");
 2 Uri mImageUri = null;
 3 Cursor cursor = managedQuery(
 4                                 MediaStore.Images.Media.EXTERNAL_CONTENT_URI, null, null, null,
 5                                 MediaStore.Images.Media.DEFAULT_SORT_ORDER);
 6 cursor.moveToFirst();
 7
 8 while (!cursor.isAfterLast()) {
 9                         String data = cursor.getString(cursor
10                                         .getColumnIndex(MediaStore.MediaColumns.DATA));
11                         if (picPath.equals(data)) {
12                                 int ringtoneID = cursor.getInt(cursor
13                                                 .getColumnIndex(MediaStore.MediaColumns._ID));
14                                 mImageUri = Uri.withAppendedPath(mUri, "" + ringtoneID);
15                                 break;
16                         }
17                         cursor.moveToNext();
18 }

2.直接从媒体数据库根据字段取出相应的记录,效率较高


 1 //TYLT: add by duanyf 20121027 start
 2                 String type = Utils.ensureNotNull(intent.getType());
 3                 Log.d(TAG, "uri is " + uri);
 4                 if (uri.getScheme().equals("file") && (type.contains("image/"))) {
 5                     String path = uri.getEncodedPath();
 6                     Log.d(TAG, "path1 is " + path);
 7                     if (path != null) {
 8                         path = Uri.decode(path);
 9                         Log.d(TAG, "path2 is " + path);
10                         ContentResolver cr = this.getContentResolver();
11                         StringBuffer buff = new StringBuffer();
12                         buff.append("(")
13                                 .append(Images.ImageColumns.DATA)
14                                 .append("=")
15                                 .append("'" + path + "'")
16                                 .append(")");
17                         Cursor cur = cr.query(
18                                 Images.Media.EXTERNAL_CONTENT_URI,
19                                 new String[] { Images.ImageColumns._ID },
20                                 buff.toString(), null, null);
21                         int index = 0;
22                         for (cur.moveToFirst(); !cur.isAfterLast(); cur
23                                 .moveToNext()) {
24                             index = cur.getColumnIndex(Images.ImageColumns._ID);
25         

补充:移动开发 , Android ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,