10

I am asking the user for the access to the gallery through the code as a listener here:

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

However, I am confused as to how I would set a variable to the photo selected.

Where would I put the code to set a variable as the photo selected?

Thanks :)

ישו אוהב אותך
  • 28,609
  • 11
  • 78
  • 96
Kinoscorpia
  • 368
  • 3
  • 6
  • 18

4 Answers4

20

First you have to override onActivityResult to get the uri of the file selected image

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
    if (requestCode == SELECT_PHOTO) {

        if (resultCode == RESULT_OK) {
            if (intent != null) {
                // Get the URI of the selected file
                final Uri uri = intent.getData();
                useImage(uri);                   
              }
        }
       super.onActivityResult(requestCode, resultCode, intent);

    }
}

Then define useImage(Uri) to use the image

void useImage(Uri uri)
{
 Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), uri);
 //use the bitmap as you like
 imageView.setImageBitmap(bitmap);
}
Akash
  • 13,107
  • 1
  • 25
  • 19
13

You can do it like this.

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

    // Here we need to check if the activity that was triggers was the Image Gallery.
    // If it is the requestCode will match the LOAD_IMAGE_RESULTS value.
    // If the resultCode is RESULT_OK and there is some data we know that an image was picked.
    if (requestCode == LOAD_IMAGE_RESULTS && resultCode == RESULT_OK && data != null) {
        // Let's read picked image data - its URI
        Uri pickedImage = data.getData();
        // Let's read picked image path using content resolver
        String[] filePath = { MediaStore.Images.Media.DATA };
        Cursor cursor = getContentResolver().query(pickedImage, filePath, null, null, null);
        cursor.moveToFirst();
        String imagePath = cursor.getString(cursor.getColumnIndex(filePath[0]));

        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inPreferredConfig = Bitmap.Config.ARGB_8888;
        Bitmap bitmap = BitmapFactory.decodeFile(imagePath, options);

         // Do something with the bitmap


        // At the end remember to close the cursor or you will end with the RuntimeException!
        cursor.close();
    }
}
Bojan Kseneman
  • 15,488
  • 2
  • 54
  • 59
  • But where should I put this? Just in onCreate or should I put this in the listener for the button to select it? – Kinoscorpia Apr 22 '15 at 17:22
  • If i wanted to save the bitmp it created, could I create a variable at the start of the class called bitmap and then just say "bitmap = BitmapFactory.decodeFile(imagePath, options);"? – Kinoscorpia Apr 22 '15 at 18:05
  • Also, thank you for clarifying and helping me out :) – Kinoscorpia Apr 22 '15 at 18:05
  • I am not sure I understand your comment question. But the image you get back from galerry is already saved that is why you get back the path pointing to that image. You can copy the file directly if you need it. But reading it into bitmap might be more usefull... It depends on what you want to do – Bojan Kseneman Apr 22 '15 at 18:15
  • imagePath I am getting is null and so my bitmap is also null applying the above approach. What could be the reason for it? – Priyavrat Talyan Feb 24 '23 at 07:13
3

Alternative for Akash Kurian Jose answer

Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), uri);

I always use

fun getBitmap(file: Uri, cr: ContentResolver): Bitmap?{
            var bitmap: Bitmap ?= null
            try {
                val inputStream = cr.openInputStream(file)
                bitmap = BitmapFactory.decodeStream(inputStream)
                // close stream
                try {
                    inputStream.close()
                } catch (e: IOException) {
                    e.printStackTrace()
                }

            }catch (e: FileNotFoundException){}
            return bitmap
        }

It works both for photos from gallery and photos from camera.

Larger issue about it: Picasso unable to display image from Gallery

Open Gallery using this method:

private void openGallery(){
    if (Build.VERSION.SDK_INT <19){
        Intent intent = new Intent(); 
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(Intent.createChooser(intent, getResources().getString(R.string.select_picture)),GALLERY_INTENT_CALLED);
    } else {
        Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        intent.setType("image/*");
        startActivityForResult(intent, GALLERY_KITKAT_INTENT_CALLED);
    }
}

Then you are able to read convert Uri to Bitmap using afromentioned ContentResolver.openInputStream or set image ImageView.setImageUri(Uri)

murt
  • 3,790
  • 4
  • 37
  • 48
2

If you want to display the selected image to any particular ImageView. Suppose we have RC_PHOTO_PICKER = 1 then these lines of code should do the magic

private void openPhotoPicker() {
    Intent photoPickerIntent = new Intent(Intent.ACTION_GET_CONTENT);
    photoPickerIntent.setType("image/*");
    photoPickerIntent.putExtra(Intent.EXTRA_LOCAL_ONLY, false);
    startActivityForResult(Intent.createChooser(photoPickerIntent,"Complete Action Using"), RC_PHOTO_PICKER);
}

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

    if (requestCode == RC_PHOTO_PICKER && resultCode == RESULT_OK && data != null) {
        Uri pickedImage = data.getData();
        //set the selected image to ImageView
        mImageView.setImageURI(pickedImage);
    }
}

And simply call the openPhotoPicker() method afterwards

Lee Royld
  • 75
  • 9