Android获取图片Uri/path

ANDROID 4.4以上:
@TargetApi(19)
private void handleImageOnKitKat(Intent data){
    String imagePath = null;
    Uri uri = data.getData();
    if(DocumentsContract.isDocumentUri(this,uri)){
        String docID = DocumentsContract.getDocumentId(uri);
        if("com.android.providers.media.documents".equals(uri.getAuthority()))
        {
            String id = docID.split(":")[1];
            String selection = MediaStore.Images.Media._ID + "=" +id;
            imagePath = getImagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,selection);
            }
        else if("com.android.providers.downloads.documents".equals(uri.getAuthority())){
            Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"),Long.valueOf(docID));
            imagePath = getImagePath(contentUri,null);
            }
        }
        else if("content".equalsIgnoreCase(uri.getScheme()))
            {
            imagePath = getImagePath(uri,null);
             }
        else if ("file".equalsIgnoreCase(uri.getScheme())){
            imagePath = uri.getPath();
         }
        displayImage(imagePath);
    }

4.4以下

private void handleImageBeforeKitKat(Intent data){
    Uri uri = data.getData();
    String imagePath = getImagePath(uri,null);
    displayImage(imagePath);

    }


getimagePath函数

private String getImagePath(Uri uri, String selection){
    String path = null;
    Cursor cursor = getContentResolver().query(uri,null,selection,null,null);
    if(cursor != null){
        path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
    }
    cursor.close();
    return path;

}

display函数

private void displayImage(String imagePath){
    if(imagePath != null){
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inSampleSize = 2;
        Bitmap bitmap = BitmapFactory.decodeFile(imagePath,options);
        showview.setImageBitmap(bitmap);
    }
    else{
        Toast.makeText(this,"failed to get image",Toast.LENGTH_SHORT).show();
    }
    }
}



你可能感兴趣的:(Android,android,图片,uri)