Uri的相互转换

文件File path(file:///)与content:// Uri的相互转换

1.content Uri to path

/** 
 * Gets the corresponding path to a file from the given content:// URI 
 * @param selectedVideoUri The content:// URI to find the file path from 
 * @param contentResolver The content resolver to use to perform the query. 
 * @return the file path as a string 
 */  
public static String getFilePathFromContentUri(Uri selectedVideoUri,ContentResolver     contentResolver) {  
    String filePath;  
    String[] filePathColumn = {MediaColumns.DATA};  
    Cursor cursor = contentResolver.query(selectedVideoUri, filePathColumn, null,null,null);  
  //      也可用下面的方法拿到cursor  
//      Cursor cursor = this.context.managedQuery(selectedVideoUri, filePathColumn, null, null, null);  
    cursor.moveToFirst();  
    int columnIndex = cursor.getColumnIndex(filePathColumn[0]);  
    filePath = cursor.getString(columnIndex);  
    cursor.close();  
    return filePath;  
}  

2.path to content Uri

/** 
 * Gets the content:// URI  from the given corresponding path to a file 
 * @param context 
 * @param imageFile 
 * @return content Uri 
 */  
public static Uri getImageContentUri(Context context, java.io.File imageFile) {  
       String filePath = imageFile.getAbsolutePath();  
       Cursor cursor = context.getContentResolver().query(  
               MediaStore.Images.Media.EXTERNAL_CONTENT_URI,  
               new String[] { MediaStore.Images.Media._ID },  
               MediaStore.Images.Media.DATA + "=? ",  
               new String[] { filePath }, null);  
       if (cursor != null && cursor.moveToFirst()) {  
           int id = cursor.getInt(cursor  
                   .getColumnIndex(MediaStore.MediaColumns._ID));  
           Uri baseUri = Uri.parse("content://media/external/images/media");  
           return Uri.withAppendedPath(baseUri, "" + id);  
       } else {  
           if (imageFile.exists()) {  
               ContentValues values = new ContentValues();  
               values.put(MediaStore.Images.Media.DATA, filePath);  
               return context.getContentResolver().insert(  
                       MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);  
           } else {  
               return null;  
           }  
       }  
   }  
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值