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.
We process the result in the onActivityResult method, which is called automatically when the gallery is finished.
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.
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.
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == GALLERY && resultCode != 0) {
Uri mImageUri = data.getData();
try {
if (getOrientation(getApplicationContext(), mImageUri) != 0) {
Matrix matrix = new Matrix();
matrix.postRotate(getOrientation(getApplicationContext(), mImageUri));
if (rotateImage != null)
rotateImage.recycle();
imageView.setImageBitmap(rotateImage);
} else
e.printStackTrace();
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.
if (cursor.getCount() != 1) {
return -1;
}
cursor.moveToFirst();
return cursor.getInt(0);
}
0 comments:
Post a Comment