Uri returned after ACTION_GET_CONTENT from gallery is not working in setImageURI() of ImageView

怎甘沉沦 提交于 2019-12-03 17:50:37

问题


I am fetching Uri of a image from gallery using

Intent intent = new Intent();  
intent.setType("image/*");  
intent.setAction(Intent.ACTION_GET_CONTENT);  
startActivityForResult(Intent.createChooser(intent, "Choose Picture"), requestCode);

and trying to display the image by

imageView.setImageURI(uri);

here, uri is Uri of the image received in onActivityResult by intent.getData().

but no image is being displayed. Also, for

File file=new File( uri.getPath() );

file.exists() is returning false.


回答1:


The problem is that you getting the Uri but from that uri you have to create Bitmap to show in your Imageview. There are various mechanism to do the same one among them is this code.

Intent intent = new Intent();  
intent.setType("image/*");  
intent.setAction(Intent.ACTION_GET_CONTENT);  
startActivityForResult(Intent.createChooser(intent, "Choose Picture"), 1);

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) 
{
    if(resultCode==RESULT_CANCELED)
    {
        // action cancelled
    }
    if(resultCode==RESULT_OK)
    {
        Uri selectedimg = data.getData();
        imageView.setImageBitmap(MediaStore.Images.Media.getBitmap(this.getContentResolver(), selectedimg));
    }
}



回答2:


Launch the Gallery Image Chooser

Intent intent = new Intent();
// Show only images, no videos or anything else
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
// Always show the chooser (if there are multiple options available)
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);

PICK_IMAGE_REQUEST is the request code defined as an instance variable.

private int PICK_IMAGE_REQUEST = 1;

Show Up the Selected Image in the Activity/Fragment

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {

        Uri uri = data.getData();

        try {
            Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
            // Log.d(TAG, String.valueOf(bitmap));

            ImageView imageView = (ImageView) findViewById(R.id.imageView);
            imageView.setImageBitmap(bitmap);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Your layout will need to have an ImageView like this:

<ImageView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/imageView" />


来源:https://stackoverflow.com/questions/9638455/uri-returned-after-action-get-content-from-gallery-is-not-working-in-setimageuri

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!