Get Image from the Gallery and Show in ImageView

119,642

Solution 1

you can try this.

paste this code in your button click event.

Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, RESULT_LOAD_IMG);

and below code is your on activity result

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


        if (resultCode == RESULT_OK) {
            try {
                final Uri imageUri = data.getData();
                final InputStream imageStream = getContentResolver().openInputStream(imageUri);
                final Bitmap selectedImage = BitmapFactory.decodeStream(imageStream);
                image_view.setImageBitmap(selectedImage);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
                Toast.makeText(PostImage.this, "Something went wrong", Toast.LENGTH_LONG).show();
            }

        }else {
            Toast.makeText(PostImage.this, "You haven't picked Image",Toast.LENGTH_LONG).show();
        }
    }

I hope it is helpful for you.

Solution 2

I use this code: This code used to start gallery activity.

 Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
 photoPickerIntent.setType("image/*");
 startActivityForResult(photoPickerIntent, GALLERY_REQUEST);

And get the result in:

 @Override
     public void onActivityResult(int requestCode, int resultCode, Intent data) {
         super.onActivityResult(requestCode, resultCode, data);
         if(resultCode == Activity.RESULT_OK)
         switch (requestCode){
             case GALLERY_REQUEST:
                 Uri selectedImage = data.getData();
                 try {
                     Bitmap bitmap = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), selectedImage);
                     carImage.setImageBitmap(bitmap);
                 } catch (IOException e) {
                     Log.i("TAG", "Some exception " + e);
                 }
                 break;
         }
     }

And don't forget to declare permission in AndroidManifest.

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

Solution 3

Because OnActivityResult method is deprecated, proper way nowadays with AndroidX Activity, is Activity Result APIs, and that recommended way, see docs

"registerForActivityResult() takes an ActivityResultContract and an ActivityResultCallback and returns an ActivityResultLauncher which you’ll use to launch the other activity."

ActivityResultLauncher<String> mGetContent = registerForActivityResult(new ActivityResultContracts.GetContent(),
    new ActivityResultCallback<Uri>() {
        @Override
        public void onActivityResult(Uri uri) {
            previewImage.setImageURI(uri);
        }
     });

And simply call

mGetContent.launch("image/*");

when needed.

Solution 4

I try all the solutions above but they don't work for me . I saw a code from tutorialspoint website and it works for me very well this is the code :

    final int PICK_IMAGE = 100;

    Button button = findViewById(R.id.button33);
    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent gallery = new Intent(Intent.ACTION_PICK,
             MediaStore.Images.Media.INTERNAL_CONTENT_URI);
             startActivityForResult(gallery, PICK_IMAGE);
        }
    });


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

    Uri imageUri;
    ImageView imageView = findViewById(R.id.image_main_galary);

    if (resultCode == RESULT_OK && reqCode == 100){
        imageUri = data.getData();
        imageView.setImageURI(imageUri);
    }
    }

the most important issue : don't forget PERMISSION :

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
Share:
119,642
Android Nerd
Author by

Android Nerd

Updated on August 10, 2021

Comments

  • Android Nerd
    Android Nerd almost 3 years

    I need to get an image from the gallery on a button click and show it into the imageview.

    I am doing it in the following way:

        btn_image_button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
    
                getImageFromAlbum();
            }
        });
    

    The method Definition is as:

       private void getImageFromAlbum(){
        try{
            Intent i = new Intent(Intent.ACTION_PICK,
                    android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            startActivityForResult(i, RESULT_LOAD_IMAGE);
        }catch(Exception exp){
            Log.i("Error",exp.toString());
        }
    }
    

    The activity result method is

      @Override
      protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
            Uri selectedImage = data.getData();
            String[] filePathColumn = { MediaStore.Images.Media.DATA };
    
            Cursor cursor = getContentResolver().query(selectedImage,
                    filePathColumn, null, null, null);
            cursor.moveToFirst();
    
            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            String picturePath = cursor.getString(columnIndex);
            cursor.close();
    
            try {
                bmp = getBitmapFromUri(selectedImage);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
    
            image_view.setImageBitmap(bmp);
    
            //to know about the selected image width and height
            Toast.makeText(MainActivity.this, image_view.getDrawable().getIntrinsicWidth()+" & "+image_view.getDrawable().getIntrinsicHeight(), Toast.LENGTH_SHORT).show();
        }
    
    }
    

    The Problem

    The problem I am facing is when the image resolution is high suppose that if the image size is of 5mp to 13mp. It won't loads up and show up into the image view.

    But the images with the low width and height are successfully loading into the image view!

    Can somebody tell me any issues with the code and what I am doing wrong? I just want to import the camera images from the gallery and show them in the image view!

  • Regular Jo
    Regular Jo over 7 years
    Thank you Anton for providing an answer on StackOverflow. You can do a great deal for the quality of your answer by explaining the steps or the reasons for them. Still, have an upvote.
  • Anton Molchan
    Anton Molchan over 6 years
    @D.Desai Do you use this in Fragment? If you want use this code in activity delete "getActivity()"
  • Varun Chandran
    Varun Chandran over 5 years
    getting rotated image?
  • Erkan
    Erkan almost 4 years
    Yes I'm facing the same problem.The image is randomly rotated.
  • niedev
    niedev almost 4 years
    If you have rotation problem check my answer: stackoverflow.com/a/64013845/8491926
  • danial iranpour
    danial iranpour over 2 years
    @Anton This one worked for me, thank you.