How can I allow the user to choose between capturing an image or selecting it from the gallery, and I want to know the type of the photo afterwards (PNG/JPG). I'm using this code but it is not working well.
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == getActivity().RESULT_OK) {
if (requestCode == REQUEST_CAMERA) {
Bitmap photo = (Bitmap) data.getExtras().get("data");
mImg.setImageBitmap(photo);
} else if (requestCode == SELECT_FILE) {
Uri selectedImageUri = data.getData();
String[] projection = {MediaStore.MediaColumns.DATA};
CursorLoader cursorLoader = new CursorLoader(getActivity(), selectedImageUri, projection, null, null,
null);
Cursor cursor = cursorLoader.loadInBackground();
int column_index = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA);
cursor.moveToFirst();
String selectedImagePath = cursor.getString(column_index);
Bitmap bm;
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(selectedImagePath, options);
final int REQUIRED_SIZE = 200;
int scale = 1;
while (options.outWidth / scale / 2 >= REQUIRED_SIZE
&& options.outHeight / scale / 2 >= REQUIRED_SIZE)
scale *= 2;
options.inSampleSize = scale;
options.inJustDecodeBounds = false;
bm = BitmapFactory.decodeFile(selectedImagePath, options);
mImg.setImageBitmap(bm);
mImg.setAlpha(1);
}
}
}
Call
getType()
on aContentResolver
, passing in theUri
.Delete most of what you have, as your
selectedImagePath
code will fail on most Android devices and you are decoding the bitmap on the main application thread. Use an image-loading library like Picasso to handle the image loading for you, asynchronous, including the scaling. Picasso can use theUri
directly without any of the flawedselectedImagePath
stuff. Then, all you need is thegetType()
call to get the MIME type of the image. Your entirerequestCode == SELECT_FILE
block will be replaced by 2-3 lines of code.You have to install Apache Commons Io Use FilenameUtils.getExtention() from this lib
i think this will help you