Gallery intent tutorial in Android


Chaunri | 10:33 AM | ,

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:

private static Bitmap Image = null;
private static Bitmap rotateImage = null;
private ImageView imageView;
private static final int GALLERY = 1;
public void onClick(View v) {
  imageView.setImageBitmap(null);
  if (Image != null)
    Image.recycle();
  Intent intent = new Intent();
  intent.setType("image/*");
  intent.setAction(Intent.ACTION_GET_CONTENT);
  startActivityForResult(Intent.createChooser(intent, "Select Picture"), GALLERY);
}


n 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.
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  if (requestCode == GALLERY && resultCode != 0) {
    Uri mImageUri = data.getData();        
    try {
  Image = Media.getBitmap(this.getContentResolver(), mImageUri);
        if (getOrientation(getApplicationContext(), mImageUri) != 0) {
          Matrix matrix = new Matrix();
          matrix.postRotate(getOrientation(getApplicationContext(), mImageUri));
          if (rotateImage != null)
            rotateImage.recycle();
          rotateImage = Bitmap.createBitmap(Image, 0, 0, Image.getWidth(), Image.getHeight(), matrix,true);
          imageView.setImageBitmap(rotateImage);
        } else
          imageView.setImageBitmap(Image);        
      } catch (FileNotFoundException e) {
        e.printStackTrace();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
  }


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.
public static int getOrientation(Context context, Uri photoUri) {
    Cursor cursor = context.getContentResolver().query(photoUri,
        new String[] { MediaStore.Images.ImageColumns.ORIENTATION },null, null, null);
 
    if (cursor.getCount() != 1) {
      return -1;
    }
    cursor.moveToFirst();
    return cursor.getInt(0);
  }
 
chosen_image
Download code: LINK
 

0 comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...