Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: How to set the photo selected from gallery to a bitmap

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 :)

like image 852
Kinoscorpia Avatar asked Apr 22 '15 16:04

Kinoscorpia


People also ask

What is bitmap image in Android?

A bitmap (or raster graphic) is a digital image composed of a matrix of dots. When viewed at 100%, each dot corresponds to an individual pixel on a display. In a standard bitmap image, each dot can be assigned a different color. In this instance we will simply create a Bitmap directly: Bitmap b = Bitmap.


1 Answers

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);
}
like image 165
Akash Avatar answered Nov 16 '22 00:11

Akash