编辑
从图库获取照片的真实路径
本文访问次数:0

如何创建Intent从图库或者相机获取图片呢,以下为代码

// ...
// Within your enclosing Class
// ...
private static final int SELECT_PICTURE = 1;

// ... 

Intent pickIntent = new Intent();
pickIntent.setType("image/*");
pickIntent.setAction(Intent.ACTION_GET_CONTENT);

Intent takePhotoIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

String pickTitle = "Select or take a new Picture"; // Or get from strings.xml
Intent chooserIntent = Intent.createChooser(pickIntent, pickTitle);
chooserIntent.putExtra
(
  Intent.EXTRA_INITIAL_INTENTS, 
  new Intent[] { takePhotoIntent }
);

startActivityForResult(chooserIntent, SELECT_PICTURE);

接收到返回结果该如何处理呢

@Override
public void onActivityResult(int requestCode,int resultCode, Intent data) {
    switch (requestCode) {
        case SELECT_PICTURE:
            if(resultCode == Activity.RESULT_OK){
                try {
                    InputStream inputStream = getActivity().getContentResolver().openInputStream(data.getData());
                }catch (FileNotFoundException e){
                    e.printStackTrace();
                }

            }
            break;
    }
}

/**
* Get the real path of image uri.
*
* @param context  The context provide content resolver.
* @param imageUri The image uri to be solved.
* @return The real path of the image uri.
*/
public static String getImagePath(Context context, Uri imageUri) {
    String[] filePathColumn = {MediaStore.Images.Media.DATA};

    Cursor cursor = context.getContentResolver().query(imageUri,
            filePathColumn, null, null, null);
    if (cursor != null) {
        cursor.moveToFirst();
        int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
        String picturePath = cursor.getString(columnIndex);
        cursor.close();
        return picturePath;
    } else {
        return null;
    }
}

需要输入验证码才能留言

没有任何评论