can i get image file width and height from uri in android?

前端 未结 10 2113
深忆病人
深忆病人 2020-12-08 01:58

i can getting the image width through MediaStore.Images.Media normally

but i need to getting the image width and height from image which selected from d

10条回答
  •  独厮守ぢ
    2020-12-08 02:55

    In addition to @Blackbelt answer you should use the following code to retrieve file path from Uri:

    public static String getPathFromURI(Context context, Uri contentUri) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT &&
                DocumentsContract.isDocumentUri(context, contentUri)) {
            return getPathForV19AndUp(context, contentUri);
        } else {
            return getPathForPreV19(context, contentUri);
        }
    }
    
    private static String getPathForPreV19(Context context, Uri contentUri) {
        String[] projection = { MediaStore.Images.Media.DATA };
        Cursor cursor = context.getContentResolver().query(contentUri, projection, null, null, null);
        if (cursor != null && cursor.moveToFirst()) {
            try {
                int columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                return cursor.getString(columnIndex);
            } finally {
                cursor.close();
            }
        }
    
        return null;
    }
    
    @TargetApi(Build.VERSION_CODES.KITKAT)
    private static String getPathForV19AndUp(Context context, Uri contentUri) {
        String documentId = DocumentsContract.getDocumentId(contentUri);
        String id = documentId.split(":")[1];
    
        String[] column = { MediaStore.Images.Media.DATA };
        String sel = MediaStore.Images.Media._ID + "=?";
        Cursor cursor = context.getContentResolver().
                query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                        column, sel, new String[]{ id }, null);
    
        if (cursor != null) {
            try {
                int columnIndex = cursor.getColumnIndex(column[0]);
                if (cursor.moveToFirst()) {
                    return cursor.getString(columnIndex);
                }
            } finally {
                cursor.close();
            }
        }
    
        return null;
    }
    

提交回复
热议问题