Android中本地图片地址和Uri的相互装换

Android中本地图片地址和Uri的相互装换

前言:

项目中我们在用到手机中的相片的时候,因为需求不同,手机型号不同,我们需要将获取到的路径转成uri,或者将获取到的uri转成绝对路径。比如我的大华为G7,获取到的就是Uri,我要把它转成绝对地址。

获取到的:

content://media/external/images/media/212304
需要的:

file:///storage/emulated/0/Android/data/com.zn_android.zn/cache/PostPicture/20170905193015.jpg

通过查阅资料,找到了两个工具方法:

Uri转绝对路径:

/**
     * Gets the corresponding path to a file from the given content:// URI
     * 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 = {MediaStore.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;
    }

 
  

绝对路径转Uri:

/**
 * Gets the content:// URI from the given corresponding path to a file
 * 绝对路径转uri
 *
 * @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;
        }
    }
}



  • 5
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值