Android 4.4從圖庫選擇圖片,獲取圖片路徑並裁剪

最近在作一個從圖庫選擇圖片或拍照,而後裁剪的功能.原本是沒問題的,一直在用java

Intent intent=new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

的方式來作,是調用系統圖庫來作,可是發現若是有圖片是同步到google相冊的話,圖庫裏面能看到一個auto backup的目錄,點進去選圖片的話是沒法獲取到圖片的路徑的.由於那些圖片根本就不存在於手機上.而後看到不管是百度貼吧,Instagram,或者還有些會選取圖片作修改的app,都是用一個很漂亮的圖片選擇器(4.4以上,4.3的仍是用系統舊的圖庫),而這個圖片選擇器能夠屏蔽掉那個auto backup的目錄.因此就開始打算用這個圖片選擇器來選圖片了.android

所以選擇下面的圖片選擇方式app

Intent intent=new Intent(Intent.ACTION_GET_CONTENT);//ACTION_OPEN_DOCUMENT  
intent.addCategory(Intent.CATEGORY_OPENABLE);  
intent.setType("image/*");  
if(android.os.Build.VERSION.SDK_INT>=android.os.Build.VERSION_CODES.KITKAT){                  
        startActivityForResult(intent, SELECT_PIC_KITKAT);    
}else{                
        startActivityForResult(intent, SELECT_PIC);   
}

爲何要分開不一樣版本呢?ide

其實在4.3或如下能夠直接用ACTION_GET_CONTENT的,在4.4或以上,官方建議用ACTION_OPEN_DOCUMENT,但其實都不算太大區別,區別是他們返回的Uri,若是使用上面pick的原生方法來選圖,返回的uri仍是正常的,但若是用ACTION_GET_CONTENT的方法,返回的uri跟4.3是徹底不同的,4.3返回的是帶文件路徑的,而4.4返回的倒是content://com.android.providers.media.documents/document/image:3951這樣的,沒有路徑,只有圖片編號的uri.這就致使接下來沒法根據圖片路徑來裁剪的步驟了.ui

還好找了不少方法,包括加權限啊什麼的,中間還試過用一些方法,本身的app沒崩潰,卻是讓系統圖庫崩潰了,引起了java.lang.SecurityException.google

Caused by: java.lang.SecurityException: Permission Denial: opening provider com.android.providers.media.MediaDocumentsProvider from ProcessRecord{437b5d88 9494:com.google.android.gallery3d/u0a20} (pid=9494, uid=10020) requires android.permission.MANAGE_DOCUMENTS or android.permission.MANAGE_DOCUMENTS

如下時4.4KITKAT的path路徑讀取方式
spa

public static String getPath(final Context context, final Uri uri) {

    final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;

    // DocumentProvider
    if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
       
        if (isExternalStorageDocument(uri)) {
            final String docId = DocumentsContract.getDocumentId(uri);
            final String[] split = docId.split(":");
            final String type = split[0];

            if ("primary".equalsIgnoreCase(type)) {
                return Environment.getExternalStorageDirectory() + "/" + split[1];
            }

            // TODO handle non-primary volumes
        }
        // 讀取下載到手機的文件
        else if (isDownloadsDocument(uri)) {

            final String id = DocumentsContract.getDocumentId(uri);
            final Uri contentUri = ContentUris.withAppendedId(
                    Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));

            return getDataColumn(context, contentUri, null, null);
        }
        // 讀取媒體文件
        else if (isMediaDocument(uri)) {
            final String docId = DocumentsContract.getDocumentId(uri);
            final String[] split = docId.split(":");
            final String type = split[0];

            Uri contentUri = null;
            if ("image".equals(type)) {
                contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
            } else if ("video".equals(type)) {
                contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
            } else if ("audio".equals(type)) {
                contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
            }

            final String selection = "_id=?";
            final String[] selectionArgs = new String[] {
                    split[1]
            };

            return getDataColumn(context, contentUri, selection, selectionArgs);
        }
    }
    // 讀取普通媒體文件或者通常的文件
    else if ("content".equalsIgnoreCase(uri.getScheme())) {

        // Return the remote address
        if (isGooglePhotosUri(uri))
            return uri.getLastPathSegment();
        return getDataColumn(context, uri, null, null);
    }
    // File
    else if ("file".equalsIgnoreCase(uri.getScheme())) {
        return uri.getPath();
    }

    return null;
}

/**
 * Android 4.4如下版本自動使用該方法
 * 
 * @param context The context.
 * @param uri The Uri to query.
 * @param selection (Optional) Filter used in the query.
 * @param selectionArgs (Optional) Selection arguments used in the query.
 * @return The value of the _data column, which is typically a file path.
 */
public static String getDataColumn(Context context, Uri uri, String selection,
        String[] selectionArgs) {

    Cursor cursor = null;
   
    final String[] projection = {
            MediaStore.Images.Media.DATA 
    };

    try {
        cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
                null);
        if (cursor != null && cursor.moveToFirst()) {
            final int index = cursor.getColumnIndexOrThrow(column);
            return cursor.getString(index);
        }
    } finally {
        if (cursor != null)
            cursor.close();
    }
    return null;
}


/**
 * @param uri The Uri to check.
 * @return Whether the Uri authority is ExternalStorageProvider.
 */
public static boolean isExternalStorageDocument(Uri uri) {
    return "com.android.externalstorage.documents".equals(uri.getAuthority());
}

/**
 * @param uri The Uri to check.
 * @return Whether the Uri authority is DownloadsProvider.
 */
public static boolean isDownloadsDocument(Uri uri) {
    return "com.android.providers.downloads.documents".equals(uri.getAuthority());
}

/**
 * @param uri The Uri to check.
 * @return Whether the Uri authority is MediaProvider.
 */
public static boolean isMediaDocument(Uri uri) {
    return "com.android.providers.media.documents".equals(uri.getAuthority());
}

/**
 * @param uri The Uri to check.
 * @return Whether the Uri authority is Google Photos.
 */
public static boolean isGooglePhotosUri(Uri uri) {
    return "com.google.android.apps.photos.content".equals(uri.getAuthority());
}

以上文章轉載自CSDN博客 Android 4.4從圖庫選擇圖片,獲取圖片路徑並裁剪.net

(本文略有刪減,並改造了原做者的表達方式)3d

相關文章
相關標籤/搜索