原文地址http://www.cnblogs.com/mytech-blog/p/3201549.html
1.将所有的图片路径取出,遍历比较找到需要的路径,取出URI,效率较低
其中 MediaStore.MediaColumns.DATA 字段存的就是图片的绝对路径,
最后mImageUri得到的就是图片的URI
Uri mUri = Uri.parse("content://media/external/images/media");
Uri mImageUri = null;
Cursor cursor = managedQuery(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, null, null, null,
MediaStore.Images.Media.DEFAULT_SORT_ORDER);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
String data = cursor.getString(cursor
.getColumnIndex(MediaStore.MediaColumns.DATA));
if (picPath.equals(data)) {
int ringtoneID = cursor.getInt(cursor
.getColumnIndex(MediaStore.MediaColumns._ID));
mImageUri = Uri.withAppendedPath(mUri, "" + ringtoneID);
break;
}
cursor.moveToNext();
}
2.直接从媒体数据库根据字段取出相应的记录,效率较高
//TYLT: add by duanyf 20121027 start
String type = Utils.ensureNotNull(intent.getType());
Log.d(TAG, "uri is " + uri);
if (uri.getScheme().equals("file") && (type.contains("image/"))) {
String path = uri.getEncodedPath();
Log.d(TAG, "path1 is " + path);
if (path != null) {
path = Uri.decode(path);
Log.d(TAG, "path2 is " + path);
ContentResolver cr = this.getContentResolver();
StringBuffer buff = new StringBuffer();
buff.append("(")
.append(Images.ImageColumns.DATA)
.append("=")
.append("'" + path + "'")
.append(")");
Cursor cur = cr.query(
Images.Media.EXTERNAL_CONTENT_URI,
new String[] { Images.ImageColumns._ID },
buff.toString(), null, null);
int index = 0;
for (cur.moveToFirst(); !cur.isAfterLast(); cur
.moveToNext()) {
index = cur.getColumnIndex(Images.ImageColumns._ID);
// set _id value
index = cur.getInt(index);
}
if (index == 0) {
//do nothing
} else {
Uri uri_temp = Uri
.parse("content://media/external/images/media/"
+ index);
Log.d(TAG, "uri_temp is " + uri_temp);
if (uri_temp != null) {
uri = uri_temp;
}
}
}
}
//TYLT: add by duanyf 20121027 end
3.直接根据路径通过 ContentProvider 的 delete() 方法删除图片,两行代码搞定,效率最高
1 String params[] = new String[]{filepath};
2 ctx.getContentResolver().delete(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, MediaStore.Images.Media.DATA + " LIKE ?", params);