如何从相机获取图像Uri?

时间:2018-09-19 12:26:20

标签: android android-camera android-camera-intent

请帮助, 我如何从相机图片中获取URI我检查了一些文章,但不了解它的工作原理,请向我解释一下或提供一些与此主题相关的链接,这是我的代码:

    private void createDirectory() {
    directory = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "Meassure Preassure Pic");
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
    if (requestCode == REQUEST_CODE_PHOTO && resultCode == RESULT_OK) {
        if (intent != null && intent.getExtras() != null) {
            Bitmap imageBitmap = (Bitmap) intent.getExtras().get("data");
            ivPhoto.setImageBitmap(imageBitmap);
        }
    }
}
public void onClickPhoto(View view) {
    Intent pictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    if (pictureIntent.resolveActivity(getPackageManager()) != null) {
        startActivityForResult(pictureIntent, REQUEST_CODE_PHOTO);
    }
}

1 个答案:

答案 0 :(得分:0)

onActivityResult方法包含数据。首先,您需要检查数据是否为空,然后可以对返回的意图使用getdata()来获取URI。如果需要,您还可以获取所捕获图像的真实路径。下面是代码示例:

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == REQUEST_GALLERY_CODE && resultCode == Activity.RESULT_OK) {
        uri = data.getData();
        String filePath = getRealPathFromURIPath(uri, getActivity());
        File file = new File(filePath);
        Log.d(TAG, "Filename " + file.getName()); 
    }
}