Gallery intent tutorial


SDK Version: 
M3

Our goal is to start the users gallery application, allow him to select an image, and use the chosen image in our application.

API Level 3 required!

We will start the operation on a buttons onclick event, implemented as follows:

  1. private static Bitmap Image = null;
  2. private static Bitmap rotateImage = null;
  3. private ImageView imageView;
  4. private static final int GALLERY = 1;

  1. public void onClick(View v) {
  2.   imageView.setImageBitmap(null);
  3.   if (Image != null)
  4.     Image.recycle();
  5.   Intent intent = new Intent();
  6.   intent.setType("image/*");
  7.   intent.setAction(Intent.ACTION_GET_CONTENT);
  8.   startActivityForResult(Intent.createChooser(intent, "Select Picture"), GALLERY);
  9. }

In order to avoid out of memory errors, we must recycle the previous image when the user presses the button second times or after that, so the returned bitmap is stored as a member variable, so we still have a reference for it when it is needs to be recycled.

select_picturegellery_app

We process the result in the onActivityResult method, which is called automatically when the gallery is finished.

  1. protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  2.   if (requestCode == GALLERY && resultCode != 0) {
  3.     Uri mImageUri = data.getData();        
  4.     try {
  5.   Image = Media.getBitmap(this.getContentResolver(), mImageUri);
  6.         if (getOrientation(getApplicationContext(), mImageUri) != 0) {
  7.           Matrix matrix = new Matrix();
  8.           matrix.postRotate(getOrientation(getApplicationContext(), mImageUri));
  9.           if (rotateImage != null)
  10.             rotateImage.recycle();
  11.           rotateImage = Bitmap.createBitmap(Image, 0, 0, Image.getWidth(), Image.getHeight(), matrix,true);
  12.           imageView.setImageBitmap(rotateImage);
  13.         } else
  14.           imageView.setImageBitmap(Image);        
  15.       } catch (FileNotFoundException e) {
  16.         e.printStackTrace();
  17.       } catch (IOException e) {
  18.         e.printStackTrace();
  19.       }
  20.     }
  21.   }

The getOrientation method, used above returns the angle the image was taken. So if it was made with a rotated phone we must rotate the image before we can correctly display it in an ImageView. It can me implemented with the help of the Android MediaStore.

  1. public static int getOrientation(Context context, Uri photoUri) {
  2.     Cursor cursor = context.getContentResolver().query(photoUri,
  3.         new String[] { MediaStore.Images.ImageColumns.ORIENTATION },null, null, null);
  4.  
  5.     if (cursor.getCount() != 1) {
  6.       return -1;
  7.     }
  8.     cursor.moveToFirst();
  9.     return cursor.getInt(0);
  10.   }

chosen_image

Download code: LINK